summaryrefslogtreecommitdiff
path: root/src/remote-proxy.c
blob: 78cf216cfbb09bd69596f2eeed9106cb156ec18c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
/*
 * Copyright © 2012 Intel Corporation
 *
 * Permission to use, copy, modify, distribute, and sell this software and
 * its documentation for any purpose is hereby granted without fee, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of the copyright holders not be used in
 * advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.  The copyright holders make
 * no representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
 * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <linux/input.h>
#include <sys/uio.h>
#include <assert.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <zlib.h>

#include <wayland-server.h>
#include <wayland-client.h>
#include "compositor.h"

#include "../shared/os-compatibility.h"

#include "remote-stream.h"
#include "remote-client-protocol.h"

/*
 * - Don't abuse weston_seat, weston_output etc.
 *
 * - Encapsulate fd users in abstract objects?  wl_buffer,
 *   wl_keyboard_map... idea is to keep most of core protocol the
 *   same, but allow the out of band usage to be encapsulated.
 *
 * - Minimize shm update regions.
 *
 * - Surface enter/leave.
 *
 */

struct remote {
	struct weston_compositor *compositor;
	struct wl_listener destroy_listener;
	struct wl_display *display;
	struct wl_registry *registry;
	struct wl_list surface_list;
	struct wl_compositor *remote_compositor;
	struct wl_shell *shell;
	struct wl_event_source *source;
	uint32_t event_mask;

	int protocol_fd[2];
	char protocol_buffer[4096];
	struct wl_event_source *protocol_source;
	struct remote_stream *stream;
	struct remote *proxy_remote;

	struct remote_stream_block protocol_stream_block;
};

struct remote_output {
	struct weston_output output;
	struct remote *remote;
	struct wl_output *proxy;
};

struct remote_seat {
	struct wl_seat seat;
	struct remote *remote;
	struct wl_seat *proxy;
	struct wl_pointer *proxy_pointer;
	struct wl_keyboard *proxy_keyboard;
	uint32_t enter_serial;
	struct wl_pointer pointer;
	struct wl_keyboard keyboard;

	int keymap_fd;
	void *keymap_area;
	size_t keymap_size;
};

struct shell_surface {
	struct wl_resource resource;
	struct weston_surface *surface;
};

struct remote_surface {
	struct weston_surface *surface;
	struct wl_surface *proxy;
	struct wl_shell_surface *proxy_shell_surface;

	struct shell_surface *shell_surface;

	struct remote *remote;
	struct wl_buffer *proxy_buffer;
	struct buffer_hash *buffer;
	void *map, *zipped;
	int width, height;
	int encoded_length;

	uint32_t remote_ping_serial;
	uint32_t subst_ping_serial;

	struct wl_listener destroy_listener;

	const struct wl_surface_interface *interface;
	const struct wl_shell_surface_interface *shell_surface_interface;

	struct remote_stream_block stream_block;
};

static struct remote_seat *
is_remote_seat(struct wl_resource *resource);

static void
destroy_remote(struct wl_listener *listener, void *data);

static int
keymap_tag_handler(struct remote_stream *stream,
		   size_t remain, void *data)
{
	struct remote_seat *seat = data;
	int len;

	if (stream->len == 0) {
		seat->keymap_size = stream->total;
		seat->keymap_fd =
			os_create_anonymous_file(seat->keymap_size);
		seat->keymap_area = mmap(NULL, seat->keymap_size,
					 PROT_READ | PROT_WRITE,
					 MAP_SHARED,
					 seat->keymap_fd, 0);
	}

	len = read(stream->fd, seat->keymap_area + stream->len, remain);
	if (len < 0)
		return -1;

	stream->len += len;

	return len;
}

static int
stream_data(int fd, uint32_t mask, void *data)
{
	struct remote *remote = data;
	int ret;

	if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) {
		fprintf(stderr, "stream_data: hangup\n");
		destroy_remote(&remote->destroy_listener, NULL);
		return 1;
	}

	if (mask & WL_EVENT_WRITABLE) {
		ret = remote_stream_write(remote->stream);
		if (ret == 0) {
			wl_event_source_fd_update(remote->source,
						  WL_EVENT_READABLE);
			wl_event_source_fd_update(remote->stream->source,
						  WL_EVENT_READABLE);
		} else if (ret == -1 && errno != EAGAIN) {
			fprintf(stderr, "other error: %m\n");
		}
	}

	if (mask & WL_EVENT_READABLE)
		remote_stream_read(remote->stream);

	return 1;
}
 
static int
protocol_data(int fd, uint32_t mask, void *data)
{
	struct remote *remote = data;
	struct remote_stream_block *block;
	int len, ret;

	if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) {
		fprintf(stderr, "stream_data: hup/err in protocol_data\n");
		return -1;
	}

	len = read(fd, remote->protocol_buffer,
		   sizeof remote->protocol_buffer);
	if (len == -1 && errno == EAGAIN) {
		return 1;
	} else if (len == -1) {
		fprintf(stderr, "read error: %m\n");
		return -1;
	}

	block = &remote->protocol_stream_block;
	wl_list_insert(&remote->stream->block_queue, &block->link);
	block->tag = 0;
	block->written = 0;
	block->size = len;
	block->data = remote->protocol_buffer;

	ret = remote_stream_write(remote->stream);
	if (ret == -1 && errno == EAGAIN) {
		wl_event_source_fd_update(remote->source, 0);
		wl_event_source_fd_update(remote->stream->source,
					  WL_EVENT_READABLE |
					  WL_EVENT_WRITABLE);
	} else if (ret == -1) {
		fprintf(stderr, "other error: %m\n");
	}

	return 1;
}

static int
protocol_tag_handler(struct remote_stream *stream, size_t remain, void *data)
{
	struct remote *remote = data;
	char buffer[4096];
	int len;

	if (remain > sizeof buffer)
		len = sizeof buffer;
	else
		len = remain;

	len = read(stream->fd, buffer, len);
	stream->len += len;
	write(remote->protocol_fd[0], buffer, len);

	return 1;
}

