summaryrefslogtreecommitdiff
path: root/Xext/mbuf.c
blob: 1f24974631b9a2300893ebb017d63f90f0ed9658 (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
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
/************************************************************

Copyright 1989, 1998  The Open Group

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.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.

********************************************************/

#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include <X11/X.h>
#include <X11/Xproto.h>
#include "window.h"
#include "os.h"
#include "windowstr.h"
#include "scrnintstr.h"
#include "pixmapstr.h"
#include "gcstruct.h"
#include "extnsionst.h"
#include "dixstruct.h"
#include "resource.h"
#include "opaque.h"
#include "sleepuntil.h"
#include "inputstr.h"
#include <X11/extensions/multibufconst.h>
#include <X11/extensions/multibufproto.h>

#include <stdio.h>
#if !defined(WIN32)
#include <sys/time.h>
#endif

/* given an OtherClientPtr obj, get the ClientPtr */
#define rClient(obj) (clients[CLIENT_ID((obj)->resource)])

/* given a MultibufferPtr b, get the ClientPtr */
#define bClient(b)   (clients[CLIENT_ID(b->pPixmap->drawable.id)])

#define ValidEventMasks (ExposureMask|MultibufferClobberNotifyMask|MultibufferUpdateNotifyMask)

/* The _Multibuffer and _Multibuffers structures below refer to each other,
 * so we need this forward declaration
 */
typedef struct _Multibuffers	*MultibuffersPtr;

/*
 * per-Multibuffer data
 */
typedef struct _Multibuffer {
    MultibuffersPtr pMultibuffers;  /* associated window data */
    Mask	    eventMask;	    /* MultibufferClobberNotifyMask|ExposureMask|MultibufferUpdateNotifyMask */
    Mask	    otherEventMask; /* mask of all other clients event masks */
    OtherClients    *otherClients;  /* other clients that want events */
    int		    number;	    /* index of this buffer into array */
    int		    side;	    /* always Mono */
    int		    clobber;	    /* Unclobbered, PartiallyClobbered, FullClobbered */
    PixmapPtr	    pPixmap;	    /* associated pixmap */
} MultibufferRec, *MultibufferPtr;

/*
 * per-window data
 */

typedef struct _Multibuffers {
    WindowPtr	pWindow;		/* associated window */
    int		numMultibuffer;		/* count of buffers */
    int		refcnt;			/* ref count for delete */
    int		displayedMultibuffer;	/* currently active buffer */
    int		updateAction;		/* Undefined, Background, Untouched, Copied */
    int		updateHint;		/* Frequent, Intermittent, Static */
    int		windowMode;		/* always Mono */

    TimeStamp	lastUpdate;		/* time of last update */

    unsigned short	width, height;	/* last known window size */
    short		x, y;		/* for static gravity */

    MultibufferPtr	buffers;        /* array of numMultibuffer buffers */
} MultibuffersRec;

/*
 * per-screen data
 */
typedef struct _MultibufferScreen {
    PositionWindowProcPtr PositionWindow;		/* pWin, x,y */
} MultibufferScreenRec, *MultibufferScreenPtr;

/*
 * per display-image-buffers request data.
 */

typedef struct _DisplayRequest {
    struct _DisplayRequest	*next;
    TimeStamp			activateTime;
    ClientPtr			pClient;
    XID				id;
} DisplayRequestRec, *DisplayRequestPtr;

#define DestroyWindowMask		(1L<<0)
#define PositionWindowMask		(1L<<1)
#define PostValidateTreeMask		(1L<<2)
#define ClipNotifyMask			(1L<<3)
#define WindowExposuresMask		(1L<<4)
#define CopyWindowMask			(1L<<5)
#define ClearToBackgroundMask		(1L<<6)
#define ChangeWindowAttributesMask	(1L<<7)

extern int		MultibufferScreenIndex;
extern int		MultibufferWindowIndex;

extern RESTYPE		MultibufferDrawableResType;

extern void		MultibufferUpdate(	/* pMbuffer, time */
				MultibufferPtr /* pMultibuffer */,
				CARD32 /* time */
				);
extern void		MultibufferExpose(	/* pMbuffer, pRegion */
				MultibufferPtr /* pMultibuffer */,
				RegionPtr /* pRegion */
				);
extern void		MultibufferClobber(	/* pMbuffer */
				MultibufferPtr /* pMultibuffer */
				);

typedef struct _mbufWindow	*mbufWindowPtr;

void DestroyImageBuffers (WindowPtr	pWin);

/*
 * per-buffer data
 */

#define MB_DISPLAYED_BUFFER(pMBWindow) \
    ((pMBWindow)->buffers + (pMBWindow)->displayedMultibuffer)

typedef struct _mbufBuffer {
    mbufWindowPtr   pMBWindow;	    /* associated window data */
    Mask	    eventMask;	    /* client event mask */
    Mask	    otherEventMask; /* union of other clients' event masks */
    OtherClientsPtr otherClients;   /* other clients that want events */
    int		    number;	    /* index of this buffer into array */
    int		    side;	    /* stero side: always Mono */
    int		    clobber;	    /* clober state */
    DrawablePtr	    pDrawable;	    /* associated drawable */
} mbufBufferRec, *mbufBufferPtr;


/*
 * per-window data
 */

#define MB_WINDOW_PRIV(pWin) \
    ((mbufWindowPtr)((pWin)->devPrivates[MultibufferWindowIndex].ptr))

typedef struct _mbufWindow {
    WindowPtr	pWindow;		/* associated window */
    int		numMultibuffer;		/* count of buffers */
    mbufBufferPtr buffers;		/* array of (numMultibuffer) buffers */
    int		displayedMultibuffer;	/* currently active buffer */
    int		updateAction;		/* Undefined, Background,
					   Untouched, Copied */
    int		updateHint;		/* Frequent, Intermittent, Static */
    int		windowMode;		/* always Mono */
    TimeStamp	lastUpdate;		/* time of last update */
    short		x, y;		/* for static gravity */
    unsigned short	width, height;	/* last known window size */
    DevUnion		devPrivate;
} mbufWindowRec;


/*
 * per-screen data
 */

#define MB_SCREEN_PRIV(pScreen) \
    ((mbufScreenPtr)((pScreen)->devPrivates[MultibufferScreenIndex].ptr))

typedef struct _mbufScreen {
    long mbufWindowCount;		/* count of multibuffered windows */

    /* Wrap pScreen->DestroyWindow */
    DestroyWindowProcPtr DestroyWindow;
    long funcsWrapped;			/* flags which functions are wrapped */

    /* Initialized by device-dependent section */
    int  nInfo;				/* number of buffer info rec's */
    xMbufBufferInfo *pInfo;		/* buffer info (for Normal buffers) */

    int  (* CreateImageBuffers)(
		WindowPtr		/* pWin */,
		int			/* nbuf */,
		XID *			/* ids */,
		int			/* action */,
		int			/* hint */
		);
    void (* DestroyImageBuffers)(
		WindowPtr		/* pWin */
		);
    void (* DisplayImageBuffers)(
		ScreenPtr		/* pScreen */,
		mbufBufferPtr *		/* ppMBBuffer */,
		mbufWindowPtr *		/* ppMBWindow */,
		int			/* nbuf */
		);
    void (* ClearImageBufferArea)(
		mbufBufferPtr		/* pMBBuffer */,
		short			/* x */,
		short			/* y */,
		unsigned short		/* width */,
		unsigned short		/* height */,
		Bool			/* exposures */
		);
    Bool (* ChangeMBufferAttributes)(	/* pMBWindow, vmask */
		/* FIXME */
		);
    Bool (* ChangeBufferAttributes)(	/* pMBBuffer, vmask */
		/* FIXME */
		);
    void (* DeleteBufferDrawable)(
		DrawablePtr		/* pDrawable */
		);
    void (* WrapScreenFuncs)(
		ScreenPtr		/* pScreen */
		);
    void (* ResetProc)(
		ScreenPtr		/* pScreen */
		);
    DevUnion	devPrivate;
} mbufScreenRec, *mbufScreenPtr;


/* Privates to mbufScreenRec */

#ifdef _MULTIBUF_PIXMAP_
#define MB_SCREEN_PRIV_PIXMAP(pScreen) \
    ((mbufPixmapPrivPtr) MB_SCREEN_PRIV((pScreen))->devPrivate.ptr)

typedef struct _mbufPixmapPriv
{
    /* Pointers to wrapped functions */
    PositionWindowProcPtr PositionWindow;		/* pWin, x,y */
    long funcsWrapped;			/* flags which functions are wrapped */
} mbufPixmapPrivRec, *mbufPixmapPrivPtr;
#endif /* _MULTIBUF_PIXMAP_ */


#ifdef _MULTIBUF_BUFFER_

extern int frameWindowPrivateIndex;

#define MB_SCREEN_PRIV_BUFFER(pScreen) \
    ((mbufBufferPrivPtr) MB_SCREEN_PRIV((pScreen))->devPrivate.ptr)

typedef struct _mbufBufferPriv
{
    DevUnion	*frameBuffer;	/* Array of screen framebuffers */
    DevUnion	selectPlane;	/* Plane(s) that select displayed buffer */

    /*
     * Note: subtractRgn and unionRgn may overlap. subtractRgn is a union
     * of all the old clipLists of the windows that are displaying
     * the backbuffer. unionRgn is the union of all the new clipLists
     * of the same windows.
     */

    RegionRec	backBuffer;	/* Area of screen displaying back buffer */
    RegionRec   subtractRgn;	/* Regions lost to backBuffer   */
    RegionRec   unionRgn;	/* Regions gained by backBuffer */
    Bool	rgnChanged;	/* TRUE if "backBuffer" needs to be updated */

    void (* CopyBufferBits)();	/* pMBWindow, srcBufferNum, dstBufferNum */
    void (* DrawSelectPlane)();	/* pScreen, selectPlane, pRegion, bufferNum */

    /* Pointers to wrapped functions */
    PostValidateTreeProcPtr	PostValidateTree; /* pParent, pChild, kind */
    ClipNotifyProcPtr		ClipNotify;       /* pWin, dx, dy */
    WindowExposuresProcPtr	WindowExposures;  /* pWin, pRegion */
    CopyWindowProcPtr		CopyWindow;       /* pWin, oldPt, pOldRegion */
    ClearToBackgroundProcPtr	ClearToBackground; /* pWin, x,y,w,h, sendExpose */
    ChangeWindowAttributesProcPtr ChangeWindowAttributes; /* pWin, vmask */
    long funcsWrapped;			/* flags which functions are wrapped */
    unsigned  inClearToBackground:1;	/* used by WindowExposure */
} mbufBufferPrivRec, *mbufBufferPrivPtr;
#endif /* _MULTIBUF_BUFFER_ */

static int		MultibufferEventBase;
static int		MultibufferErrorBase;
static int MultibufferScreenPrivKeyIndex;
static DevPrivateKey MultibufferScreenPrivKey = &MultibufferScreenPrivKeyIndex;
static int MultibufferWindowPrivKeyIndex;
static DevPrivateKey MultibufferWindowPrivKey = &MultibufferWindowPrivKeyIndex;

static void		PerformDisplayRequest (
				MultibuffersPtr * /* ppMultibuffers */,
				MultibufferPtr * /* pMultibuffer */,
				int /* nbuf */
				);
static Bool		QueueDisplayRequest (
				ClientPtr /* client */,
				TimeStamp /* activateTime */
				);

static void		BumpTimeStamp (
				TimeStamp * /* ts */,
				CARD32 /* inc */
				);

static void		AliasMultibuffer (
				MultibuffersPtr /* pMultibuffers */,
				int /* i */
				);
static void		RecalculateMultibufferOtherEvents (
				MultibufferPtr /* pMultibuffer */
				);
static int		EventSelectForMultibuffer(
				MultibufferPtr /* pMultibuffer */,
				ClientPtr /* client */,
				Mask /* mask */
				);

/*
 * The Pixmap associated with a buffer can be found as a resource
 * with this type
 */
RESTYPE			MultibufferDrawableResType;
static int		MultibufferDrawableDelete (
				pointer /* value */,
				XID /* id */
				);
/*
 * The per-buffer data can be found as a resource with this type.
 * the resource id of the per-buffer data is the same as the resource
 * id of the pixmap
 */
static RESTYPE		MultibufferResType;
static int		MultibufferDelete (
				pointer /* value */,
				XID /* id */
				);

/*
 * The per-window data can be found as a resource with this type,
 * using the window resource id
 */
static RESTYPE		MultibuffersResType;
static int		MultibuffersDelete (
				pointer /* value */,
				XID /* id */
				);

/*
 * Clients other than the buffer creator attach event masks in
 * OtherClient structures; each has a resource of this type.
 */
static RESTYPE		OtherClientResType;
static int		OtherClientDelete (
				pointer /* value */,
				XID /* id */
				);

/****************
 * MultibufferExtensionInit
 *
 * Called from InitExtensions in main()
 *
 ****************/

extern DISPATCH_PROC(ProcGetBufferAttributes);

static DISPATCH_PROC(ProcClearImageBufferArea);
static DISPATCH_PROC(ProcCreateImageBuffers);
static DISPATCH_PROC(ProcDestroyImageBuffers);
static DISPATCH_PROC(ProcDisplayImageBuffers);
static DISPATCH_PROC(ProcGetBufferInfo);
static DISPATCH_PROC(ProcGetBufferVersion);
static DISPATCH_PROC(ProcGetMBufferAttributes);
static DISPATCH_PROC(ProcMultibufferDispatch);
static DISPATCH_PROC(ProcSetBufferAttributes);
static DISPATCH_PROC(ProcSetMBufferAttributes);
static DISPATCH_PROC(SProcClearImageBufferArea);
static DISPATCH_PROC(SProcCreateImageBuffers);
static DISPATCH_PROC(SProcDestroyImageBuffers);
static DISPATCH_PROC(SProcDisplayImageBuffers);
static DISPATCH_PROC(SProcGetBufferAttributes);
static DISPATCH_PROC(SProcGetBufferInfo);
static DISPATCH_PROC(SProcGetBufferVersion);
static DISPATCH_PROC(SProcGetMBufferAttributes);
static DISPATCH_PROC(SProcMultibufferDispatch);
static DISPATCH_PROC(SProcSetBufferAttributes);
static DISPATCH_PROC(SProcSetMBufferAttributes);

static void		MultibufferResetProc(
				ExtensionEntry * /* extEntry */
				);
static void		SClobberNotifyEvent(
				xMbufClobberNotifyEvent * /* from */,
				xMbufClobberNotifyEvent	* /* to */
				);
static void		SUpdateNotifyEvent(
				xMbufUpdateNotifyEvent * /* from */,
				xMbufUpdateNotifyEvent * /* to */
				);
static Bool		MultibufferPositionWindow(
				WindowPtr /* pWin */,
				int /* x */,
				int /* y */
				);

static void		SetupBackgroundPainter (
				WindowPtr /* pWin */,
				GCPtr /* pGC */
				);

static int		DeliverEventsToMultibuffer (
				MultibufferPtr /* pMultibuffer */,
				xEvent * /* pEvents */,
				int /* count */,
				Mask /* filter */
				);

void
MultibufferExtensionInit()
{
    ExtensionEntry	    *extEntry;
    int			    i, j;
    ScreenPtr		    pScreen;
    MultibufferScreenPtr    pMultibufferScreen;

    for (i = 0; i < screenInfo.numScreens; i++)
    {
	pScreen = screenInfo.screens[i];
	if (!(pMultibufferScreen = xalloc (sizeof (MultibufferScreenRec))))
	{
	    for (j = 0; j < i; j++)
		xfree (dixLookupPrivate(&screenInfo.screens[j]->devPrivates, MultibufferScreenPrivKey));
	    return;
	}
	dixSetPrivate(&pScreen->devPrivates, MultibufferScreenPrivKey, pMultibufferScreen);
	/*
 	 * wrap PositionWindow to resize the pixmap when the window
	 * changes size
 	 */
	pMultibufferScreen->PositionWindow = pScreen->PositionWindow;
	pScreen->PositionWindow = MultibufferPositionWindow;
    }
    /*
     * create the resource types
     */
    MultibufferDrawableResType =
	CreateNewResourceType(MultibufferDrawableDelete)|RC_DRAWABLE;
    MultibufferResType = CreateNewResourceType(MultibufferDelete);
    MultibuffersResType = CreateNewResourceType(MultibuffersDelete);
    OtherClientResType = CreateNewResourceType(OtherClientDelete);
    if (MultibufferDrawableResType && MultibufferResType &&
	MultibuffersResType && 	OtherClientResType &&
	(extEntry = AddExtension(MULTIBUFFER_PROTOCOL_NAME,
				 MultibufferNumberEvents, 
				 MultibufferNumberErrors,
				 ProcMultibufferDispatch, SProcMultibufferDispatch,
				 MultibufferResetProc, StandardMinorOpcode)))
    {
	MultibufferEventBase = extEntry->eventBase;
	MultibufferErrorBase = extEntry->errorBase;
	EventSwapVector[MultibufferEventBase + MultibufferClobberNotify] = (EventSwapPtr) SClobberNotifyEvent;
	EventSwapVector[MultibufferEventBase + MultibufferUpdateNotify] = (EventSwapPtr) SUpdateNotifyEvent;
    }
}

/*ARGSUSED*/
static void
MultibufferResetProc (extEntry)
ExtensionEntry	*extEntry;
{
    int			    i;
    ScreenPtr		    pScreen;
    MultibufferScreenPtr    pMultibufferScreen;
    
    for (i = 0; i < screenInfo.numScreens; i++)
    {
	pScreen = screenInfo.screens[i];
	if ((pMultibufferScreen = (MultibufferScreenPtr)dixLookupPrivate(&pScreen->devPrivates, MultibufferScreenPrivKey)))
	{
	    pScreen->PositionWindow = pMultibufferScreen->PositionWindow;
	    xfree (pMultibufferScreen);
	}
    }
}

static int
ProcGetBufferVersion (client)
    ClientPtr	client;
{
    xMbufGetBufferVersionReply	rep;
    int		n;

    REQUEST_SIZE_MATCH (xMbufGetBufferVersionReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.majorVersion = MULTIBUFFER_MAJOR_VERSION;
    rep.minorVersion = MULTIBUFFER_MINOR_VERSION;
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    }
    WriteToClient(client, sizeof (xMbufGetBufferVersionReply), (char *)&rep);
    return (client->noClientException);
}

static void
SetupBackgroundPainter (pWin, pGC)
    WindowPtr	pWin;
    GCPtr	pGC;
{
    pointer	    gcvalues[4];
    int		    ts_x_origin, ts_y_origin;
    PixUnion	    background;
    int		    backgroundState;
    Mask	    gcmask;

    /*
     * First take care of any ParentRelative stuff by altering the
     * tile/stipple origin to match the coordinates of the upper-left
     * corner of the first ancestor without a ParentRelative background.
     * This coordinate is, of course, negative.
     */

    ts_x_origin = ts_y_origin = 0;
    while (pWin->backgroundState == ParentRelative) {
	ts_x_origin -= pWin->origin.x;
	ts_y_origin -= pWin->origin.y;
	pWin = pWin->parent;
    }
    backgroundState = pWin->backgroundState;
    background = pWin->background;

    switch (backgroundState)
    {
    case BackgroundPixel:
	gcvalues[0] = (pointer) background.pixel;
	gcvalues[1] = (pointer) FillSolid;
	gcmask = GCForeground|GCFillStyle;
	break;

    case BackgroundPixmap:
	gcvalues[0] = (pointer) FillTiled;
	gcvalues[1] = (pointer) background.pixmap;
	gcvalues[2] = (pointer)(long) ts_x_origin;
	gcvalues[3] = (pointer)(long) ts_y_origin;
	gcmask = GCFillStyle|GCTile|GCTileStipXOrigin|GCTileStipYOrigin;
	break;

    default:
	gcvalues[0] = (pointer) GXnoop;
	gcmask = GCFunction;
    }
    DoChangeGC(pGC, gcmask, (XID *)gcvalues, TRUE);
}

int
CreateImageBuffers (pWin, nbuf, ids, action, hint)
    WindowPtr	pWin;
    int		nbuf;
    XID		*ids;
    int		action;
    int		hint;
{
    MultibuffersPtr	pMultibuffers;
    MultibufferPtr	pMultibuffer;
    ScreenPtr		pScreen;
    int			width, height, depth;
    int			i;
    GCPtr		pClearGC = NULL;
    xRectangle		clearRect;

    DestroyImageBuffers(pWin);
    pMultibuffers = xalloc (sizeof (MultibuffersRec) + nbuf * sizeof (MultibufferRec));
    if (!pMultibuffers)
	return BadAlloc;
    pMultibuffers->pWindow = pWin;
    pMultibuffers->buffers = (MultibufferPtr) (pMultibuffers + 1);
    pMultibuffers->refcnt = pMultibuffers->numMultibuffer = 0;
    if (!AddResource (pWin->drawable.id, MultibuffersResType, (pointer) pMultibuffers))
	return BadAlloc;
    width = pWin->drawable.width;
    height = pWin->drawable.height;
    depth = pWin->drawable.depth;
    pScreen = pWin->drawable.pScreen;

    if (pWin->backgroundState != None)
    {
	pClearGC = GetScratchGC (pWin->drawable.depth, pScreen);
	SetupBackgroundPainter (pWin, pClearGC);
	clearRect.x = clearRect.y = 0;
	clearRect.width = width;
	clearRect.height = height;
    }

    for (i = 0; i < nbuf; i++)
    {
	pMultibuffer = &pMultibuffers->buffers[i];
	pMultibuffer->eventMask = 0L;
	pMultibuffer->otherEventMask = 0L;
	pMultibuffer->otherClients = (OtherClientsPtr) NULL;
	pMultibuffer->number = i;
	pMultibuffer->side = MultibufferSideMono;
	pMultibuffer->clobber = MultibufferUnclobbered;
	pMultibuffer->pMultibuffers = pMultibuffers;
	if (!AddResource (ids[i], MultibufferResType, (pointer) pMultibuffer))
	    break;
	pMultibuffer->pPixmap = (*pScreen->CreatePixmap) (pScreen, width, height, depth, 0);
	if (!pMultibuffer->pPixmap)
	    break;
	if (!AddResource (ids[i], MultibufferDrawableResType, (pointer) pMultibuffer->pPixmap))
	{
	    FreeResource (ids[i], MultibufferResType);
	    (*pScreen->DestroyPixmap) (pMultibuffer->pPixmap);
	    break;
	}
	pMultibuffer->pPixmap->drawable.id = ids[i];

	if (i > 0 && pClearGC)
	{
	    ValidateGC((DrawablePtr)pMultibuffer->pPixmap, pClearGC);
	    (*pClearGC->ops->PolyFillRect)((DrawablePtr)pMultibuffer->pPixmap,
					   pClearGC, 1, &clearRect);
	}
    }
    pMultibuffers->numMultibuffer = i;
    pMultibuffers->refcnt = i;
    pMultibuffers->displayedMultibuffer = -1;
    if (i > 0)
	AliasMultibuffer (pMultibuffers, 0);
    pMultibuffers->updateAction = action;
    pMultibuffers->updateHint = hint;
    pMultibuffers->windowMode = MultibufferModeMono;
    pMultibuffers->lastUpdate.months = 0;
    pMultibuffers->lastUpdate.milliseconds = 0;
    pMultibuffers->width = width;
    pMultibuffers->height = height;
    dixSetPrivate(&pWin->devPrivates, MultibufferWindowPrivKey, pMultibuffers);
    if (pClearGC) FreeScratchGC(pClearGC);
    return Success;
}


static int
ProcCreateImageBuffers (client)
    ClientPtr	client;
{
    REQUEST(xMbufCreateImageBuffersReq);
    xMbufCreateImageBuffersReply	rep;
    int		n;
    WindowPtr			pWin;
    XID				*ids;
    int				len, nbuf, i, err, rc;

    REQUEST_AT_LEAST_SIZE (xMbufCreateImageBuffersReq);
    len = stuff->length - bytes_to_int32(sizeof(xMbufCreateImageBuffersReq));
    if (len == 0)
	return BadLength;
    rc = dixLookupWindow(&pWin, stuff->window, client, DixUnknownAccess);
    if (rc != Success)
	return rc;
    if (pWin->drawable.class == InputOnly)
	return BadMatch;
    switch (stuff->updateAction)
    {
    case MultibufferUpdateActionUndefined:
    case MultibufferUpdateActionBackground:
    case MultibufferUpdateActionUntouched:
    case MultibufferUpdateActionCopied:
	break;
    default:
	client->errorValue = stuff->updateAction;
	return BadValue;
    }
    switch (stuff->updateHint)
    {
    case MultibufferUpdateHintFrequent:
    case MultibufferUpdateHintIntermittent:
    case MultibufferUpdateHintStatic:
	break;
    default:
	client->errorValue = stuff->updateHint;
	return BadValue;
    }
    nbuf = len;
    ids = (XID *) &stuff[1];
    for (i = 0; i < nbuf; i++)
    {
	LEGAL_NEW_RESOURCE(ids[i], client);
    }
    err = CreateImageBuffers (pWin, nbuf, ids,
			      stuff->updateAction, stuff->updateHint);
    if (err != Success)
	return err;
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.numberBuffer = ((MultibuffersPtr) (dixLookupPrivate(&pWin->devPrivates, MultibufferWindowPrivKey)))->numMultibuffer;
    if (client->swapped)
    {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
	swaps(&rep.numberBuffer, n);
    }
    WriteToClient(client, sizeof (xMbufCreateImageBuffersReply), (char*)&rep);
    return (client->noClientException);
}

static int
ProcDisplayImageBuffers (client)
    ClientPtr	client;
{
    REQUEST(xMbufDisplayImageBuffersReq);
    MultibufferPtr	    *pMultibuffer;
    MultibuffersPtr	    *ppMultibuffers;
    int		    nbuf;
    XID		    *ids;
    int		    i, j;
    CARD32	    minDelay;
    TimeStamp	    activateTime, bufferTime;
    int		    rc;
    

    REQUEST_AT_LEAST_SIZE (xMbufDisplayImageBuffersReq);
    nbuf = stuff->length - bytes_to_int32(sizeof (xMbufDisplayImageBuffersReq));
    if (!nbuf)
	return Success;
    minDelay = stuff->minDelay;
    ids = (XID *) &stuff[1];
    ppMultibuffers = xalloc(nbuf * sizeof (MultibuffersPtr));
    pMultibuffer = xalloc(nbuf * sizeof (MultibufferPtr));
    if (!ppMultibuffers || !pMultibuffer)
    {
	if (ppMultibuffers) xfree(ppMultibuffers);
	if (pMultibuffer)   xfree(pMultibuffer);
	client->errorValue = 0;
	return BadAlloc;
    }
    activateTime.months = 0;
    activateTime.milliseconds = 0;
    for (i = 0; i < nbuf; i++)
    {
	rc = dixLookupResourceByType(&pMultibuffer[i], ids[i],
		MultibufferResType, client, DixUseAccess);
	if (rc != Success)
	{
	    xfree(ppMultibuffers);
	    xfree(pMultibuffer);
	    client->errorValue = ids[i];
	    return MultibufferErrorBase + MultibufferBadBuffer;
	}
	ppMultibuffers[i] = pMultibuffer[i]->pMultibuffers;
	for (j = 0; j < i; j++)
	{
	    if (ppMultibuffers[i] == ppMultibuffers[j])
	    {
	    	xfree(ppMultibuffers);
	    	xfree(pMultibuffer);
		client->errorValue = ids[i];
	    	return BadMatch;
	    }
	}
	bufferTime = ppMultibuffers[i]->lastUpdate;
	BumpTimeStamp (&bufferTime, minDelay);
	if (CompareTimeStamps (bufferTime, activateTime) == LATER)
	    activateTime = bufferTime;
    }
    UpdateCurrentTime ();
    if (CompareTimeStamps (activateTime, currentTime) == LATER &&
	QueueDisplayRequest (client, activateTime))
    {
	;
    }
    else
	PerformDisplayRequest (ppMultibuffers, pMultibuffer, nbuf);

    xfree(ppMultibuffers);
    xfree(pMultibuffer);
    return Success;
}


static int
ProcDestroyImageBuffers (client)
    ClientPtr	client;
{
    REQUEST (xMbufDestroyImageBuffersReq);
    WindowPtr	pWin;
    int rc;

    REQUEST_SIZE_MATCH (xMbufDestroyImageBuffersReq);
    rc = dixLookupWindow(&pWin, stuff->window, client, DixUnknownAccess);
    if (rc != Success)
	return rc;
    DestroyImageBuffers (pWin);
    return Success;
}

static int
ProcSetMBufferAttributes (client)
    ClientPtr	client;
{
    REQUEST (xMbufSetMBufferAttributesReq);
    WindowPtr	pWin;
    MultibuffersPtr	pMultibuffers;
    int		len, rc;
    Mask	vmask;
    Mask	index2;
    CARD32	updateHint;
    XID		*vlist;

    REQUEST_AT_LEAST_SIZE (xMbufSetMBufferAttributesReq);
    rc = dixLookupWindow(&pWin, stuff->window, client, DixUnknownAccess);
    if (rc != Success)
	return rc;
    rc = dixLookupResourceByType(&pMultibuffers, pWin->drawable.id,
	    MultibufferResType, client, DixSetAttrAccess);
    if (rc != Success)
	return BadMatch;
    len = stuff->length - bytes_to_int32(sizeof (xMbufSetMBufferAttributesReq));
    vmask = stuff->valueMask;
    if (len != Ones (vmask))
	return BadLength;
    vlist = (XID *) &stuff[1];
    while (vmask)
    {
	index2 = (Mask) lowbit (vmask);
	vmask &= ~index2;
	switch (index2)
	{
	case MultibufferWindowUpdateHint:
	    updateHint = (CARD32) *vlist;
	    switch (updateHint)
	    {
	    case MultibufferUpdateHintFrequent:
	    case MultibufferUpdateHintIntermittent:
	    case MultibufferUpdateHintStatic:
		pMultibuffers->updateHint = updateHint;
		break;
	    default:
		client->errorValue = updateHint;
		return BadValue;
	    }
	    vlist++;
	    break;
	default:
	    client->errorValue = stuff->valueMask;
	    return BadValue;
	}
    }
    return Success;
}

static int
ProcGetMBufferAttributes (client)
    ClientPtr	client;
{
    REQUEST (xMbufGetMBufferAttributesReq);
    WindowPtr	pWin;
    MultibuffersPtr	pMultibuffers;
    XID		*ids;
    xMbufGetMBufferAttributesReply  rep;
    int		i, n, rc;

    REQUEST_SIZE_MATCH (xMbufGetMBufferAttributesReq);
    rc = dixLookupWindow(&pWin, stuff->window, client, DixUnknownAccess);
    if (rc != Success)
	return rc;
    rc = dixLookupResourceByType(&pMultibuffers, pWin->drawable.id,
	    MultibufferResType, client, DixGetAttrAccess);
    if (rc != Success)
	return BadAccess;
    ids = xalloc (pMultibuffers->numMultibuffer * sizeof (XID));
    if (!ids)
	return BadAlloc;
    for (i = 0; i < pMultibuffers->numMultibuffer; i++)
	ids[i] = pMultibuffers->buffers[i].pPixmap->drawable.id;
    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;
    rep.length = pMultibuffers->numMultibuffer;
    rep.displayedBuffer = pMultibuffers->displayedMultibuffer;
    rep.updateAction = pMultibuffers->updateAction;
    rep.updateHint = pMultibuffers->updateHint;
    rep.windowMode = pMultibuffers->windowMode;
    if (client->swapped)
    {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
	swaps(&rep.displayedBuffer, n);
	SwapLongs (ids, pMultibuffers->numMultibuffer);
    }
    WriteToClient (client, sizeof(xMbufGetMBufferAttributesReply),
		   (char *)&rep);
    WriteToClient (client, (int)(pMultibuffers->numMultibuffer * sizeof (XID)),
		   (char *)ids);
    xfree((pointer) ids);
    return client->noClientException;
}

static int
ProcSetBufferAttributes (client)
    ClientPtr	client;
{
    REQUEST(xMbufSetBufferAttributesReq);
    MultibufferPtr	pMultibuffer;
    int		len;
    Mask	vmask, index2;
    XID		*vlist;
    Mask	eventMask;
    int		result;
    int		rc;

    REQUEST_AT_LEAST_SIZE (xMbufSetBufferAttributesReq);

    rc = dixLookupResourceByType(&pMultibuffer, stuff->buffer,
	    MultibufferResType, client, DixSetAttrAccess);
    if (rc != Success)
	return MultibufferErrorBase + MultibufferBadBuffer;
    len = stuff->length - bytes_to_int32(sizeof (xMbufSetBufferAttributesReq));
    vmask = stuff->valueMask;
    if (len != Ones (vmask))
	return BadLength;
    vlist = (XID *) &stuff[1];
    while (vmask)
    {
	index2 = (Mask) lowbit (vmask);
	vmask &= ~index2;
	switch (index2)
	{
	case MultibufferBufferEventMask:
	    eventMask = (Mask) *vlist;
	    vlist++;
	    result = EventSelectForMultibuffer (pMultibuffer, client, eventMask);
	    if (result != Success)
		return result;
	    break;
	default:
	    client->errorValue = stuff->valueMask;
	    return BadValue;
	}
    }
    return Success;
}

int
ProcGetBufferAttributes (client)
    ClientPtr	client;
{
    REQUEST(xMbufGetBufferAttributesReq);
    MultibufferPtr	pMultibuffer;
    xMbufGetBufferAttributesReply	rep;
    OtherClientsPtr		other;
    int				n;
    int				rc;

    REQUEST_SIZE_MATCH (xMbufGetBufferAttributesReq);
    rc = dixLookupResourceByType(&pMultibuffer, stuff->buffer,
	    MultibufferResType, client, DixGetAttrAccess);
    if (rc != Success)
	return MultibufferErrorBase + MultibufferBadBuffer;
    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;
    rep.length = 0;
    rep.window = pMultibuffer->pMultibuffers->pWindow->drawable.id;
    if (bClient (pMultibuffer) == client)
	rep.eventMask = pMultibuffer->eventMask;
    else
    {
	rep.eventMask = (Mask) 0L;
	for (other = pMultibuffer->otherClients; other; other = other->next)
	    if (SameClient (other, client))
	    {
		rep.eventMask = other->mask;
		break;
	    }
    }
    rep.bufferIndex = pMultibuffer->number;
    rep.side = pMultibuffer->side;
    if (client->swapped)
    {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
	swapl(&rep.window, n);
	swapl(&rep.eventMask, n);
	swaps(&rep.bufferIndex, n);
    }
    WriteToClient(client, sizeof (xMbufGetBufferAttributesReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcGetBufferInfo (client)
    ClientPtr	client;
{
    REQUEST (xMbufGetBufferInfoReq);
    DrawablePtr		    pDrawable;
    xMbufGetBufferInfoReply rep;
    ScreenPtr		    pScreen;
    int			    i, j, k, n, rc;
    xMbufBufferInfo	    *pInfo;
    int			    nInfo;
    DepthPtr		    pDepth;

    rc = dixLookupDrawable(&pDrawable, stuff->drawable, client, 0,
			   DixUnknownAccess);
    if (rc != Success)
	return rc;
    pScreen = pDrawable->pScreen;
    nInfo = 0;
    for (i = 0; i < pScreen->numDepths; i++)
    {
	pDepth = &pScreen->allowedDepths[i];
	nInfo += pDepth->numVids;
    }
    pInfo = xalloc (nInfo * sizeof (xMbufBufferInfo));
    if (!pInfo)
	return BadAlloc;

    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;
    rep.length = nInfo * bytes_to_int32(sizeof (xMbufBufferInfo));
    rep.normalInfo = nInfo;
    rep.stereoInfo = 0;
    if (client->swapped)
    {
	swaps(&rep.sequenceNumber, n);
	swapl(&rep.length, n);
	swaps(&rep.normalInfo, n);
	swaps(&rep.stereoInfo, n);
    }

    k = 0;
    for (i = 0; i < pScreen->numDepths; i++)
    {
	pDepth = &pScreen->allowedDepths[i];
	for (j = 0; j < pDepth->numVids; j++)
	{
	    pInfo[k].visualID = pDepth->vids[j];
	    pInfo[k].maxBuffers = 0;
	    pInfo[k].depth = pDepth->depth;
	    if (client->swapped)
	    {
		swapl (&pInfo[k].visualID, n);
		swaps (&pInfo[k].maxBuffers, n);
	    }
	    k++;
	}
    }
    WriteToClient (client, sizeof (xMbufGetBufferInfoReply), (pointer) &rep);
    WriteToClient (client, (int) nInfo * sizeof (xMbufBufferInfo), (pointer) pInfo);
    xfree ((pointer) pInfo);
    return client->noClientException;
}

static int
ProcClearImageBufferArea (client)
    ClientPtr	client;
{
    REQUEST (xMbufClearImageBufferAreaReq);
    MultibufferPtr	pMultibuffer;
    WindowPtr pWin;
    xRectangle clearRect;
    int width, height;
    DrawablePtr pDrawable;
    ScreenPtr pScreen;
    int rc;

    REQUEST_SIZE_MATCH (xMbufClearImageBufferAreaReq);
    rc = dixLookupResourceByType(&pMultibuffer, stuff->buffer,
	    MultibufferResType, client, DixWriteAccess);
    if (rc != Success)
	return MultibufferErrorBase + MultibufferBadBuffer;
    if ((stuff->exposures != xTrue) && (stuff->exposures != xFalse))
    {
	client->errorValue = stuff->exposures;
        return(BadValue);
    }
    pWin = pMultibuffer->pMultibuffers->pWindow;
    width  = pWin->drawable.width;
    height = pWin->drawable.height;
    pScreen = pWin->drawable.pScreen;

    clearRect.x = stuff->x;
    clearRect.y = stuff->y;
    clearRect.width  = stuff->width  ? stuff->width  : width;
    clearRect.height = stuff->height ? stuff->height : height;

    if (pWin->backgroundState != None)
    {
	GCPtr pClearGC;
	pClearGC = GetScratchGC (pWin->drawable.depth, pScreen);
	SetupBackgroundPainter (pWin, pClearGC);

	if (pMultibuffer->number == pMultibuffer->pMultibuffers->displayedMultibuffer)
	    pDrawable = (DrawablePtr)pWin;
	else
	    pDrawable = (DrawablePtr)pMultibuffer->pPixmap;

	ValidateGC(pDrawable, pClearGC);
	(*pClearGC->ops->PolyFillRect) (pDrawable, pClearGC, 1, &clearRect);
	FreeScratchGC(pClearGC);
    }

    if (stuff->exposures)
    {
	RegionRec region;
	BoxRec box;
	box.x1 = clearRect.x;
	box.y1 = clearRect.y;
	box.x2 = clearRect.x + clearRect.width;
	box.y2 = clearRect.y + clearRect.height;
	REGION_INIT(pScreen, &region, &box, 1);
	MultibufferExpose(pMultibuffer, &region);
	REGION_UNINIT(pScreen, &region);
    }
    return Success;
}

static int
ProcMultibufferDispatch (client)
    ClientPtr	client;
{
    REQUEST(xReq);
    switch (stuff->data) {
    case X_MbufGetBufferVersion:
	return ProcGetBufferVersion (client);
    case X_MbufCreateImageBuffers:
	return ProcCreateImageBuffers (client);
    case X_MbufDisplayImageBuffers:
	return ProcDisplayImageBuffers (client);
    case X_MbufDestroyImageBuffers:
	return ProcDestroyImageBuffers (client);
    case X_MbufSetMBufferAttributes:
	return ProcSetMBufferAttributes (client);
    case X_MbufGetMBufferAttributes:
	return ProcGetMBufferAttributes (client);
    case X_MbufSetBufferAttributes:
	return ProcSetBufferAttributes (client);
    case X_MbufGetBufferAttributes:
	return ProcGetBufferAttributes (client);
    case X_MbufGetBufferInfo:
	return ProcGetBufferInfo (client);
    case X_MbufClearImageBufferArea:
	return ProcClearImageBufferArea (client);
    default:
	return BadRequest;
    }
}

static int
SProcGetBufferVersion (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufGetBufferVersionReq);

    swaps (&stuff->length, n);
    return ProcGetBufferVersion (client);
}

static int
SProcCreateImageBuffers (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufCreateImageBuffersReq);

    swaps (&stuff->length, n);
    REQUEST_AT_LEAST_SIZE (xMbufCreateImageBuffersReq);
    swapl (&stuff->window, n);
    SwapRestL(stuff);
    return ProcCreateImageBuffers (client);
}

static int
SProcDisplayImageBuffers (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufDisplayImageBuffersReq);
    
    swaps (&stuff->length, n);
    REQUEST_AT_LEAST_SIZE (xMbufDisplayImageBuffersReq);
    swaps (&stuff->minDelay, n);
    swaps (&stuff->maxDelay, n);
    SwapRestL(stuff);
    return ProcDisplayImageBuffers (client);
}

static int
SProcDestroyImageBuffers (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufDestroyImageBuffersReq);
    
    swaps (&stuff->length, n);
    REQUEST_SIZE_MATCH (xMbufDestroyImageBuffersReq);
    swapl (&stuff->window, n);
    return ProcDestroyImageBuffers (client);
}

static int
SProcSetMBufferAttributes (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufSetMBufferAttributesReq);

    swaps (&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xMbufSetMBufferAttributesReq);
    swapl (&stuff->window, n);
    swapl (&stuff->valueMask, n);
    SwapRestL(stuff);
    return ProcSetMBufferAttributes (client);
}

static int
SProcGetMBufferAttributes (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufGetMBufferAttributesReq);

    swaps (&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xMbufGetMBufferAttributesReq);
    swapl (&stuff->window, n);
    return ProcGetMBufferAttributes (client);
}

static int
SProcSetBufferAttributes (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufSetBufferAttributesReq);

    swaps (&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xMbufSetBufferAttributesReq);
    swapl (&stuff->buffer, n);
    swapl (&stuff->valueMask, n);
    SwapRestL(stuff);
    return ProcSetBufferAttributes (client);
}

static int
SProcGetBufferAttributes (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufGetBufferAttributesReq);

    swaps (&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xMbufGetBufferAttributesReq);
    swapl (&stuff->buffer, n);
    return ProcGetBufferAttributes (client);
}

static int
SProcGetBufferInfo (client)
    ClientPtr	client;
{
    int    n;
    REQUEST (xMbufGetBufferInfoReq);

    swaps (&stuff->length, n);
    REQUEST_SIZE_MATCH (xMbufGetBufferInfoReq);
    swapl (&stuff->drawable, n);
    return ProcGetBufferInfo (client);
}