static struct remote_stream *
remote_stream_connect(struct remote *remote,
		      const char *hostname, int port)
{
	struct wl_event_loop *loop =
		wl_display_get_event_loop(remote->compositor->wl_display);
	struct remote_stream *stream;
	struct sockaddr_in name;
	struct hostent *hostinfo;

	stream = malloc(sizeof *stream);
	if (stream == NULL)
		return NULL;

	memset(stream, 0, sizeof *stream);
	stream->tag_handler[0].func = protocol_tag_handler;
	stream->tag_handler[0].data = remote;
	stream->tag = 1;
	stream->tag_handler_count = 1;
	wl_list_init(&stream->block_queue);

	hostinfo = gethostbyname(hostname);
	if (hostinfo == NULL) {
		weston_log("Unknown host %s.\n", hostname);
		free(stream);
		return NULL;
	}

	name.sin_family = AF_INET;
	name.sin_port = htons(port);
	name.sin_addr = *(struct in_addr *) hostinfo->h_addr;

	stream->fd = socket(PF_INET,
			    SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
	if (stream->fd < 0) {
		weston_log("Failed to create socket for remote stream: %m.\n");
		free(stream);
		return NULL;
	}
	
	if (connect(stream->fd, (struct sockaddr *) &name, sizeof name) < 0 &&
	    errno != EINPROGRESS) {
		weston_log("Could not connect to remote server: %m.\n");
		return NULL;
	}

	/* FIXME: Poll socket for writability, check for error with
	 * getsockopt for SO_ERROR, level SOL_SOCKET. */

	stream->source =
		wl_event_loop_add_fd(loop, stream->fd,
				     WL_EVENT_READABLE, stream_data, remote);

	return stream;
}

static void
surface_enter(void *data,
	      struct wl_surface *wl_surface, struct wl_output *wl_output)
{
}

static void
surface_leave(void *data,
	      struct wl_surface *wl_surface, struct wl_output *output)
{
}

static const struct wl_surface_listener surface_listener = {
	surface_enter,
	surface_leave
};

static void
shell_surface_handle_ping(void *data, struct wl_shell_surface *shell_surface,
			  uint32_t serial)
{
	struct remote_surface *surface = data;
	struct weston_compositor *compositor = surface->remote->compositor;

	surface->remote_ping_serial = serial;
	surface->subst_ping_serial =
		wl_display_get_serial(compositor->wl_display);
	wl_shell_surface_send_ping(&surface->shell_surface->resource,
				   surface->subst_ping_serial);
}

static void
shell_surface_handle_configure(void *data,
			       struct wl_shell_surface *shell_surface,
			       uint32_t edges, int32_t width, int32_t height)
{
	struct remote_surface *surface = data;

	wl_shell_surface_send_configure(&surface->shell_surface->resource,
					edges, width, height);
}

static void
shell_surface_handle_popup_done(void *data,
				struct wl_shell_surface *shell_surface)
{
}

static const struct wl_shell_surface_listener shell_surface_listener = {
	shell_surface_handle_ping,
	shell_surface_handle_configure,
	shell_surface_handle_popup_done
};

static void
resize_buffer(struct remote_surface *surface)
{
	struct remote *remote = surface->remote;
	struct weston_surface *es = surface->surface;
	struct wl_buffer *buffer = es->pending.buffer;
	int stride, size;
	uint32_t format;

	if (surface->proxy_buffer != NULL &&
	    buffer != NULL &&
	    surface->width == buffer->width &&
	    surface->height == buffer->height)
		return;

	if (surface->proxy_buffer != NULL)
		wl_buffer_destroy(surface->proxy_buffer);

	if (buffer == NULL) {
		wl_surface_attach(surface->proxy, NULL, 0, 0);
		return;
	}

	stride = buffer->width * 4;
	size = stride * buffer->height;

	/* Assume ARGB for now */
	format = REMOTE_FORMAT_ARGB8888;

	surface->width = buffer->width;
	surface->height = buffer->height;
	surface->map = malloc(size);

	surface->zipped = malloc(size);

	surface->proxy_buffer =
		remote_create_buffer(remote->proxy_remote,
				     buffer->width, buffer->height, format);

	wl_surface_attach(surface->proxy, surface->proxy_buffer,
			  es->pending.sx, es->pending.sy);
}

struct entry {
	int count;
	int matches;
	uint32_t hash;
	int x, y;
	int index;
};

struct buffer_hash {
	void *data;
	struct entry *table;
	int width, height, stride;
	int block_stride, length, block_count, shift;
	int stats[5];
	int clashes;
};

static const uint32_t prime = 0x1f821e2d;
static const uint32_t end_prime = 0xf907ec81;	/* prime^size */
#if 0
static const uint32_t vprime = 0x0137b89d;
static const uint32_t end_vprime = 0xaea9a281;	/* vprime^size */
#else
static const uint32_t vprime = 0xf907ec81;
static const uint32_t end_vprime = 0xcdb99001;	/* vprime^size */
#endif
static const uint32_t step = 0x0ac93019;
static const int size = 32, mask = 31;

static int
verify_match(struct buffer_hash *bh, int x, int y,
	     struct buffer_hash *prev, struct entry *entry)
{
       int i;
       void *old, *match;

       if (x + size > bh->width || y + size > bh->height)
               return 0;

       for (i = 0; i < size; i++) {
	       match = bh->data + (y + i) * bh->stride + x * 4;
	       old = prev->data + (entry->y + i) * prev->stride + entry->x * 4;
               if (memcmp(match, old, size * 4) != 0) {
		       bh->clashes++;
		       return 0;
	       }
       }

       return 1;
}

static void
insert_block(struct buffer_hash *bh, uint32_t h, int x, int y)
{
	struct entry *entry;
	int i;
	uint32_t collision = 0;

	entry = &bh->table[h >> bh->shift];
	for (i = step; entry->count > 0 && entry->hash != h; i += step) {
		entry = &bh->table[(h + i) >> bh->shift];
		collision++;
	}

	entry->hash = h;
	entry->count++;
	entry->x = x;
	entry->y = y;
	entry->index = (bh->block_stride * y + x) / size;

	if (collision > ARRAY_LENGTH(bh->stats) - 1)
		collision = ARRAY_LENGTH(bh->stats) - 1;
	bh->stats[collision]++;
}

static struct entry *
lookup_block(struct buffer_hash *prev, uint32_t h)
{
	uint32_t i;
	struct entry *entry;
	int shift = prev->shift;

	for (i = h;
	     entry = &prev->table[i >> shift], entry->count > 0;
	     i += step)
		if (entry->hash == h)
			return entry;

	return NULL;
}

struct encoder {
	uint32_t color;
	uint32_t color_run;
	uint32_t delta;
	uint32_t delta_run;
	void *data;
	int bytes;
};

/* Encoding:
 *
 *  - all 1 pixel colors are encoded literally
 *
 *  - using premultiplied alpha lets us use colors with alpha 0 and
 *    non-zero color components as special codes:
 *
 *     - 0x00 00 00 00 : one alpha 0 pixel
 *     - 0xaa rr gg bb : one color pixel, alpha > 0
 *     - 0x00 1x xx xx : delta 0 run, x is length, (20 bits)
 *     - 0x00 2x xx xx : block ref, block number x (20 bits)
 *     - 0x00 3x xx xx 0xaarrggbb : solid color run, length x
 *     - 0x00 4x xx xx 0xaarrggbb : delta run, length x
 *
 */

static void
emit(struct encoder *encoder, uint32_t symbol)
{
	*(uint32_t *) (encoder->data + encoder->bytes) = symbol;
	encoder->bytes += 4;
}

static void
encode_pixel(struct encoder *encoder, uint32_t color, uint32_t delta)
{
	if ((encoder->color != color &&
	     encoder->color_run > encoder->delta_run) ||

	    (encoder->delta != delta &&
	     encoder->delta_run > encoder->color_run) ||

	    (encoder->delta != delta && encoder->color != color)) {

		if (encoder->color_run >= encoder->delta_run) {
			if (encoder->color_run == 1) {
				emit(encoder, encoder->color);
			} else {
				emit(encoder, 0x00300000 | encoder->color_run);
				emit(encoder, encoder->color);
			}
		} else {
			if (encoder->delta == 0) {
				emit(encoder, 0x00100000 | encoder->delta_run);
			} else {
				emit(encoder, 0x00400000 | encoder->delta_run);
				emit(encoder, encoder->delta);
			}
		}

		encoder->color_run = 1;
		encoder->color = color;
		encoder->delta_run = 1;
		encoder->delta = delta;
		return;
	}

	if (encoder->color == color) {
		encoder->color_run++;
	} else {
		encoder->color_run = 1;
		encoder->color = color;
	}

	if (encoder->delta == delta) {
		encoder->delta_run++;
	} else {
		encoder->delta_run = 1;
		encoder->delta = delta;
	}
}

static void
encode_block(struct encoder *encoder, struct entry *entry, int x, int y)
{
	/* 0x00 2x xx xx 0x xxxx yyyy:
	 *	block ref, block number x (20 bits) at x, y */

	/* FIXME: Maybe don't encode pixels under blocks and just emit
	 * blocks at their position within the stream. */

	emit(encoder, 0x00200000 | entry->index);
	emit(encoder, (x << 16) | y);
}

static void
destroy_buffer(struct buffer_hash *bh)
{
	free(bh->data);
	free(bh->table);
	free(bh);
}

static struct buffer_hash *
create_buffer(int width, int height)
{
	struct buffer_hash *bh;

	bh = malloc(sizeof *bh);
	bh->width = width;
	bh->stride = width * 4;
	bh->height = height;

	bh->block_stride = (width + size - 1) / size;
	bh->block_count =
		bh->block_stride * ((height + size - 1) / size);
	bh->length = 1 << (31 - __builtin_clz(bh->block_count * 4));
	bh->shift = __builtin_clz(bh->length) + 1;

	bh->table = malloc(bh->length * sizeof bh->table[0]);
	memset(bh->table, 0, bh->length * sizeof bh->table[0]);

	memset(bh->stats, 0, sizeof bh->stats);
	bh->clashes = 0;

	bh->data = malloc(bh->stride * height);

	return bh;
}

static int
encode_buffer(struct buffer_hash *bh, struct buffer_hash *prev, void *data)
{
	struct entry *entry;
	int i, j, k;
	int x0, x1, y0, y1;
	uint32_t *block_hashes;
	uint32_t hash, bottom_hash, h, *line, *bottom, *prev_line;
	int width, height;
	struct encoder encoder;
	int *skyline, skyline_pixels;
	int matches;

	width = bh->width;
	height = bh->height;
	x0 = 0;
	x1 = width;
	y0 = 0;
	y1 = height;

	skyline = malloc((width + size) * sizeof skyline[0]);
	memset(skyline, 0, width * sizeof skyline[0]);

	block_hashes = malloc(width * sizeof block_hashes[0]);
	memset(block_hashes, 0, width * sizeof block_hashes[0]);

	matches = 0;
	memset(&encoder, 0, sizeof encoder);
	encoder.data = data;

	for (i = y0; i < y0 + size; i++) {
		line = bh->data + i * bh->stride;
		hash = 0;
		for (j = x0; j < x0 + size; j++)
			hash = hash * prime + line[j];
		for (j = x0; j < x1; j++) {
			block_hashes[j] = block_hashes[j] * vprime + hash;
			hash = hash * prime - line[j] * end_prime;
			if (j + size < width)
				hash += line[j + size];
		}
	}

	for (i = y0; i < y1; i++) {
		bottom = bh->data + (i + size) * bh->stride;
		line = bh->data + i * bh->stride;
		bottom_hash = 0;
		hash = 0;
		skyline_pixels = 0;

		if (prev)
			prev_line = prev->data + i * prev->stride; 

		for (j = x0; j < x0 + size; j++) {
			hash = hash * prime + line[j];
			if (i + size < height)
				bottom_hash = bottom_hash * prime + bottom[j];
			if (i < skyline[j])
				skyline_pixels = 0;
			else
				skyline_pixels++;
		}
		
		for (j = x0; j < x1; j++) {
			if (i < skyline[j])
				encode_pixel(&encoder, line[j], 0);
			else if (prev) {
				/* FIXME: Add back overlap exception
				 * for consecutive blocks */

				h = block_hashes[j];
				entry = lookup_block(prev, h);
				if (entry && entry->count < 2 &&
				    skyline_pixels >= size &&
				    verify_match(bh, j, i, prev, entry) &&
				    (entry->x != j || entry->y != i)) {
					matches++;
					encode_block(&encoder, entry, j, i);

					for (k = 0; k < size; k++)
						skyline[j + k] = i + size;

					encode_pixel(&encoder, line[j], 0);
				} else {
					encode_pixel(&encoder, line[j],
						     line[j] - prev_line[j]);
				}
			} else
				encode_pixel(&encoder, line[j], line[j]);

			if (i < skyline[j + size])
				skyline_pixels = 0;
			else
				skyline_pixels++;

			/* Insert block in hash table if we're on a
			 * grid point. */
			if (((i | j) & mask) == 0 && i + size <= width &&
			    j + size <= height)
				insert_block(bh, block_hashes[j], j, i);

			/* Update sliding block hash */
			block_hashes[j] =
				block_hashes[j] * vprime + bottom_hash -
				hash * end_vprime;

			if (i + size < height) {
				bottom_hash = bottom_hash * prime -
					bottom[j] * end_prime;
				if (j + size < width)
					bottom_hash += bottom[j + size];
			}
			hash = hash * prime + line[j + size] -
				line[j] * end_prime;
		}
	}

#if 0
	fprintf(stderr, "collision stats:");
	for (i = 0; i < (int) ARRAY_LENGTH(bh->stats); i++)
		fprintf(stderr, "%c%d", i == 0 ? ' ' : '/', bh->stats[i]);
	fprintf(stderr, "\n");

	fprintf(stderr, "%d / %d blocks (%d%%) matched, %d clashes\n",
		matches, bh->block_count,
		100 * matches / bh->block_count, bh->clashes);

	fprintf(stderr, "output stream %d bytes, raw buffer %d bytes (%d%%)\n",
		encoder.bytes, height * bh->stride,
		100 * encoder.bytes / (height * bh->stride));
#endif

	free(skyline);
	free(block_hashes);

	return encoder.bytes;
}

static void
remote_surface_commit(struct remote_surface *surface)
{
	struct remote *remote = surface->remote;
	struct weston_renderer *renderer;
	struct wl_region *region;
	struct buffer_hash *bh;
	size_t length;

	resize_buffer(surface);

	bh = create_buffer(surface->width, surface->height);
	renderer = remote->compositor->renderer;
	renderer->read_surface_pixels(surface->surface,
				      remote->compositor->read_format,
				      bh->data,
				      0, 0, bh->width, bh->height);

	surface->encoded_length =
		encode_buffer(bh, surface->buffer, surface->map);

	compress2(surface->zipped, &length,
		  surface->map, surface->encoded_length, 1);

	if (surface->buffer)
		destroy_buffer(surface->buffer);
	surface->buffer = bh;

#if 0
	if (surface->encoded_length > 0)
		fprintf(stderr, "zip %d -> %zu bytes (%zu%%)\n",
			surface->encoded_length, length,
			length * 100 / surface->encoded_length);
#endif

	if (surface->encoded_length > 0) {
		remote_stream_queue_block(remote->stream,
					  &surface->stream_block,
					  surface->zipped, length);
		region = wl_compositor_create_region(remote->remote_compositor);
		wl_region_add(region, 0, 0, surface->width, surface->height);
		remote_update_buffer(remote->proxy_remote, surface->proxy_buffer,
				     surface->stream_block.tag, region);
		wl_region_destroy(region);

		wl_surface_damage(surface->proxy,
				  0, 0, surface->width, surface->height);

		/* We need to flush the surface data before the
		 * commit, but we need something more subtle than this
		 * big, blocking hammer.  We'll need to read the
		 * protocol data into a buffer and then queue that.
		 * We also have to make the socketpair non-blocking so
		 * that we don't end up in protocol_data after this
		 * with nothing to read. */
		wl_display_flush(remote->display);
		protocol_data(remote->protocol_fd[0], WL_EVENT_READABLE, remote);

		while (!wl_list_empty(&remote->stream->block_queue)) {
			fprintf(stderr, "more flushing\n");
			remote_stream_write(remote->stream);
		}
	}

	wl_surface_commit(surface->proxy);
}

static void
remote_surface_destroy(struct wl_listener *listener, void *data)
{
	struct remote_surface *surface =
		container_of(listener,
			     struct remote_surface, destroy_listener);

	wl_surface_destroy(surface->proxy);
	if (surface->proxy_shell_surface)
		wl_shell_surface_destroy(surface->proxy_shell_surface);

	free(surface);
}

static struct remote_surface *
get_remote_surface(struct wl_resource *resource)
{
	struct wl_listener *listener;

	listener = wl_signal_get(&resource->destroy_signal,
				 remote_surface_destroy);

	if (listener == NULL)
		return NULL;

	return container_of(listener, struct remote_surface, destroy_listener);
}

static void
surface_handle_destroy(struct wl_client *client, struct wl_resource *resource)
{
	struct remote_surface *surface = get_remote_surface(resource);

	surface->interface->destroy(client, resource);
}

static void
surface_handle_attach(struct wl_client *client,
		      struct wl_resource *resource,
		      struct wl_resource *buffer_resource,
		      int32_t sx, int32_t sy)
{
	struct remote_surface *surface = get_remote_surface(resource);

	surface->interface->attach(client, resource, buffer_resource, sx, sy);
}

static void
surface_handle_damage(struct wl_client *client,
		      struct wl_resource *resource,
		      int32_t x, int32_t y, int32_t width, int32_t height)
{
	struct remote_surface *surface = get_remote_surface(resource);

	surface->interface->damage(client, resource, x, y, width, height);
}

static void
surface_handle_frame(struct wl_client *client,
		     struct wl_resource *resource, uint32_t callback)
{
	struct remote_surface *surface = get_remote_surface(resource);

	surface->interface->frame(client, resource, callback);
}

static struct wl_region *
get_remote_region(struct remote *remote, pixman_region32_t *region)
{
	struct wl_region *remote_region;
	pixman_box32_t *rectangles;
	int i, n;

	remote_region = wl_compositor_create_region(remote->remote_compositor);
	rectangles = pixman_region32_rectangles(region, &n);
	for (i = 0; i < n; i++)
		wl_region_add(remote_region,
			      rectangles[i].x1, rectangles[i].y1,
			      rectangles[i].x2 - rectangles[i].x1,
			      rectangles[i].y2 - rectangles[i].y1);

	return remote_region;
}

static void
surface_handle_set_opaque_region(struct wl_client *client,
				 struct wl_resource *resource,
				 struct wl_resource *region_resource)
{
	struct remote_surface *surface = get_remote_surface(resource);
	struct weston_region *region;
	struct wl_region *proxy;

	surface->interface->set_opaque_region(client,
					      resource, region_resource);

	if (region_resource) {
		region = region_resource->data;
		proxy = get_remote_region(surface->remote, &region->region);
		wl_surface_set_opaque_region(surface->proxy, proxy);
		wl_region_destroy(proxy);
	} else {
		wl_surface_set_opaque_region(surface->proxy, NULL);
	}
}

static void
surface_handle_set_input_region(struct wl_client *client,
				struct wl_resource *resource,
				struct wl_resource *region_resource)
{
	struct remote_surface *surface = get_remote_surface(resource);
	struct weston_region *region;
	struct wl_region *proxy;

	surface->interface->set_input_region(client,
					     resource, region_resource);

	if (region_resource) {
		region = region_resource->data;
		proxy = get_remote_region(surface->remote, &region->region);
		wl_surface_set_input_region(surface->proxy, proxy);
		wl_region_destroy(proxy);
	} else {
		wl_surface_set_input_region(surface->proxy, NULL);
	}		
}

static void
surface_handle_commit(struct wl_client *client,
		      struct wl_resource *resource)
{
	struct remote_surface *surface = get_remote_surface(resource);

	surface->interface->commit(client, resource);

	remote_surface_commit(surface);
}

static const struct wl_surface_interface surface_interface = {
	surface_handle_destroy,
	surface_handle_attach,
	surface_handle_damage,
	surface_handle_frame,
	surface_handle_set_opaque_region,
	surface_handle_set_input_region,
	surface_handle_commit
};


static void
shell_surface_handle_pong(struct wl_client *client,
			  struct wl_resource *resource, uint32_t serial)
{
	struct shell_surface *shell_surface = resource->data;
	struct remote_surface *surface =
		get_remote_surface(&shell_surface->surface->surface.resource);

	if (serial == surface->subst_ping_serial)
		wl_shell_surface_pong(surface->proxy_shell_surface,
				      surface->remote_ping_serial);
	else
		surface->shell_surface_interface->pong(client,
						       resource, serial);
}

static void
shell_surface_handle_move(struct wl_client *client,
			  struct wl_resource *resource,
			  struct wl_resource *seat_resource, uint32_t serial)
{
	struct remote_seat *seat;
	struct shell_surface *shell_surface = resource->data;
	struct remote_surface *surface =
		get_remote_surface(&shell_surface->surface->surface.resource);

	seat = is_remote_seat(seat_resource);
	if (seat) {
		wl_shell_surface_move(surface->proxy_shell_surface,
				      seat->proxy, serial);
	} else {
		surface->shell_surface_interface->move(client, resource,
						       seat_resource, serial);
	}
}

static void
shell_surface_handle_resize(struct wl_client *client,
			    struct wl_resource *resource,
			    struct wl_resource *seat_resource,
			    uint32_t serial, uint32_t edges)
{
	struct remote_seat *seat;
	struct shell_surface *shell_surface = resource->data;
	struct remote_surface *surface =
		get_remote_surface(&shell_surface->surface->surface.resource);

	seat = is_remote_seat(seat_resource);
	if (seat) {
		wl_shell_surface_resize(surface->proxy_shell_surface,
					seat->proxy, serial, edges);
	} else {
		surface->shell_surface_interface->resize(client, resource,
							 seat_resource,
							 serial, edges);
	}
}

static void
shell_surface_handle_set_toplevel(struct wl_client *client,
				  struct wl_resource *resource)
{
}

static void
shell_surface_handle_set_transient(struct wl_client *client,
				   struct wl_resource *resource,
				   struct wl_resource *parent_resource,
				   int x, int y, uint32_t flags)
{
}

static void
shell_surface_handle_set_fullscreen(struct wl_client *client,
				    struct wl_resource *resource,
				    uint32_t method,
				    uint32_t framerate,
				    struct wl_resource *output_resource)
{
	/* FIXME: How could this ever work with different size outputs */
}

static void
shell_surface_handle_set_popup(struct wl_client *client,
			       struct wl_resource *resource,
			       struct wl_resource *seat_resource,
			       uint32_t serial,
			       struct wl_resource *parent_resource,
			       int32_t x, int32_t y, uint32_t flags)
{
}

static void
shell_surface_handle_set_maximized(struct wl_client *client,
				   struct wl_resource *resource,
				   struct wl_resource *output_resource)
{
}

static void
shell_surface_handle_set_title(struct wl_client *client,
			       struct wl_resource *resource, const char *title)
{
}

static void
shell_surface_handle_set_class(struct wl_client *client,
			       struct wl_resource *resource, const char *class)
{
}

static const struct wl_shell_surface_interface shell_surface_implementation = {
	shell_surface_handle_pong,
	shell_surface_handle_move,
	shell_surface_handle_resize,
	shell_surface_handle_set_toplevel,
	shell_surface_handle_set_transient,
	shell_surface_handle_set_fullscreen,
	shell_surface_handle_set_popup,
	shell_surface_handle_set_maximized,
	shell_surface_handle_set_title,
	shell_surface_handle_set_class
};

static struct remote_surface *
remote_surface_create(struct remote *remote, struct weston_surface *surface,
		      struct shell_surface *shell_surface)
{
	struct remote_surface *rs;
	struct wl_region *proxy;

	weston_log("creating remote surface for %p\n", surface);

	rs = malloc(sizeof *rs);
	if (rs == NULL)
		return NULL;

	memset(rs, 0, sizeof *rs);
	rs->remote = remote;
	rs->surface = surface;
	wl_list_init(&rs->stream_block.link);
	rs->proxy = wl_compositor_create_surface(remote->remote_compositor);
	wl_surface_add_listener(rs->proxy, &surface_listener, rs);

	rs->destroy_listener.notify = remote_surface_destroy;
	wl_signal_add(&surface->surface.resource.destroy_signal,
		      &rs->destroy_listener);

	rs->interface = (const struct wl_surface_interface *)
		surface->surface.resource.object.implementation;
	surface->surface.resource.object.implementation =
		(void *) &surface_interface;

	rs->shell_surface = shell_surface;
	if (shell_surface) {
		rs->proxy_shell_surface =
			wl_shell_get_shell_surface(remote->shell, rs->proxy);
		wl_shell_surface_add_listener(rs->proxy_shell_surface,
					      &shell_surface_listener, rs);

		wl_shell_surface_set_toplevel(rs->proxy_shell_surface);

		rs->shell_surface_interface =
			(const struct wl_shell_surface_interface *)
			rs->shell_surface->resource.object.implementation;
		rs->shell_surface->resource.object.implementation =
			(void *) &shell_surface_implementation;
	}

	if (surface->buffer_ref.buffer)
		remote_surface_commit(rs);

	if (pixman_region32_not_empty(&surface->opaque)) {
		proxy = get_remote_region(remote, &surface->opaque);
		wl_surface_set_opaque_region(rs->proxy, proxy);
		wl_region_destroy(proxy);
	}

	if (pixman_region32_not_empty(&surface->input)) {
		proxy = get_remote_region(remote, &surface->input);
		wl_surface_set_input_region(rs->proxy, proxy);
		wl_region_destroy(proxy);
	}

	wl_surface_commit(rs->proxy);
	wl_display_flush(remote->display);

	return rs;
}

static void
remote_binding(struct wl_seat *seat, uint32_t time, uint32_t key, void *data)
{
	struct remote *remote = data;
	struct weston_surface *surface;

	if (seat->keyboard->focus == NULL)
		return;

	/* FIXME: Verify this is a shell surface, handle other surface
	 * types (eg cursor) */

	surface = (struct weston_surface *) seat->keyboard->focus;
	remote_surface_create(remote, surface, surface->private);

#if 0
	wl_list_remove(&surface->layer_link);
	wl_list_insert(&remote->surface_list, &surface->layer_link);
#endif
	weston_surface_schedule_repaint(surface);
}

static void
pointer_handle_set_cursor(struct wl_client *client,
			  struct wl_resource *resource,
			  uint32_t serial,
			  struct wl_resource *surface_resource,
			  int32_t x, int32_t y)
{
	struct remote_seat *seat = resource->data;
	struct weston_surface *surface;
	struct remote_surface *remote_surface;

	if (surface_resource == NULL) {
		wl_pointer_set_cursor(seat->proxy_pointer,
				      seat->enter_serial, NULL, x, y);
		return;
	}

	surface = surface_resource->data;
	remote_surface = get_remote_surface(surface_resource);
	if (remote_surface == NULL)
		remote_surface = remote_surface_create(seat->remote,
						       surface, NULL);

	wl_pointer_set_cursor(seat->proxy_pointer, seat->enter_serial,
			      remote_surface->proxy, x, y);
}

static const struct wl_pointer_interface pointer_implementation = {
	pointer_handle_set_cursor
};

static void
pointer_handle_enter(void *data, struct wl_pointer *pointer,
		     uint32_t serial, struct wl_surface *wl_surface,
		     wl_fixed_t sx, wl_fixed_t sy)
{
	struct remote_seat *seat = data;
	struct remote_surface *surface = wl_surface_get_user_data(wl_surface);

	wl_pointer_set_focus(&seat->pointer,
			     &surface->surface->surface, sx, sy);
}

static void
pointer_handle_leave(void *data, struct wl_pointer *pointer,
		     uint32_t serial, struct wl_surface *surface)
{
	struct remote_seat *seat = data;

	wl_pointer_set_focus(&seat->pointer, NULL, 0, 0);
}

static void
pointer_handle_motion(void *data, struct wl_pointer *pointer,
		      uint32_t time, wl_fixed_t x, wl_fixed_t y)
{
	struct remote_seat *seat = data;
	struct wl_resource *resource = seat->pointer.focus_resource;

	if (resource)
		wl_pointer_send_motion(resource, time, x, y);
}

static void
pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial,
		      uint32_t time, uint32_t button, uint32_t state)
{
	struct remote_seat *seat = data;
	struct wl_resource *resource = seat->pointer.focus_resource;

	/* FIXME: translate serials? */

	if (resource)
		wl_pointer_send_button(resource, serial, time, button, state);
}