static int
SProcClearImageBufferArea(client)
    ClientPtr client;
{
    char n;
    REQUEST(xMbufClearImageBufferAreaReq);

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH (xMbufClearImageBufferAreaReq);
    swapl(&stuff->buffer, n);
    swaps(&stuff->x, n);
    swaps(&stuff->y, n);
    swaps(&stuff->width, n);
    swaps(&stuff->height, n);
    return ProcClearImageBufferArea(client);
}

static int
SProcMultibufferDispatch (client)
    ClientPtr	client;
{
    REQUEST(xReq);
    switch (stuff->data) {
    case X_MbufGetBufferVersion:
	return SProcGetBufferVersion (client);
    case X_MbufCreateImageBuffers:
	return SProcCreateImageBuffers (client);
    case X_MbufDisplayImageBuffers:
	return SProcDisplayImageBuffers (client);
    case X_MbufDestroyImageBuffers:
	return SProcDestroyImageBuffers (client);
    case X_MbufSetMBufferAttributes:
	return SProcSetMBufferAttributes (client);
    case X_MbufGetMBufferAttributes:
	return SProcGetMBufferAttributes (client);
    case X_MbufSetBufferAttributes:
	return SProcSetBufferAttributes (client);
    case X_MbufGetBufferAttributes:
	return SProcGetBufferAttributes (client);
    case X_MbufGetBufferInfo:
	return SProcGetBufferInfo (client);
    case X_MbufClearImageBufferArea:
	return SProcClearImageBufferArea (client);
    default:
	return BadRequest;
    }
}

static void
SUpdateNotifyEvent (from, to)
    xMbufUpdateNotifyEvent	*from, *to;
{
    to->type = from->type;
    cpswaps (from->sequenceNumber, to->sequenceNumber);
    cpswapl (from->buffer, to->buffer);
    cpswapl (from->timeStamp, to->timeStamp);
}

static void
SClobberNotifyEvent (from, to)
    xMbufClobberNotifyEvent	*from, *to;
{
    to->type = from->type;
    cpswaps (from->sequenceNumber, to->sequenceNumber);
    cpswapl (from->buffer, to->buffer);
    to->state = from->state;
}

RegionPtr CreateUnclippedWinSize(WindowPtr pWin);

RegionPtr
CreateUnclippedWinSize (WindowPtr pWin)
{
    RegionPtr	pRgn;
    BoxRec	box;

    box.x1 = pWin->drawable.x;
    box.y1 = pWin->drawable.y;
    box.x2 = pWin->drawable.x + (int) pWin->drawable.width;
    box.y2 = pWin->drawable.y + (int) pWin->drawable.height;
    pRgn = REGION_CREATE(pWin->drawable.pScreen, &box, 1);
    if (wBoundingShape (pWin) || wClipShape (pWin)) {
	ScreenPtr pScreen;
        pScreen = pWin->drawable.pScreen;

	REGION_TRANSLATE(pScreen, pRgn, - pWin->drawable.x,
			 - pWin->drawable.y);
	if (wBoundingShape (pWin))
	    REGION_INTERSECT(pScreen, pRgn, pRgn, wBoundingShape (pWin));
	if (wClipShape (pWin))
	    REGION_INTERSECT(pScreen, pRgn, pRgn, wClipShape (pWin));
	REGION_TRANSLATE(pScreen, pRgn, pWin->drawable.x, pWin->drawable.y);
    }
    return pRgn;
}