static void
pointer_handle_axis(void *data, struct wl_pointer *pointer,
		    uint32_t time, uint32_t axis, wl_fixed_t value)
{
	struct remote_seat *seat = data;
	struct wl_resource *resource = seat->pointer.focus_resource;

	if (resource)
		wl_pointer_send_axis(resource, time, axis, value);
}

static const struct wl_pointer_listener pointer_listener = {
	pointer_handle_enter,
	pointer_handle_leave,
	pointer_handle_motion,
	pointer_handle_button,
	pointer_handle_axis,
};

static void
keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
		       uint32_t format, int fd, uint32_t size)
{
	/* We'll never get this event. */
}

static void
keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
		      uint32_t serial, struct wl_surface *wl_surface,
		      struct wl_array *keys)
{
	struct remote_seat *seat = data;
	struct remote_surface *surface = wl_surface_get_user_data(wl_surface);

	wl_keyboard_set_focus(&seat->keyboard,
			      &surface->surface->surface);
}

static void
keyboard_handle_leave(void *data, struct wl_keyboard *keyboard,
		      uint32_t serial, struct wl_surface *surface)
{
	struct remote_seat *seat = data;

	wl_keyboard_set_focus(&seat->keyboard, NULL);
}

static void
keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
		    uint32_t serial, uint32_t time, uint32_t key,
		    uint32_t state)
{
	struct remote_seat *seat = data;
	struct wl_resource *resource = seat->keyboard.focus_resource;

	if (resource)
		wl_keyboard_send_key(resource, serial, time, key, state);
}