static void
PerformDisplayRequest (ppMultibuffers, pMultibuffer, nbuf)
    MultibufferPtr	    *pMultibuffer;
    MultibuffersPtr	    *ppMultibuffers;
    int		    nbuf;
{
    GCPtr	    pGC;
    PixmapPtr	    pPrevPixmap, pNewPixmap;
    xRectangle	    clearRect;
    WindowPtr	    pWin;
    RegionPtr	    pExposed;
    int		    i;
    MultibufferPtr  pPrevMultibuffer;
    XID		    graphicsExpose;

    UpdateCurrentTime ();
    for (i = 0; i < nbuf; i++)
    {
	pWin = ppMultibuffers[i]->pWindow;
	pGC = GetScratchGC (pWin->drawable.depth, pWin->drawable.pScreen);
	pPrevMultibuffer =
	   &ppMultibuffers[i]->buffers[ppMultibuffers[i]->displayedMultibuffer];
	pPrevPixmap = pPrevMultibuffer->pPixmap;
	pNewPixmap = pMultibuffer[i]->pPixmap;
	switch (ppMultibuffers[i]->updateAction)
	{
	case MultibufferUpdateActionUndefined:
	    break;
	case MultibufferUpdateActionBackground:
	    SetupBackgroundPainter (pWin, pGC);
	    ValidateGC ((DrawablePtr)pPrevPixmap, pGC);
	    clearRect.x = 0;
	    clearRect.y = 0;
	    clearRect.width = pPrevPixmap->drawable.width;
	    clearRect.height = pPrevPixmap->drawable.height;
	    (*pGC->ops->PolyFillRect) ((DrawablePtr)pPrevPixmap, pGC,
				       1, &clearRect);
	    break;
	case MultibufferUpdateActionUntouched:
	    /* copy the window to the pixmap that represents the
	     * currently displayed buffer
	     */
	    if (pPrevMultibuffer->eventMask & ExposureMask)
	    {
	    	graphicsExpose = TRUE;
	    	DoChangeGC (pGC, GCGraphicsExposures, &graphicsExpose, FALSE);
	    }
	    ValidateGC ((DrawablePtr)pPrevPixmap, pGC);
	    pExposed = (*pGC->ops->CopyArea)
			    ((DrawablePtr) pWin,
			     (DrawablePtr) pPrevPixmap,
			     pGC,
			     0, 0,
			     pWin->drawable.width, pWin->drawable.height,
			     0, 0);

	    /* if we couldn't copy the whole window to the buffer,
	     * send expose events (if any client wants them)
	     */
	    if (pPrevMultibuffer->eventMask & ExposureMask)
	    { /* some client wants expose events */
	    	if (pExposed)
	    	{
		    RegionPtr	pWinSize;

		    pWinSize = CreateUnclippedWinSize (pWin);
		    /* pExposed is window-relative, but at this point
		     * pWinSize is screen-relative.  Make pWinSize be
		     * window-relative so that region ops involving
		     * pExposed and pWinSize behave sensibly.
		     */
		    REGION_TRANSLATE(pWin->drawable.pScreen, pWinSize,
				     -pWin->drawable.x, -pWin->drawable.y);
		    REGION_INTERSECT(pWin->drawable.pScreen, pExposed,
				     pExposed, pWinSize);
		    REGION_DESTROY(pWin->drawable.pScreen, pWinSize);
	    	    MultibufferExpose (pPrevMultibuffer, pExposed);
	    	    REGION_DESTROY(pWin->drawable.pScreen, pExposed);
	    	}
	    	graphicsExpose = FALSE;
	    	DoChangeGC (pGC, GCGraphicsExposures, &graphicsExpose, FALSE);
	    }
	    break; /* end case MultibufferUpdateActionUntouched */

	case MultibufferUpdateActionCopied:
	    ValidateGC ((DrawablePtr)pPrevPixmap, pGC);
	    (*pGC->ops->CopyArea) ((DrawablePtr)pNewPixmap,
				   (DrawablePtr)pPrevPixmap, pGC,
				   0, 0,
				   pWin->drawable.width, pWin->drawable.height,
				   0, 0);
	    break;
	} /* end switch on update action */

	/* display the new buffer */
	ValidateGC ((DrawablePtr)pWin, pGC);
	(*pGC->ops->CopyArea) ((DrawablePtr)pNewPixmap, (DrawablePtr)pWin, pGC,
			       0, 0,
			       pWin->drawable.width, pWin->drawable.height,
			       0, 0);
	ppMultibuffers[i]->lastUpdate = currentTime;
	MultibufferUpdate (pMultibuffer[i],
			   ppMultibuffers[i]->lastUpdate.milliseconds);
	AliasMultibuffer (ppMultibuffers[i],
			  pMultibuffer[i] - ppMultibuffers[i]->buffers);
	FreeScratchGC (pGC);
    }
}

DrawablePtr
GetBufferPointer (pWin, i)
    WindowPtr	pWin;
    int		i;
{
    MultibuffersPtr pMultibuffers;

    if (!(pMultibuffers = (MultibuffersPtr) dixLookupPrivate(&pWin->devPrivates, MultibufferWindowPrivKey)))
	return NULL;
    return (DrawablePtr) pMultibuffers->buffers[i].pPixmap;
}

static Bool
QueueDisplayRequest (client, activateTime)
    ClientPtr	    client;
    TimeStamp	    activateTime;
{
    /* see xtest.c:ProcXTestFakeInput for code similar to this */

    if (!ClientSleepUntil(client, &activateTime, NULL, NULL))
    {
	return FALSE;
    }
    /* swap the request back so we can simply re-execute it */
    if (client->swapped)
    {
    	int    n;
    	REQUEST (xMbufDisplayImageBuffersReq);
    	
    	SwapRestL(stuff);
    	swaps (&stuff->length, n);
    	swaps (&stuff->minDelay, n);
    	swaps (&stuff->maxDelay, n);
    }
    ResetCurrentRequest (client);
    client->sequence--;
    return TRUE;
}


/*
 * Deliver events to a buffer
 */

static int
DeliverEventsToMultibuffer (pMultibuffer, pEvents, count, filter)
    MultibufferPtr	pMultibuffer;
    xEvent	*pEvents;
    int		count;
    Mask	filter;
{
    int deliveries = 0, nondeliveries = 0;
    int attempt;
    OtherClients *other;

    /* if nobody wants the event, we're done */
    if (!((pMultibuffer->otherEventMask|pMultibuffer->eventMask) & filter))
	return 0;

    /* maybe send event to owner */
    if ((attempt = TryClientEvents(
	bClient(pMultibuffer), NULL, pEvents, count, pMultibuffer->eventMask, filter, (GrabPtr) 0)) != 0)
    {
	if (attempt > 0)
	    deliveries++;
	else
	    nondeliveries--;
    }

    /* maybe send event to other clients */
    for (other = pMultibuffer->otherClients; other; other=other->next)
    {
	if ((attempt = TryClientEvents(
	      rClient(other), NULL, pEvents, count, other->mask, filter, (GrabPtr) 0)) != 0)
	{
	    if (attempt > 0)
		deliveries++;
	    else
		nondeliveries--;
	}
    }
    if (deliveries)
	return deliveries;
    return nondeliveries;
}