static void
keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard,
			  uint32_t serial, uint32_t mods_depressed,
			  uint32_t mods_latched, uint32_t mods_locked,
			  uint32_t group)
{
	struct remote_seat *seat = data;
	struct wl_resource *resource = seat->keyboard.focus_resource;

	if (resource)
		wl_keyboard_send_modifiers(resource, serial, mods_depressed,
					   mods_latched, mods_locked, group);
}

static const struct wl_keyboard_listener keyboard_listener = {
	keyboard_handle_keymap,
	keyboard_handle_enter,
	keyboard_handle_leave,
	keyboard_handle_key,
	keyboard_handle_modifiers,
};

static void
seat_handle_capabilities(void *data, struct wl_seat *wl_seat,
			 enum wl_seat_capability capabilities)
{
	struct remote_seat *seat = data;

	if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
		seat->proxy_pointer = wl_seat_get_pointer(seat->proxy);
		wl_pointer_add_listener(seat->proxy_pointer,
					&pointer_listener, seat);

		wl_pointer_init(&seat->pointer);
		wl_seat_set_pointer(&seat->seat, &seat->pointer);

	} else {
		wl_pointer_destroy(seat->proxy_pointer);
		seat->proxy_pointer = NULL;
	}

	if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
		seat->proxy_keyboard = wl_seat_get_keyboard(seat->proxy);
		wl_keyboard_add_listener(seat->proxy_keyboard,
					 &keyboard_listener, seat);

		wl_keyboard_init(&seat->keyboard);
		wl_seat_set_keyboard(&seat->seat, &seat->keyboard);
	} else {
		wl_keyboard_destroy(seat->proxy_keyboard);
		seat->proxy_keyboard = NULL;
	}
}