/*
 * Send Expose events to interested clients
 */

void
MultibufferExpose (pMultibuffer, pRegion)
    MultibufferPtr	pMultibuffer;
    RegionPtr	pRegion;
{
    if (pRegion && !REGION_NIL(pRegion))
    {
	xEvent *pEvent;
	PixmapPtr   pPixmap;
	xEvent *pe;
	BoxPtr pBox;
	int i;
	int numRects;

	pPixmap = pMultibuffer->pPixmap;
	REGION_TRANSLATE(pPixmap->drawable.pScreen, pRegion,
		    -pPixmap->drawable.x, -pPixmap->drawable.y);
	/* XXX MultibufferExpose "knows" the region representation */
	numRects = REGION_NUM_RECTS(pRegion);
	pBox = REGION_RECTS(pRegion);

	pEvent = xalloc(numRects * sizeof(xEvent));
	if (pEvent) {
	    pe = pEvent;

	    for (i=1; i<=numRects; i++, pe++, pBox++)
	    {
		pe->u.u.type = Expose;
		pe->u.expose.window = pPixmap->drawable.id;
		pe->u.expose.x = pBox->x1;
		pe->u.expose.y = pBox->y1;
		pe->u.expose.width = pBox->x2 - pBox->x1;
		pe->u.expose.height = pBox->y2 - pBox->y1;
		pe->u.expose.count = (numRects - i);
	    }
	    (void) DeliverEventsToMultibuffer (pMultibuffer, pEvent, numRects,
					       ExposureMask);
	    xfree(pEvent);
	}
    }
}

/* send UpdateNotify event */
void
MultibufferUpdate (pMultibuffer, time2)
    MultibufferPtr	pMultibuffer;
    CARD32	time2;
{
    xMbufUpdateNotifyEvent	event;

    event.type = MultibufferEventBase + MultibufferUpdateNotify;
    event.buffer = pMultibuffer->pPixmap->drawable.id;
    event.timeStamp = time2;
    (void) DeliverEventsToMultibuffer (pMultibuffer, (xEvent *)&event,
				1, (Mask)MultibufferUpdateNotifyMask);
}

/*
 * The sample implementation will never generate MultibufferClobberNotify
 * events
 */

void
MultibufferClobber (pMultibuffer)
    MultibufferPtr	pMultibuffer;
{
    xMbufClobberNotifyEvent	event;

    event.type = MultibufferEventBase + MultibufferClobberNotify;
    event.buffer = pMultibuffer->pPixmap->drawable.id;
    event.state = pMultibuffer->clobber;
    (void) DeliverEventsToMultibuffer (pMultibuffer, (xEvent *)&event,
				1, (Mask)MultibufferClobberNotifyMask);
}

/*
 * make the resource id for buffer i refer to the window
 * drawable instead of the pixmap;
 */

static void
AliasMultibuffer (pMultibuffers, i)
    MultibuffersPtr	pMultibuffers;
    int		i;
{
    MultibufferPtr	pMultibuffer;

    if (i == pMultibuffers->displayedMultibuffer)
	return;
    /*
     * remove the old association
     */
    if (pMultibuffers->displayedMultibuffer >= 0)
    {
	pMultibuffer = &pMultibuffers->buffers[pMultibuffers->displayedMultibuffer];
	ChangeResourceValue (pMultibuffer->pPixmap->drawable.id,
			     MultibufferDrawableResType,
 			     (pointer) pMultibuffer->pPixmap);
    }
    /*
     * make the new association
     */
    pMultibuffer = &pMultibuffers->buffers[i];
    ChangeResourceValue (pMultibuffer->pPixmap->drawable.id,
			 MultibufferDrawableResType,
			 (pointer) pMultibuffers->pWindow);
    pMultibuffers->displayedMultibuffer = i;
}

/*
 * free everything associated with multibuffering for this
 * window
 */

void
DestroyImageBuffers (pWin)
    WindowPtr	pWin;
{
    FreeResourceByType (pWin->drawable.id, MultibuffersResType, FALSE);
    /* Zero out the window's pointer to the buffers so they won't be reused */
    dixSetPrivate(&pWin->devPrivates, MultibufferWindowPrivKey, NULL);
}

/*
 * resize the buffers when the window is resized
 */ 