static const struct wl_seat_listener seat_listener = {
	seat_handle_capabilities,
};

static void unbind_resource(struct wl_resource *resource)
{
	wl_list_remove(&resource->link);
	free(resource);
}

static void
remote_seat_get_pointer(struct wl_client *client,
			struct wl_resource *resource, uint32_t id)
{
	struct remote_seat *seat = resource->data;
	struct wl_resource *cr;

	if (!seat->proxy_pointer)
		return;

        cr = wl_client_add_object(client, &wl_pointer_interface,
				  &pointer_implementation, id, seat);
	wl_list_insert(&seat->pointer.resource_list, &cr->link);
	cr->destroy = unbind_resource;
}

static void
remote_seat_get_keyboard(struct wl_client *client,
			 struct wl_resource *resource, uint32_t id)
{
	struct remote_seat *seat = resource->data;
	struct wl_resource *cr;

	if (!seat->proxy_keyboard)
		return;

        cr = wl_client_add_object(client, &wl_keyboard_interface,
				  NULL, id, seat);
	wl_list_insert(&seat->keyboard.resource_list, &cr->link);
	cr->destroy = unbind_resource;

	wl_keyboard_send_keymap(cr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
				seat->keymap_fd,
				seat->keymap_size);

	if (seat->seat.keyboard->focus &&
	    seat->seat.keyboard->focus->resource.client == client) {
		wl_keyboard_set_focus(seat->seat.keyboard,
				      seat->seat.keyboard->focus);
	}
}

static void
remote_seat_get_touch(struct wl_client *client,
		      struct wl_resource *resource, uint32_t id)
{
}

static const struct wl_seat_interface remote_seat_interface = {
	remote_seat_get_pointer,
	remote_seat_get_keyboard,
	remote_seat_get_touch,
};

static struct remote_seat *
is_remote_seat(struct wl_resource *resource)
{
	if (resource->object.implementation == (void *) &remote_seat_interface)
		return resource->data;
	else
		return NULL;
}

static void
bind_seat(struct wl_client *client, void *data, uint32_t version, uint32_t id)
{
	struct remote_seat *seat = data;
	struct wl_resource *resource;
	enum wl_seat_capability caps = 0;

	resource = wl_client_add_object(client, &wl_seat_interface,
					&remote_seat_interface, id, seat);
	wl_list_insert(&seat->seat.base_resource_list, &resource->link);
	resource->destroy = unbind_resource;

	if (seat->proxy_pointer)
		caps |= WL_SEAT_CAPABILITY_POINTER;
	if (seat->proxy_keyboard)
		caps |= WL_SEAT_CAPABILITY_KEYBOARD;

	wl_seat_send_capabilities(resource, caps);
}

static void
remote_add_seat(struct remote *remote, uint32_t id)
{
	struct remote_seat *seat;

	seat = malloc(sizeof *seat);
	if (seat == NULL)
		return;

	memset(seat, 0, sizeof *seat);

	seat->remote = remote;
	seat->proxy = wl_registry_bind(remote->registry, id,
				       &wl_seat_interface, 1);
	wl_seat_add_listener(seat->proxy, &seat_listener, seat);

	wl_seat_init(&seat->seat);
	wl_display_add_global(seat->remote->compositor->wl_display,
			      &wl_seat_interface, seat, bind_seat);
}