static Bool
MultibufferPositionWindow (pWin, x, y)
    WindowPtr	pWin;
    int		x, y;
{
    ScreenPtr	    pScreen;
    MultibufferScreenPtr pMultibufferScreen;
    MultibuffersPtr	    pMultibuffers;
    MultibufferPtr	    pMultibuffer;
    int		    width, height;
    int		    i;
    int		    dx, dy, dw, dh;
    int		    sourcex, sourcey;
    int		    destx, desty;
    PixmapPtr	    pPixmap;
    GCPtr	    pGC;
    int		    savewidth, saveheight;
    xRectangle	    clearRect;
    Bool	    clear;

    pScreen = pWin->drawable.pScreen;
    pMultibufferScreen = (MultibufferScreenPtr) dixLookupPrivate(&pScreen->devPrivates, MultibufferScreenPrivKey);
    (*pMultibufferScreen->PositionWindow) (pWin, x, y);

    /* if this window is not multibuffered, we're done */
    if (!(pMultibuffers = (MultibuffersPtr) dixLookupPrivate(&pWin->devPrivates, MultibufferWindowPrivKey)))
	return TRUE;

    /* if new size is same as old, we're done */
    if (pMultibuffers->width == pWin->drawable.width &&
        pMultibuffers->height == pWin->drawable.height)
	return TRUE;

    width = pWin->drawable.width;
    height = pWin->drawable.height;
    dx = pWin->drawable.x - pMultibuffers->x;
    dy = pWin->drawable.x - pMultibuffers->y;
    dw = width - pMultibuffers->width;
    dh = height - pMultibuffers->height;
    GravityTranslate (0, 0, -dx, -dy, dw, dh,
		      pWin->bitGravity, &destx, &desty);

    /* if the window grew, remember to paint the window background,
     * and maybe send expose events, for the new areas of the buffers
     */
    clear = pMultibuffers->width < width || pMultibuffers->height < height ||
		pWin->bitGravity == ForgetGravity;

    sourcex = 0;
    sourcey = 0;
    savewidth = pMultibuffers->width;
    saveheight = pMultibuffers->height;
    /* clip rectangle to source and destination */
    if (destx < 0)
    {
	savewidth += destx;
	sourcex -= destx;
	destx = 0;
    }
    if (destx + savewidth > width)
	savewidth = width - destx;
    if (desty < 0)
    {
	saveheight += desty;
	sourcey -= desty;
	desty = 0;
    }
    if (desty + saveheight > height)
	saveheight = height - desty;

    pMultibuffers->width = width;
    pMultibuffers->height = height;
    pMultibuffers->x = pWin->drawable.x;
    pMultibuffers->y = pWin->drawable.y;

    pGC = GetScratchGC (pWin->drawable.depth, pScreen);
    if (clear)
    {
	SetupBackgroundPainter (pWin, pGC);
	clearRect.x = 0;
	clearRect.y = 0;
	clearRect.width = width;
	clearRect.height = height;
    }
    for (i = 0; i < pMultibuffers->numMultibuffer; i++)
    {
	pMultibuffer = &pMultibuffers->buffers[i];
	pPixmap = (*pScreen->CreatePixmap) (pScreen, width, height,
					    pWin->drawable.depth,
					    CREATE_PIXMAP_USAGE_SCRATCH);
	if (!pPixmap)
	{
	    DestroyImageBuffers (pWin);
	    break;
	}
	ValidateGC ((DrawablePtr)pPixmap, pGC);
	/*
	 * I suppose this could avoid quite a bit of work if
	 * it computed the minimal area required.
	 */
	if (clear)
	    (*pGC->ops->PolyFillRect) ((DrawablePtr)pPixmap, pGC, 1, &clearRect);
	if (pWin->bitGravity != ForgetGravity)
	{
	    (*pGC->ops->CopyArea) ((DrawablePtr)pMultibuffer->pPixmap,
				   (DrawablePtr)pPixmap, pGC,
				    sourcex, sourcey, savewidth, saveheight,
				    destx, desty);
	}
	pPixmap->drawable.id = pMultibuffer->pPixmap->drawable.id;
	(*pScreen->DestroyPixmap) (pMultibuffer->pPixmap);
	pMultibuffer->pPixmap = pPixmap;
	if (i != pMultibuffers->displayedMultibuffer)
	{
	    ChangeResourceValue (pPixmap->drawable.id,
				 MultibufferDrawableResType,
				 (pointer) pPixmap);
	}
    }
    FreeScratchGC (pGC);
    return TRUE;
}

/* Resource delete func for MultibufferDrawableResType */
/*ARGSUSED*/
static int
MultibufferDrawableDelete (value, id)
    pointer	value;
    XID		id;
{
    DrawablePtr	pDrawable = (DrawablePtr)value;
    WindowPtr	pWin;
    MultibuffersPtr	pMultibuffers;
    PixmapPtr	pPixmap;

    if (pDrawable->type == DRAWABLE_WINDOW)
    {
	pWin = (WindowPtr) pDrawable;
	pMultibuffers = (MultibuffersPtr) dixLookupPrivate(&pWin->devPrivates, MultibufferWindowPrivKey);
	pPixmap = pMultibuffers->buffers[pMultibuffers->displayedMultibuffer].pPixmap;
    }
    else
    {
	pPixmap = (PixmapPtr) pDrawable;
    }
    (*pPixmap->drawable.pScreen->DestroyPixmap) (pPixmap);
    return Success;
}

/* Resource delete func for MultibufferResType */
/*ARGSUSED*/
static int
MultibufferDelete (value, id)
    pointer	value;
    XID		id;
{
    MultibufferPtr	pMultibuffer = (MultibufferPtr)value;
    MultibuffersPtr	pMultibuffers;

    pMultibuffers = pMultibuffer->pMultibuffers;
    if (--pMultibuffers->refcnt == 0)
    {
	FreeResourceByType (pMultibuffers->pWindow->drawable.id,
			    MultibuffersResType, TRUE);
	xfree (pMultibuffers);
    }
    return Success;
}

/* Resource delete func for MultibuffersResType */
/*ARGSUSED*/
static int
MultibuffersDelete (value, id)
    pointer	value;
    XID		id;
{
    MultibuffersPtr	pMultibuffers = (MultibuffersPtr)value;
    int	i;

    if (pMultibuffers->refcnt == pMultibuffers->numMultibuffer)
    {
	for (i = pMultibuffers->numMultibuffer; --i >= 0; )
	    FreeResource (pMultibuffers->buffers[i].pPixmap->drawable.id, 0);
    }
    return Success;
}

/* Resource delete func for OtherClientResType */
static int
OtherClientDelete (value, id)
    pointer	value;
    XID		id;
{
    MultibufferPtr	pMultibuffer = (MultibufferPtr)value;
    OtherClientsPtr	other, prev;

    prev = 0;
    for (other = pMultibuffer->otherClients; other; other = other->next)
    {
	if (other->resource == id)
	{
	    if (prev)
		prev->next = other->next;
	    else
		pMultibuffer->otherClients = other->next;
	    xfree (other);
	    RecalculateMultibufferOtherEvents (pMultibuffer);
	    break;
	}
	prev = other;
    }
    return Success;
}

static int
EventSelectForMultibuffer (pMultibuffer, client, mask)
    MultibufferPtr	pMultibuffer;
    ClientPtr	client;
    Mask	mask;
{
    OtherClientsPtr	other;

    if (mask & ~ValidEventMasks)
    {
	client->errorValue = mask;
	return BadValue;
    }
    if (bClient (pMultibuffer) == client)
    {
	pMultibuffer->eventMask = mask;
    }
    else /* some other client besides the creator wants events */
    {
	for (other = pMultibuffer->otherClients; other; other = other->next)
	{
	    if (SameClient (other, client))
	    {
		if (mask == 0)
		{
		    FreeResource (other->resource, RT_NONE);
		    break;
		}
		other->mask = mask;
		break;
	    }
	}
	if (!other)
	{ /* new client that never selected events on this buffer before */
	    other = xalloc (sizeof (OtherClients));
	    if (!other)
		return BadAlloc;
	    other->mask = mask;
	    other->resource = FakeClientID (client->index);
	    if (!AddResource (other->resource, OtherClientResType, (pointer) pMultibuffer))
	    {
		xfree (other);
		return BadAlloc;
	    }
	    other->next = pMultibuffer->otherClients;
	    pMultibuffer->otherClients = other;
	}
	RecalculateMultibufferOtherEvents (pMultibuffer);
    }
    return (client->noClientException);
}

/* or together all the otherClients event masks */
static void
RecalculateMultibufferOtherEvents (pMultibuffer)
    MultibufferPtr	pMultibuffer;
{
    Mask	    otherEventMask;
    OtherClients    *other;

    otherEventMask = 0L;
    for (other = pMultibuffer->otherClients; other; other = other->next)
	otherEventMask |= other->mask;
    pMultibuffer->otherEventMask = otherEventMask;
}

/* add milliseconds to a timestamp, handling overflow */
static void
BumpTimeStamp (ts, inc)
TimeStamp   *ts;
CARD32	    inc;
{
    CARD32  newms;

    newms = ts->milliseconds + inc;
    if (newms < ts->milliseconds)
	ts->months++;
    ts->milliseconds = newms;
}