static void
output_handle_geometry(void *data,
		       struct wl_output *wl_output,
		       int32_t x, int32_t y,
		       int32_t physical_width,
		       int32_t physical_height,
		       int subpixel,
		       const char *make,
		       const char *model,
		       int transform)
{
	struct remote_output *output = data;

	/* Discard x and y. */
	output->output.make = strdup(make);
	output->output.model = strdup(model);
	output->output.mm_width = physical_width;
	output->output.mm_height = physical_height;
	output->output.subpixel = subpixel;
	output->output.transform = transform;
	wl_list_init(&output->output.mode_list);
}

struct remote_mode {
	struct weston_mode base;
};

static void
output_handle_mode(void *data,
		   struct wl_output *wl_output,
		   uint32_t flags,
		   int width,
		   int height,
		   int refresh)
{
	struct remote_output *output = data;
	struct remote_mode *mode;

	mode = malloc(sizeof *mode);

	mode->base.flags = flags;
	mode->base.width = width;
	mode->base.height = height;
	mode->base.refresh = refresh;

	if (flags & WL_OUTPUT_MODE_CURRENT)
		output->output.current = &mode->base;

	wl_list_insert(output->output.mode_list.prev, &mode->base.link);
}

static const struct wl_output_listener output_listener = {
	output_handle_geometry,
	output_handle_mode
};

static void
output_callback_done(void *data, struct wl_callback *callback, uint32_t time)
{
	struct remote_output *output = data;
	int x = 0, y = 0, width = 800, height = 600;

	wl_callback_destroy(callback);
	weston_output_init(&output->output, output->remote->compositor,
			   x, y, width, height, WL_OUTPUT_TRANSFORM_NORMAL);
}

static const struct wl_callback_listener output_callback_listener = {
	output_callback_done
};

static void
remote_output_destroy(struct weston_output *output)
{
	free(output->make);
	free(output->model);
	weston_output_destroy(output);
	wl_list_remove(&output->link);
}

static void
remote_output_repaint(struct weston_output *output_base,
		      pixman_region32_t *damage)
{
}

static void
remote_add_output(struct remote *remote, uint32_t id)
{
	struct remote_output *output;
	struct wl_callback *callback;

	output = malloc(sizeof *output);
	if (output == NULL)
		return;

	memset(output, 0, sizeof *output);
	output->remote = remote;
	output->proxy = wl_registry_bind(remote->registry, id,
					 &wl_output_interface, 1);

	output->output.destroy = remote_output_destroy;
	output->output.repaint = remote_output_repaint;

	wl_output_add_listener(output->proxy, &output_listener, output);

	callback = wl_display_sync(remote->display);
	wl_callback_add_listener(callback, &output_callback_listener, output);
}

static void
remote_handle_keymap(void *data, struct remote *proxy,
		     struct wl_keyboard *keyboard, uint32_t format,
		     uint32_t tag, uint32_t size)
{
	struct remote *remote = data;
	struct remote_seat *seat = wl_keyboard_get_user_data(keyboard);

	remote_stream_handle_tag(remote->stream, tag,
				 keymap_tag_handler, seat);
}

static const struct remote_listener remote_listener = {
	remote_handle_keymap
};

static void
registry_handle_global(void *data, struct wl_registry *registry, uint32_t name,
		       const char *interface, uint32_t version)
{
	struct remote *remote = data;

	if (strcmp(interface, "wl_compositor") == 0) {
		remote->remote_compositor =
			wl_registry_bind(registry, name,
					 &wl_compositor_interface, 1);
	} else if (strcmp(interface, "wl_output") == 0) {
		remote_add_output(remote, name);
	} else if (strcmp(interface, "wl_seat") == 0) {
		remote_add_seat(remote, name);
	} else if (strcmp(interface, "wl_shell") == 0) {
		remote->shell = wl_registry_bind(registry, name,
						 &wl_shell_interface, 1);
	} else if (strcmp(interface, "remote") == 0) {
		remote->proxy_remote =
			wl_registry_bind(registry, name, &remote_interface, 1);
		remote_add_listener(remote->proxy_remote,
				    &remote_listener, remote);
	}
}

static const struct wl_registry_listener registry_listener = {
	registry_handle_global
};

static void
destroy_remote(struct wl_listener *listener, void *data)
{
	struct remote *remote =
		container_of(listener, struct remote, destroy_listener);

	/* FIXME: More clean up needed, unhook all forwarded surfaces,
	 * for example. */

	wl_registry_destroy(remote->registry);
	wl_event_source_remove(remote->stream->source);
	close(remote->stream->fd);
	wl_event_source_remove(remote->source);
	wl_event_source_remove(remote->protocol_source);
	close(remote->protocol_fd[0]);
	wl_display_disconnect(remote->display);
	wl_list_remove(&remote->destroy_listener.link);
	free(remote);
}

static int
remote_handle_event(int fd, uint32_t mask, void *data)
{
	struct remote *remote = data;
	int count = 0;

	if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) {
		destroy_remote(&remote->destroy_listener, NULL);
		return 0;
	}

	if (mask & WL_EVENT_READABLE)
		count = wl_display_dispatch(remote->display);
	if (mask & WL_EVENT_WRITABLE)
		wl_display_flush(remote->display);

	if (mask == 0) {
		count = wl_display_dispatch_pending(remote->display);
		wl_display_flush(remote->display);
	}

	return count;
}

WL_EXPORT int
module_init(struct weston_compositor *compositor,
	    int *argc, char *argv[], const char *config_file)
{
	struct remote *remote;
	struct wl_event_loop *loop =
		wl_display_get_event_loop(compositor->wl_display);
	int port = 44888;
	static const char *host;

	host = getenv("WESTON_REMOTE_HOST");
	if (host == NULL)
		host = "localhost";

	remote = malloc(sizeof *remote);
	if (remote == NULL)
		return -1;

	memset(remote, 0, sizeof *remote);
	remote->compositor = compositor;
	remote->stream = remote_stream_connect(remote, host, port);
	if (remote->stream == NULL)
 		return -1;

	if (os_socketpair_cloexec(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0,
				  remote->protocol_fd) < 0)
		return -1;

	remote->protocol_source =
		wl_event_loop_add_fd(loop, remote->protocol_fd[0],
				     WL_EVENT_READABLE,
				     protocol_data, remote);

	remote->display =
		wl_display_connect_to_fd(remote->protocol_fd[1]);

	if (remote->display == NULL) {
		weston_log("failed to connect to remote display on %s:%d\n",
			   host, port);
		free(remote);
		return -1;
	}

	remote->source = wl_event_loop_add_fd(loop, remote->protocol_fd[1],
					      WL_EVENT_READABLE,
					      remote_handle_event, remote);
	if (remote->source == NULL) {
		wl_display_disconnect(remote->display);
		free(remote);
		return -1;
	}

	wl_event_source_check(remote->source);

	remote->registry = wl_display_get_registry(remote->display);
	wl_registry_add_listener(remote->registry, &registry_listener, remote);

	weston_compositor_add_key_binding(compositor, KEY_F, MODIFIER_SUPER,
					  remote_binding, remote);

	wl_list_init(&remote->surface_list);
	remote->destroy_listener.notify = destroy_remote;
	wl_signal_add(&compositor->destroy_signal, &remote->destroy_listener);

	weston_log("connected to remote host %s:%d\n", host, port);

	wl_display_flush(remote->display);

	return 0;
}