summaryrefslogtreecommitdiffstats
path: root/generic/tkGrab.c
blob: 00d4511a343089cde102f99a9825a7387fe899d5 (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
/*
 * tkGrab.c --
 *
 *	This file provides functions that implement grabs for Tk.
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"

#ifdef _WIN32
#include "tkWinInt.h"
#elif !defined(MAC_OSX_TK)
#include "tkUnixInt.h"
#endif

/*
 * The grab state machine has four states: ungrabbed, button pressed, grabbed,
 * and button pressed while grabbed. In addition, there are three pieces of
 * grab state information: the current grab window, the current restrict
 * window, and whether the mouse is captured.
 *
 * The current grab window specifies the point in the Tk window heirarchy
 * above which pointer events will not be reported. Any window within the
 * subtree below the grab window will continue to receive events as normal.
 * Events outside of the grab tree will be reported to the grab window.
 *
 * If the current restrict window is set, then all pointer events will be
 * reported only to the restrict window. The restrict window is normally set
 * during an automatic button grab.
 *
 * The mouse capture state specifies whether the window system will report
 * mouse events outside of any Tk toplevels. This is set during a global grab
 * or an automatic button grab.
 *
 * The transitions between different states is given in the following table:
 *
 * Event\State	U	B	G	GB
 * -----------	--	--	--	--
 * FirstPress	B	B	GB	GB
 * Press	B	B	G	GB
 * Release	U	B	G	GB
 * LastRelease	U	U	G	G
 * Grab		G	G	G	G
 * Ungrab	U	B	U	U
 *
 * Note: U=Ungrabbed, B=Button, G=Grabbed, GB=Grab and Button
 *
 * In addition, the following conditions are always true:
 *
 * State\Variable	Grab	     Restrict	     Capture
 * --------------	----	     --------	     -------
 * Ungrabbed		 0		0		0
 * Button		 0		1		1
 * Grabbed		 1		0		b/g
 * Grab and Button	 1		1		1
 *
 * Note: 0 means variable is set to NULL, 1 means variable is set to some
 * window, b/g means the variable is set to a window if a button is currently
 * down or a global grab is in effect.
 *
 * The final complication to all of this is enter and leave events. In order
 * to correctly handle all of the various cases, Tk cannot rely on X
 * enter/leave events in all situations. The following describes the correct
 * sequence of enter and leave events that should be observed by Tk scripts:
 *
 * Event(state)		Enter/Leave From -> To
 * ------------		----------------------
 * LastRelease(B | GB): restrict window -> anc(grab window, event window)
 * Grab(U | B): 	event window -> anc(grab window, event window)
 * Grab(G):		anc(old grab window, event window) ->
 * 				anc(new grab window, event window)
 * Grab(GB):		restrict window -> anc(new grab window, event window)
 * Ungrab(G):		anc(grab window, event window) -> event window
 * Ungrab(GB):		restrict window -> event window
 *
 * Note: anc(x,y) returns the least ancestor of y that is in the tree of x,
 * terminating at toplevels.
 */

/*
 * The following structure is used to pass information to GrabRestrictProc
 * from EatGrabEvents.
 */

typedef struct {
    Display *display;		/* Display from which to discard events. */
    unsigned int serial;	/* Serial number with which to compare. */
} GrabInfo;

/*
 * Bit definitions for grabFlags field of TkDisplay structures:
 *
 * GRAB_GLOBAL			1 means this is a global grab (we grabbed via
 *				the server so all applications are locked out).
 *				0 means this is a local grab that affects only
 *				this application.
 * GRAB_TEMP_GLOBAL		1 means we've temporarily grabbed via the
 *				server because a button is down and we want to
 *				make sure that we get the button-up event. The
 *				grab will be released when the last mouse
 *				button goes up.
 */

#define GRAB_GLOBAL		1
#define GRAB_TEMP_GLOBAL	4

/*
 * The following structure is a Tcl_Event that triggers a change in the
 * grabWinPtr field of a display. This event guarantees that the change occurs
 * in the proper order relative to enter and leave events.
 */

typedef struct NewGrabWinEvent {
    Tcl_Event header;		/* Standard information for all Tcl events. */
    TkDisplay *dispPtr;		/* Display whose grab window is to change. */
    Window grabWindow;		/* New grab window for display. This is
				 * recorded instead of a (TkWindow *) because
				 * it will allow us to detect cases where the
				 * window is destroyed before this event is
				 * processed. */
} NewGrabWinEvent;

/*
 * The following magic value is stored in the "send_event" field of
 * EnterNotify and LeaveNotify events that are generated in this file. This
 * allows us to separate "real" events coming from the server from those that
 * we generated.
 */

#define GENERATED_GRAB_EVENT_MAGIC ((Bool) 0x147321ac)

/*
 * Mask that selects any of the state bits corresponding to buttons, plus
 * masks that select individual buttons' bits:
 */

#define ALL_BUTTONS \
	(Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask)
static const unsigned int buttonStates[] = {
    Button1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask
};

/*
 * Forward declarations for functions declared later in this file:
 */

static void		EatGrabEvents(TkDisplay *dispPtr, unsigned int serial);
static TkWindow *	FindCommonAncestor(TkWindow *winPtr1,
			    TkWindow *winPtr2, int *countPtr1, int *countPtr2);
static Tk_RestrictProc GrabRestrictProc;
static int		GrabWinEventProc(Tcl_Event *evPtr, int flags);
static void		MovePointer2(TkWindow *sourcePtr, TkWindow *destPtr,
			    int mode, int leaveEvents, int EnterEvents);
static void		QueueGrabWindowChange(TkDisplay *dispPtr,
			    TkWindow *grabWinPtr);
static void		ReleaseButtonGrab(TkDisplay *dispPtr);

/*
 *----------------------------------------------------------------------
 *
 * Tk_GrabObjCmd --
 *
 *	This function is invoked to process the "grab" Tcl command. See the
 *	user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *----------------------------------------------------------------------
 */

	/* ARGSUSED */
int
Tk_GrabObjCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    int globalGrab;
    Tk_Window tkwin;
    TkDisplay *dispPtr;
    const char *arg;
    int index;
    int len;
    static const char *const optionStrings[] = {
	"current", "release", "set", "status", NULL
    };
    static const char *const flagStrings[] = {
	"-global", NULL
    };
    enum options {
	GRABCMD_CURRENT, GRABCMD_RELEASE, GRABCMD_SET, GRABCMD_STATUS
    };

    if (objc < 2) {
	/*
	 * Can't use Tcl_WrongNumArgs here because we want the message to
	 * read:
	 * wrong # args: should be "cmd ?-global? window" or "cmd option
	 *    ?arg ...?"
	 * We can fake it with Tcl_WrongNumArgs if we assume the command name
	 * is "grab", but if it has been aliased, the message will be
	 * incorrect.
	 */

	Tcl_WrongNumArgs(interp, 1, objv, "?-global? window");
	Tcl_AppendResult(interp, " or \"", Tcl_GetString(objv[0]),
		" option ?arg ...?\"", NULL);
	/* This API not exposed:
	 *
	((Interp *) interp)->flags |= INTERP_ALTERNATE_WRONG_ARGS;
	Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
	 */
	return TCL_ERROR;
    }

    /*
     * First check for a window name or "-global" as the first argument.
     */

    arg = Tcl_GetStringFromObj(objv[1], &len);
    if (arg[0] == '.') {
	/* [grab window] */
	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 1, objv, "?-global? window");
	    return TCL_ERROR;
	}
	tkwin = Tk_NameToWindow(interp, arg, clientData);
	if (tkwin == NULL) {
	    return TCL_ERROR;
	}
	return Tk_Grab(interp, tkwin, 0);
    } else if (arg[0] == '-' && len > 1) {
	if (Tcl_GetIndexFromObj(interp, objv[1], flagStrings, "option", 0,
		&index) != TCL_OK) {
	    return TCL_ERROR;
	}

	/* [grab -global window] */
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 1, objv, "?-global? window");
	    return TCL_ERROR;
	}
	tkwin = Tk_NameToWindow(interp, Tcl_GetString(objv[2]), clientData);
	if (tkwin == NULL) {
	    return TCL_ERROR;
	}
	return Tk_Grab(interp, tkwin, 1);
    }

    /*
     * First argument is not a window name and not "-global", find out which
     * option it is.
     */

    if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0,
	    &index) != TCL_OK) {
	return TCL_ERROR;
    }

    switch ((enum options) index) {
    case GRABCMD_CURRENT:
	/* [grab current ?window?] */
	if (objc > 3) {
	    Tcl_WrongNumArgs(interp, 1, objv, "current ?window?");
	    return TCL_ERROR;
	}
	if (objc == 3) {
	    tkwin = Tk_NameToWindow(interp, Tcl_GetString(objv[2]),
		    clientData);
	    if (tkwin == NULL) {
		return TCL_ERROR;
	    }
	    dispPtr = ((TkWindow *) tkwin)->dispPtr;
	    if (dispPtr->eventualGrabWinPtr != NULL) {
		Tcl_SetObjResult(interp, TkNewWindowObj((Tk_Window)
			dispPtr->eventualGrabWinPtr));
	    }
	} else {
	    Tcl_Obj *resultObj = Tcl_NewObj();

	    for (dispPtr = TkGetDisplayList(); dispPtr != NULL;
		    dispPtr = dispPtr->nextPtr) {
		if (dispPtr->eventualGrabWinPtr != NULL) {
		    Tcl_ListObjAppendElement(NULL, resultObj, TkNewWindowObj(
			    (Tk_Window) dispPtr->eventualGrabWinPtr));
		}
	    }
	    Tcl_SetObjResult(interp, resultObj);
	}
	return TCL_OK;

    case GRABCMD_RELEASE:
	/* [grab release window] */
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 1, objv, "release window");
	    return TCL_ERROR;
	}
	tkwin = Tk_NameToWindow(interp, Tcl_GetString(objv[2]), clientData);
	if (tkwin == NULL) {
	    Tcl_ResetResult(interp);
	} else {
	    Tk_Ungrab(tkwin);
	}
	break;

    case GRABCMD_SET:
	/* [grab set ?-global? window] */
	if ((objc != 3) && (objc != 4)) {
	    Tcl_WrongNumArgs(interp, 1, objv, "set ?-global? window");
	    return TCL_ERROR;
	}
	if (objc == 3) {
	    globalGrab = 0;
	    tkwin = Tk_NameToWindow(interp, Tcl_GetString(objv[2]),
		    clientData);
	} else {
	    globalGrab = 1;

	    /*
	     * We could just test the argument by hand instead of using
	     * Tcl_GetIndexFromObj; the benefit of using the function is that
	     * it sets up the error message for us, so we are certain to be
	     * consistant with the rest of Tcl.
	     */

	    if (Tcl_GetIndexFromObj(interp, objv[2], flagStrings, "option",
		    0, &index) != TCL_OK) {
		return TCL_ERROR;
	    }
	    tkwin = Tk_NameToWindow(interp, Tcl_GetString(objv[3]),
		    clientData);
	}
	if (tkwin == NULL) {
	    return TCL_ERROR;
	}
	return Tk_Grab(interp, tkwin, globalGrab);

    case GRABCMD_STATUS: {
	/* [grab status window] */
	TkWindow *winPtr;
	const char *statusString;

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 1, objv, "status window");
	    return TCL_ERROR;
	}
	winPtr = (TkWindow *) Tk_NameToWindow(interp, Tcl_GetString(objv[2]),
		clientData);
	if (winPtr == NULL) {
	    return TCL_ERROR;
	}
	dispPtr = winPtr->dispPtr;
	if (dispPtr->eventualGrabWinPtr != winPtr) {
	    statusString = "none";
	} else if (dispPtr->grabFlags & GRAB_GLOBAL) {
	    statusString = "global";
	} else {
	    statusString = "local";
	}
	Tcl_SetObjResult(interp, Tcl_NewStringObj(statusString, -1));
	break;
    }
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_Grab --
 *
 *	Grabs the pointer and keyboard, so that mouse-related events are only
 *	reported relative to a given window and its descendants.
 *
 * Results:
 *	A standard Tcl result is returned. TCL_OK is the normal return value;
 *	if the grab could not be set then TCL_ERROR is returned and the
 *	interp's result will hold an error message.
 *
 * Side effects:
 *	Once this call completes successfully, no window outside the tree
 *	rooted at tkwin will receive pointer- or keyboard-related events until
 *	the next call to Tk_Ungrab. If a previous grab was in effect within
 *	this application, then it is replaced with a new one.
 *
 *----------------------------------------------------------------------
 */

int
Tk_Grab(
    Tcl_Interp *interp,		/* Used for error reporting. */
    Tk_Window tkwin,		/* Window on whose behalf the pointer is to be
				 * grabbed. */
    int grabGlobal)		/* Non-zero means issue a grab to the server
				 * so that no other application gets mouse or
				 * keyboard events. Zero means the grab only
				 * applies within this application. */
{
    int grabResult, numTries;
    TkWindow *winPtr = (TkWindow *) tkwin;
    TkDisplay *dispPtr = winPtr->dispPtr;
    TkWindow *winPtr2;
    unsigned int serial;

    ReleaseButtonGrab(dispPtr);
    if (dispPtr->eventualGrabWinPtr != NULL) {
	if ((dispPtr->eventualGrabWinPtr == winPtr)
		&& (grabGlobal == ((dispPtr->grabFlags & GRAB_GLOBAL) != 0))) {
	    return TCL_OK;
	}
	if (dispPtr->eventualGrabWinPtr->mainPtr != winPtr->mainPtr) {
	    goto alreadyGrabbed;
	}
	Tk_Ungrab((Tk_Window) dispPtr->eventualGrabWinPtr);
    }

    Tk_MakeWindowExist(tkwin);
#ifndef MAC_OSX_TK
    if (!grabGlobal)
#else
    if (0)
#endif /* MAC_OSX_TK */
    {
	Window dummy1, dummy2;
	int dummy3, dummy4, dummy5, dummy6;
	unsigned int state;

	/*
	 * Local grab. However, if any mouse buttons are down, turn it into a
	 * global grab temporarily, until the last button goes up. This does
	 * two things: (a) it makes sure that we see the button-up event; and
	 * (b) it allows us to track mouse motion among all of the windows of
	 * this application.
	 */

	dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL);
	XQueryPointer(dispPtr->display, winPtr->window, &dummy1,
		&dummy2, &dummy3, &dummy4, &dummy5, &dummy6, &state);
	if (state & ALL_BUTTONS) {
	    dispPtr->grabFlags |= GRAB_TEMP_GLOBAL;
	    goto setGlobalGrab;
	}
    } else {
	dispPtr->grabFlags |= GRAB_GLOBAL;
    setGlobalGrab:

	/*
	 * Tricky point: must ungrab before grabbing. This is needed in case
	 * there is a button auto-grab already in effect. If there is, and the
	 * mouse has moved to a different window, X won't generate enter and
	 * leave events to move the mouse if we grab without ungrabbing.
	 */

	XUngrabPointer(dispPtr->display, CurrentTime);
	serial = NextRequest(dispPtr->display);

	/*
	 * Another tricky point: there are races with some window managers
	 * that can cause grabs to fail because the window manager hasn't
	 * released its grab quickly enough. To work around this problem,
	 * retry a few times after AlreadyGrabbed errors to give the grab
	 * release enough time to register with the server.
	 */

	grabResult = 0;			/* Needed only to prevent gcc compiler
					 * warnings. */
	for (numTries = 0; numTries < 10; numTries++) {
	    grabResult = XGrabPointer(dispPtr->display, winPtr->window,
		    True, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask
		    |PointerMotionMask, GrabModeAsync, GrabModeAsync, None,
		    None, CurrentTime);
	    if (grabResult != AlreadyGrabbed) {
		break;
	    }
	    Tcl_Sleep(100);
	}
	if (grabResult != 0) {
	    goto grabError;
	}
	grabResult = XGrabKeyboard(dispPtr->display, Tk_WindowId(tkwin),
		False, GrabModeAsync, GrabModeAsync, CurrentTime);
	if (grabResult != 0) {
	    XUngrabPointer(dispPtr->display, CurrentTime);
	    goto grabError;
	}

	/*
	 * Eat up any grab-related events generated by the server for the
	 * grab. There are several reasons for doing this:
	 *
	 * 1. We have to synthesize the events for local grabs anyway, since
	 *    the server doesn't participate in them.
	 * 2. The server doesn't always generate the right events for global
	 *    grabs (e.g. it generates events even if the current window is in
	 *    the grab tree, which we don't want).
	 * 3. We want all the grab-related events to be processed immediately
	 *    (before other events that are already queued); events coming
	 *    from the server will be in the wrong place, but events we
	 *    synthesize here will go to the front of the queue.
	 */

	EatGrabEvents(dispPtr, serial);
    }

    /*
     * Synthesize leave events to move the pointer from its current window up
     * to the lowest ancestor that it has in common with the grab window.
     * However, only do this if the pointer is outside the grab window's
     * subtree but inside the grab window's application.
     */

    if ((dispPtr->serverWinPtr != NULL)
	    && (dispPtr->serverWinPtr->mainPtr == winPtr->mainPtr)) {
	for (winPtr2 = dispPtr->serverWinPtr; ; winPtr2 = winPtr2->parentPtr) {
	    if (winPtr2 == winPtr) {
		break;
	    }
	    if (winPtr2 == NULL) {
		MovePointer2(dispPtr->serverWinPtr, winPtr, NotifyGrab, 1, 0);
		break;
	    }
	}
    }
    QueueGrabWindowChange(dispPtr, winPtr);
    return TCL_OK;

  grabError:
    if (grabResult == GrabNotViewable) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"grab failed: window not viewable", -1));
	Tcl_SetErrorCode(interp, "TK", "GRAB", "UNVIEWABLE", NULL);
    } else if (grabResult == AlreadyGrabbed) {
    alreadyGrabbed:
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"grab failed: another application has grab", -1));
	Tcl_SetErrorCode(interp, "TK", "GRAB", "GRABBED", NULL);
    } else if (grabResult == GrabFrozen) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"grab failed: keyboard or pointer frozen", -1));
	Tcl_SetErrorCode(interp, "TK", "GRAB", "FROZEN", NULL);
    } else if (grabResult == GrabInvalidTime) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"grab failed: invalid time", -1));
	Tcl_SetErrorCode(interp, "TK", "GRAB", "BAD_TIME", NULL);
    } else {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"grab failed for unknown reason (code %d)", grabResult));
	Tcl_SetErrorCode(interp, "TK", "GRAB", "UNKNOWN", NULL);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_Ungrab --
 *
 *	Releases a grab on the mouse pointer and keyboard, if there is one set
 *	on the specified window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Pointer and keyboard events will start being delivered to other
 *	windows again.
 *
 *----------------------------------------------------------------------
 */

void
Tk_Ungrab(
    Tk_Window tkwin)		/* Window whose grab should be released. */
{
    TkDisplay *dispPtr;
    TkWindow *grabWinPtr, *winPtr;
    unsigned int serial;

    grabWinPtr = (TkWindow *) tkwin;
    dispPtr = grabWinPtr->dispPtr;
    if (grabWinPtr != dispPtr->eventualGrabWinPtr) {
	return;
    }
    ReleaseButtonGrab(dispPtr);
    QueueGrabWindowChange(dispPtr, NULL);
    if (dispPtr->grabFlags & (GRAB_GLOBAL|GRAB_TEMP_GLOBAL)) {
	dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL);
	serial = NextRequest(dispPtr->display);
	XUngrabPointer(dispPtr->display, CurrentTime);
	XUngrabKeyboard(dispPtr->display, CurrentTime);
	EatGrabEvents(dispPtr, serial);
    }

    /*
     * Generate events to move the pointer back to the window where it really
     * is. Some notes:
     * 1. As with grabs, only do this if the "real" window is not a descendant
     *    of the grab window, since in this case the pointer is already where
     *    it's supposed to be.
     * 2. If the "real" window is in some other application then don't
     *    generate any events at all, since everything's already been reported
     *    correctly.
     * 3. Only generate enter events. Don't generate leave events, because we
     *    never told the lower-level windows that they had the pointer in the
     *    first place.
     */

    for (winPtr = dispPtr->serverWinPtr; ; winPtr = winPtr->parentPtr) {
	if (winPtr == grabWinPtr) {
	    break;
	}
	if (winPtr == NULL) {
	    if ((dispPtr->serverWinPtr == NULL) ||
		    (dispPtr->serverWinPtr->mainPtr == grabWinPtr->mainPtr)) {
		MovePointer2(grabWinPtr, dispPtr->serverWinPtr,
			NotifyUngrab, 0, 1);
	    }
	    break;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ReleaseButtonGrab --
 *
 *	This function is called to release a simulated button grab, if there
 *	is one in effect. A button grab is present whenever
 *	dispPtr->buttonWinPtr is non-NULL or when the GRAB_TEMP_GLOBAL flag is
 *	set.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	DispPtr->buttonWinPtr is reset to NULL, and enter and leave events are
 *	generated if necessary to move the pointer from the button grab window
 *	to its current window.
 *
 *----------------------------------------------------------------------
 */

static void
ReleaseButtonGrab(
    register TkDisplay *dispPtr)/* Display whose button grab is to be
				 * released. */
{
    unsigned int serial;

    if (dispPtr->buttonWinPtr != NULL) {
	if (dispPtr->buttonWinPtr != dispPtr->serverWinPtr) {
	    MovePointer2(dispPtr->buttonWinPtr, dispPtr->serverWinPtr,
		    NotifyUngrab, 1, 1);
	}
	dispPtr->buttonWinPtr = NULL;
    }
    if (dispPtr->grabFlags & GRAB_TEMP_GLOBAL) {
	dispPtr->grabFlags &= ~GRAB_TEMP_GLOBAL;
	serial = NextRequest(dispPtr->display);
	XUngrabPointer(dispPtr->display, CurrentTime);
	XUngrabKeyboard(dispPtr->display, CurrentTime);
	EatGrabEvents(dispPtr, serial);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkPointerEvent --
 *
 *	This function is called for each pointer-related event, before the
 *	event has been processed. It does various things to make grabs work
 *	correctly.
 *
 * Results:
 *	If the return value is 1 it means the event should be processed (event
 *	handlers should be invoked). If the return value is 0 it means the
 *	event should be ignored in order to make grabs work correctly. In some
 *	cases this function modifies the event.
 *
 * Side effects:
 *	Grab state information may be updated. New events may also be pushed
 *	back onto the event queue to replace or augment the one passed in
 *	here.
 *
 *----------------------------------------------------------------------
 */

int
TkPointerEvent(
    register XEvent *eventPtr,	/* Pointer to the event. */
    TkWindow *winPtr)		/* Tk's information for window where event was
				 * reported. */
{
    register TkWindow *winPtr2;
    TkDisplay *dispPtr = winPtr->dispPtr;
    unsigned int serial;
    int outsideGrabTree = 0;
    int ancestorOfGrab = 0;
    int appGrabbed = 0;		/* Non-zero means event is being reported to
				 * an application that is affected by the
				 * grab. */

    /*
     * Collect information about the grab (if any).
     */

    switch (TkGrabState(winPtr)) {
    case TK_GRAB_IN_TREE:
	appGrabbed = 1;
	break;
    case TK_GRAB_ANCESTOR:
	appGrabbed = 1;
	outsideGrabTree = 1;
	ancestorOfGrab = 1;
	break;
    case TK_GRAB_EXCLUDED:
	appGrabbed = 1;
	outsideGrabTree = 1;
	break;
    }

    if ((eventPtr->type == EnterNotify) || (eventPtr->type == LeaveNotify)) {
	/*
	 * Keep track of what window the mouse is *really* over. Any events
	 * that we generate have a special send_event value, which is detected
	 * below and used to ignore the event for purposes of setting
	 * serverWinPtr.
	 */

	if (eventPtr->xcrossing.send_event != GENERATED_GRAB_EVENT_MAGIC) {
	    if ((eventPtr->type == LeaveNotify) &&
		    (winPtr->flags & TK_TOP_HIERARCHY)) {
		dispPtr->serverWinPtr = NULL;
	    } else {
		dispPtr->serverWinPtr = winPtr;
	    }
	}

	/*
	 * When a grab is active, X continues to report enter and leave events
	 * for windows outside the tree of the grab window:
	 * 1. Detect these events and ignore them except for windows above the
	 *    grab window.
	 * 2. Allow Enter and Leave events to pass through the windows above
	 *    the grab window, but never let them end up with the pointer *in*
	 *    one of those windows.
	 */

	if (dispPtr->grabWinPtr != NULL) {
	    if (outsideGrabTree && appGrabbed) {
		if (!ancestorOfGrab) {
		    return 0;
		}
		switch (eventPtr->xcrossing.detail) {
		case NotifyInferior:
		    return 0;
		case NotifyAncestor:
		    eventPtr->xcrossing.detail = NotifyVirtual;
		    break;
		case NotifyNonlinear:
		    eventPtr->xcrossing.detail = NotifyNonlinearVirtual;
		    break;
		}
	    }

	    /*
	     * Make buttons have the same grab-like behavior inside a grab as
	     * they do outside a grab: do this by ignoring enter and leave
	     * events except for the window in which the button was pressed.
	     */

	    if ((dispPtr->buttonWinPtr != NULL)
		    && (winPtr != dispPtr->buttonWinPtr)) {
		return 0;
	    }
	}
	return 1;
    }

    if (!appGrabbed) {
	return 1;
    }

    if (eventPtr->type == MotionNotify) {
	/*
	 * When grabs are active, X reports motion events relative to the
	 * window under the pointer. Instead, it should report the events
	 * relative to the window the button went down in, if there is a
	 * button down. Otherwise, if the pointer window is outside the
	 * subtree of the grab window, the events should be reported relative
	 * to the grab window. Otherwise, the event should be reported to the
	 * pointer window.
	 */

	winPtr2 = winPtr;
	if (dispPtr->buttonWinPtr != NULL) {
	    winPtr2 = dispPtr->buttonWinPtr;
	} else if (outsideGrabTree || (dispPtr->serverWinPtr == NULL)) {
	    winPtr2 = dispPtr->grabWinPtr;
	}
	if (winPtr2 != winPtr) {
	    TkChangeEventWindow(eventPtr, winPtr2);
	    Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD);
	    return 0;
	}
	return 1;
    }

    /*
     * Process ButtonPress and ButtonRelease events:
     * 1. Keep track of whether a button is down and what window it went down
     *    in.
     * 2. If the first button goes down outside the grab tree, pretend it went
     *    down in the grab window. Note: it's important to redirect events to
     *    the grab window like this in order to make things like menus work,
     *    where button presses outside the grabbed menu need to be seen. An
     *    application can always ignore the events if they occur outside its
     *    window.
     * 3. If a button press or release occurs outside the window where the
     *    first button was pressed, retarget the event so it's reported to the
     *    window where the first button was pressed.
     * 4. If the last button is released in a window different than where the
     *    first button was pressed, generate Enter/Leave events to move the
     *    mouse from the button window to its current window.
     * 5. If the grab is set at a time when a button is already down, or if
     *    the window where the button was pressed was deleted, then
     *    dispPtr->buttonWinPtr will stay NULL. Just forget about the
     *    auto-grab for the button press; events will go to whatever window
     *    contains the pointer. If this window isn't in the grab tree then
     *    redirect events to the grab window.
     * 6. When a button is pressed during a local grab, the X server sets a
     *    grab of its own, since it doesn't even know about our local grab.
     *    This causes enter and leave events no longer to be generated in the
     *    same way as for global grabs. To eliminate this problem, set a
     *    temporary global grab when the first button goes down and release it
     *    when the last button comes up.
     */

    if ((eventPtr->type == ButtonPress) || (eventPtr->type == ButtonRelease)) {
	winPtr2 = dispPtr->buttonWinPtr;
	if (winPtr2 == NULL) {
	    if (outsideGrabTree) {
		winPtr2 = dispPtr->grabWinPtr;			/* Note 5. */
	    } else {
		winPtr2 = winPtr;				/* Note 5. */
	    }
	}
	if (eventPtr->type == ButtonPress) {
	    if (!(eventPtr->xbutton.state & ALL_BUTTONS)) {
		if (outsideGrabTree) {
		    TkChangeEventWindow(eventPtr, dispPtr->grabWinPtr);
		    Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD);
		    return 0;					/* Note 2. */
		}
		if (!(dispPtr->grabFlags & GRAB_GLOBAL)) {	/* Note 6. */
		    serial = NextRequest(dispPtr->display);
		    if (XGrabPointer(dispPtr->display,
			    dispPtr->grabWinPtr->window, True,
			    ButtonPressMask|ButtonReleaseMask|ButtonMotionMask,
			    GrabModeAsync, GrabModeAsync, None, None,
			    CurrentTime) == 0) {
			EatGrabEvents(dispPtr, serial);
			if (XGrabKeyboard(dispPtr->display, winPtr->window,
				False, GrabModeAsync, GrabModeAsync,
				CurrentTime) == 0) {
			    dispPtr->grabFlags |= GRAB_TEMP_GLOBAL;
			} else {
			    XUngrabPointer(dispPtr->display, CurrentTime);
			}
		    }
		}
		dispPtr->buttonWinPtr = winPtr;
		return 1;
	    }
	} else {
	    if ((eventPtr->xbutton.state & ALL_BUTTONS)
		    == buttonStates[eventPtr->xbutton.button - Button1]) {
		ReleaseButtonGrab(dispPtr);			/* Note 4. */
	    }
	}
	if (winPtr2 != winPtr) {
	    TkChangeEventWindow(eventPtr, winPtr2);
	    Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD);
	    return 0;						/* Note 3. */
	}
    }

    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkChangeEventWindow --
 *
 *	Given an event and a new window to which the event should be
 *	retargeted, modify fields of the event so that the event is properly
 *	retargeted to the new window.
 *
 * Results:
 *	The following fields of eventPtr are modified: window, subwindow, x,
 *	y, same_screen.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkChangeEventWindow(
    register XEvent *eventPtr,	/* Event to retarget. Must have type
				 * ButtonPress, ButtonRelease, KeyPress,
				 * KeyRelease, MotionNotify, EnterNotify, or
				 * LeaveNotify. */
    TkWindow *winPtr)		/* New target window for event. */
{
    int x, y, sameScreen, bd;
    register TkWindow *childPtr;

    eventPtr->xmotion.window = Tk_WindowId(winPtr);
    if (eventPtr->xmotion.root ==
	    RootWindow(winPtr->display, winPtr->screenNum)) {
	Tk_GetRootCoords((Tk_Window) winPtr, &x, &y);
	eventPtr->xmotion.x = eventPtr->xmotion.x_root - x;
	eventPtr->xmotion.y = eventPtr->xmotion.y_root - y;
	eventPtr->xmotion.subwindow = None;
	for (childPtr = winPtr->childList; childPtr != NULL;
		childPtr = childPtr->nextPtr) {
	    if (childPtr->flags & TK_TOP_HIERARCHY) {
		continue;
	    }
	    x = eventPtr->xmotion.x - childPtr->changes.x;
	    y = eventPtr->xmotion.y - childPtr->changes.y;
	    bd = childPtr->changes.border_width;
	    if ((x >= -bd) && (y >= -bd)
		    && (x < (childPtr->changes.width + bd))
		    && (y < (childPtr->changes.height + bd))) {
		eventPtr->xmotion.subwindow = childPtr->window;
	    }
	}
	sameScreen = 1;
    } else {
	eventPtr->xmotion.x = 0;
	eventPtr->xmotion.y = 0;
	eventPtr->xmotion.subwindow = None;
	sameScreen = 0;
    }
    if (eventPtr->type == MotionNotify) {
	eventPtr->xmotion.same_screen = sameScreen;
    } else {
	eventPtr->xbutton.same_screen = sameScreen;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkInOutEvents --
 *
 *	This function synthesizes EnterNotify and LeaveNotify events to
 *	correctly transfer the pointer from one window to another. It can also
 *	be used to generate FocusIn and FocusOut events to move the input
 *	focus.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Synthesized events may be pushed back onto the event queue. The event
 *	pointed to by eventPtr is modified.
 *
 *----------------------------------------------------------------------
 */

void
TkInOutEvents(
    XEvent *eventPtr,		/* A template X event. Must have all fields
				 * properly set except for type, window,
				 * subwindow, x, y, detail, and same_screen.
				 * (Not all of these fields are valid for
				 * FocusIn/FocusOut events; x_root and y_root
				 * must be valid for Enter/Leave events, even
				 * though x and y needn't be valid). */
    TkWindow *sourcePtr,	/* Window that used to have the pointer or
				 * focus (NULL means it was not in a window
				 * managed by this process). */
    TkWindow *destPtr,		/* Window that is to end up with the pointer
				 * or focus (NULL means it's not one managed
				 * by this process). */
    int leaveType,		/* Type of events to generate for windows
				 * being left (LeaveNotify or FocusOut). 0
				 * means don't generate leave events. */
    int enterType,		/* Type of events to generate for windows
				 * being entered (EnterNotify or FocusIn). 0
				 * means don't generate enter events. */
    Tcl_QueuePosition position)	/* Position at which events are added to the
				 * system event queue. */
{
    register TkWindow *winPtr;
    int upLevels, downLevels, i, j, focus;

    /*
     * There are four possible cases to deal with:
     *
     * 1. SourcePtr and destPtr are the same. There's nothing to do in this
     *    case.
     * 2. SourcePtr is an ancestor of destPtr in the same top-level window.
     *    Must generate events down the window tree from source to dest.
     * 3. DestPtr is an ancestor of sourcePtr in the same top-level window.
     *    Must generate events up the window tree from sourcePtr to destPtr.
     * 4. All other cases. Must first generate events up the window tree from
     *    sourcePtr to its top-level, then down from destPtr's top-level to
     *    destPtr. This form is called "non-linear."
     *
     * The call to FindCommonAncestor separates these four cases and decides
     * how many levels up and down events have to be generated for.
     */

    if (sourcePtr == destPtr) {
	return;
    }
    if ((leaveType == FocusOut) || (enterType == FocusIn)) {
	focus = 1;
    } else {
	focus = 0;
    }
    FindCommonAncestor(sourcePtr, destPtr, &upLevels, &downLevels);

    /*
     * Generate enter/leave events and add them to the grab event queue.
     */

#define QUEUE(w, t, d)					\
    if (w->window != None) {				\
	eventPtr->type = t;				\
	if (focus) {					\
	    eventPtr->xfocus.window = w->window;	\
	    eventPtr->xfocus.detail = d;		\
	} else {					\
	    eventPtr->xcrossing.detail = d;		\
	    TkChangeEventWindow(eventPtr, w);		\
	}						\
	Tk_QueueWindowEvent(eventPtr, position);	\
    }

    if (downLevels == 0) {
	/*
	 * SourcePtr is an inferior of destPtr.
	 */

	if (leaveType != 0) {
	    QUEUE(sourcePtr, leaveType, NotifyAncestor);
	    for (winPtr = sourcePtr->parentPtr, i = upLevels-1; i > 0;
		    winPtr = winPtr->parentPtr, i--) {
		QUEUE(winPtr, leaveType, NotifyVirtual);
	    }
	}
	if ((enterType != 0) && (destPtr != NULL)) {
	    QUEUE(destPtr, enterType, NotifyInferior);
	}
    } else if (upLevels == 0) {
	/*
	 * DestPtr is an inferior of sourcePtr.
	 */

	if ((leaveType != 0) && (sourcePtr != NULL)) {
	    QUEUE(sourcePtr, leaveType, NotifyInferior);
	}
	if (enterType != 0) {
	    for (i = downLevels-1; i > 0; i--) {
		for (winPtr = destPtr->parentPtr, j = 1; j < i;
			winPtr = winPtr->parentPtr, j++) {
		    /* empty */
		}
		QUEUE(winPtr, enterType, NotifyVirtual);
	    }
	    if (destPtr != NULL) {
		QUEUE(destPtr, enterType, NotifyAncestor);
	    }
	}
    } else {
	/*
	 * Non-linear: neither window is an inferior of the other.
	 */

	if (leaveType != 0) {
	    QUEUE(sourcePtr, leaveType, NotifyNonlinear);
	    for (winPtr = sourcePtr->parentPtr, i = upLevels-1; i > 0;
		    winPtr = winPtr->parentPtr, i--) {
		QUEUE(winPtr, leaveType, NotifyNonlinearVirtual);
	    }
	}
	if (enterType != 0) {
	    for (i = downLevels-1; i > 0; i--) {
		for (winPtr = destPtr->parentPtr, j = 1; j < i;
			winPtr = winPtr->parentPtr, j++) {
		}
		QUEUE(winPtr, enterType, NotifyNonlinearVirtual);
	    }
	    if (destPtr != NULL) {
		QUEUE(destPtr, enterType, NotifyNonlinear);
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MovePointer2 --
 *
 *	This function synthesizes EnterNotify and LeaveNotify events to
 *	correctly transfer the pointer from one window to another. It is
 *	different from TkInOutEvents in that no template X event needs to be
 *	supplied; this function generates the template event and calls
 *	TkInOutEvents.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Synthesized events may be pushed back onto the event queue.
 *
 *----------------------------------------------------------------------
 */

static void
MovePointer2(
    TkWindow *sourcePtr,	/* Window currently containing pointer (NULL
				 * means it's not one managed by this
				 * process). */
    TkWindow *destPtr,		/* Window that is to end up containing the
				 * pointer (NULL means it's not one managed by
				 * this process). */
    int mode,			/* Mode for enter/leave events, such as
				 * NotifyNormal or NotifyUngrab. */
    int leaveEvents,		/* Non-zero means generate leave events for
				 * the windows being left. Zero means don't
				 * generate leave events. */
    int enterEvents)		/* Non-zero means generate enter events for
				 * the windows being entered. Zero means don't
				 * generate enter events. */
{
    XEvent event;
    Window dummy1, dummy2;
    int dummy3, dummy4;
    TkWindow *winPtr;

    winPtr = sourcePtr;
    if ((winPtr == NULL) || (winPtr->window == None)) {
	winPtr = destPtr;
	if ((winPtr == NULL) || (winPtr->window == None)) {
	    return;
	}
    }

    event.xcrossing.serial = LastKnownRequestProcessed(winPtr->display);
    event.xcrossing.send_event = GENERATED_GRAB_EVENT_MAGIC;
    event.xcrossing.display = winPtr->display;
    event.xcrossing.root = RootWindow(winPtr->display, winPtr->screenNum);
    event.xcrossing.time = TkCurrentTime(winPtr->dispPtr);
    XQueryPointer(winPtr->display, winPtr->window, &dummy1, &dummy2,
	    &event.xcrossing.x_root, &event.xcrossing.y_root,
	    &dummy3, &dummy4, &event.xcrossing.state);
    event.xcrossing.mode = mode;
    event.xcrossing.focus = False;
    TkInOutEvents(&event, sourcePtr, destPtr, (leaveEvents) ? LeaveNotify : 0,
	    (enterEvents) ? EnterNotify : 0, TCL_QUEUE_MARK);
}

/*
 *----------------------------------------------------------------------
 *
 * TkGrabDeadWindow --
 *
 *	This function is invoked whenever a window is deleted, so that
 *	grab-related cleanup can be performed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Various cleanups happen, such as generating events to move the pointer
 *	back to its "natural" window as if an ungrab had been done. See the
 *	code.
 *
 *----------------------------------------------------------------------
 */

void
TkGrabDeadWindow(
    register TkWindow *winPtr)	/* Window that is in the process of being
				 * deleted. */
{
    TkDisplay *dispPtr = winPtr->dispPtr;

    if (dispPtr->eventualGrabWinPtr == winPtr) {
	/*
	 * Grab window was deleted. Release the grab.
	 */

	Tk_Ungrab((Tk_Window) dispPtr->eventualGrabWinPtr);
    } else if (dispPtr->buttonWinPtr == winPtr) {
	ReleaseButtonGrab(dispPtr);
    }
    if (dispPtr->serverWinPtr == winPtr) {
	if (winPtr->flags & TK_TOP_HIERARCHY) {
	    dispPtr->serverWinPtr = NULL;
	} else {
	    dispPtr->serverWinPtr = winPtr->parentPtr;
	}
    }
    if (dispPtr->grabWinPtr == winPtr) {
	dispPtr->grabWinPtr = NULL;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * EatGrabEvents --
 *
 *	This function is called to eliminate any Enter, Leave, FocusIn, or
 *	FocusOut events in the event queue for a display that have mode
 *	NotifyGrab or NotifyUngrab and have a serial number no less than a
 *	given value and are not generated by the grab module.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	DispPtr's display gets sync-ed, and some of the events get removed
 *	from the Tk event queue.
 *
 *----------------------------------------------------------------------
 */

static void
EatGrabEvents(
    TkDisplay *dispPtr,		/* Display from which to consume events. */
    unsigned int serial)	/* Only discard events that have a serial
				 * number at least this great. */
{
    Tk_RestrictProc *prevProc;
    GrabInfo info;
    ClientData prevArg;

    info.display = dispPtr->display;
    info.serial = serial;
    TkpSync(info.display);
    prevProc = Tk_RestrictEvents(GrabRestrictProc, &info, &prevArg);
    while (Tcl_ServiceEvent(TCL_WINDOW_EVENTS)) {
	/* EMPTY */
    }
    Tk_RestrictEvents(prevProc, prevArg, &prevArg);
}

/*
 *----------------------------------------------------------------------
 *
 * GrabRestrictProc --
 *
 *	A Tk_RestrictProc used by EatGrabEvents to eliminate any Enter, Leave,
 *	FocusIn, or FocusOut events in the event queue for a display that has
 *	mode NotifyGrab or NotifyUngrab and have a serial number no less than
 *	a given value.
 *
 * Results:
 *	Returns either TK_DISCARD_EVENT or TK_DEFER_EVENT.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static Tk_RestrictAction
GrabRestrictProc(
    ClientData arg,
    XEvent *eventPtr)
{
    GrabInfo *info = arg;
    int mode, diff;

    /*
     * The diff caculation is trickier than it may seem. Don't forget that
     * serial numbers can wrap around, so can't compare the two serial numbers
     * directly.
     */

    diff = eventPtr->xany.serial - info->serial;
    if ((eventPtr->type == EnterNotify)
	    || (eventPtr->type == LeaveNotify)) {
	mode = eventPtr->xcrossing.mode;
    } else if ((eventPtr->type == FocusIn)
	    || (eventPtr->type == FocusOut)) {
	mode = eventPtr->xfocus.mode;
    } else {
	mode = NotifyNormal;
    }
    if ((info->display != eventPtr->xany.display) || (mode == NotifyNormal)
	    || (diff < 0)) {
	return TK_DEFER_EVENT;
    } else {
	return TK_DISCARD_EVENT;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * QueueGrabWindowChange --
 *
 *	This function queues a special event in the Tcl event queue, which
 *	will cause the "grabWinPtr" field for the display to get modified when
 *	the event is processed. This is needed to make sure that the grab
 *	window changes at the proper time relative to grab-related enter and
 *	leave events that are also in the queue. In particular, this approach
 *	works even when multiple grabs and ungrabs happen back-to-back.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	DispPtr->grabWinPtr will be modified later (by GrabWinEventProc) when
 *	the event is removed from the grab event queue.
 *
 *----------------------------------------------------------------------
 */

static void
QueueGrabWindowChange(
    TkDisplay *dispPtr,		/* Display on which to change the grab
				 * window. */
    TkWindow *grabWinPtr)	/* Window that is to become the new grab
				 * window (may be NULL). */
{
    NewGrabWinEvent *grabEvPtr;

    grabEvPtr = ckalloc(sizeof(NewGrabWinEvent));
    grabEvPtr->header.proc = GrabWinEventProc;
    grabEvPtr->dispPtr = dispPtr;
    if (grabWinPtr == NULL) {
	grabEvPtr->grabWindow = None;
    } else {
	grabEvPtr->grabWindow = grabWinPtr->window;
    }
    Tcl_QueueEvent(&grabEvPtr->header, TCL_QUEUE_MARK);
    dispPtr->eventualGrabWinPtr = grabWinPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * GrabWinEventProc --
 *
 *	This function is invoked as a handler for Tcl_Events of type
 *	NewGrabWinEvent. It updates the current grab window field in a
 *	display.
 *
 * Results:
 *	Returns 1 if the event was processed, 0 if it should be deferred for
 *	processing later.
 *
 * Side effects:
 *	The grabWinPtr field is modified in the display associated with the
 *	event.
 *
 *----------------------------------------------------------------------
 */

static int
GrabWinEventProc(
    Tcl_Event *evPtr,		/* Event of type NewGrabWinEvent. */
    int flags)			/* Flags argument to Tk_DoOneEvent: indicates
				 * what kinds of events are being processed
				 * right now. */
{
    NewGrabWinEvent *grabEvPtr = (NewGrabWinEvent *) evPtr;

    grabEvPtr->dispPtr->grabWinPtr = (TkWindow *) Tk_IdToWindow(
	    grabEvPtr->dispPtr->display, grabEvPtr->grabWindow);
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * FindCommonAncestor --
 *
 *	Given two windows, this function finds their least common ancestor and
 *	also computes how many levels up this ancestor is from each of the
 *	original windows.
 *
 * Results:
 *	If the windows are in different applications or top-level windows,
 *	then NULL is returned and *countPtr1 and *countPtr2 are set to the
 *	depths of the two windows in their respective top-level windows (1
 *	means the window is a top-level, 2 means its parent is a top-level,
 *	and so on). Otherwise, the return value is a pointer to the common
 *	ancestor and the counts are set to the distance of winPtr1 and winPtr2
 *	from this ancestor (1 means they're children, 2 means grand-children,
 *	etc.).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static TkWindow *
FindCommonAncestor(
    TkWindow *winPtr1,		/* First window. May be NULL. */
    TkWindow *winPtr2,		/* Second window. May be NULL. */
    int *countPtr1,		/* Store nesting level of winPtr1 within
				 * common ancestor here. */
    int *countPtr2)		/* Store nesting level of winPtr2 within
				 * common ancestor here. */
{
    register TkWindow *winPtr;
    TkWindow *ancestorPtr;
    int count1, count2, i;

    /*
     * Mark winPtr1 and all of its ancestors with a special flag bit.
     */

    if (winPtr1 != NULL) {
	for (winPtr = winPtr1; winPtr != NULL; winPtr = winPtr->parentPtr) {
	    winPtr->flags |= TK_GRAB_FLAG;
	    if (winPtr->flags & TK_TOP_HIERARCHY) {
		break;
	    }
	}
    }

    /*
     * Search upwards from winPtr2 until an ancestor of winPtr1 is found or a
     * top-level window is reached.
     */

    winPtr = winPtr2;
    count2 = 0;
    ancestorPtr = NULL;
    if (winPtr2 != NULL) {
	for (; winPtr != NULL; count2++, winPtr = winPtr->parentPtr) {
	    if (winPtr->flags & TK_GRAB_FLAG) {
		ancestorPtr = winPtr;
		break;
	    }
	    if (winPtr->flags & TK_TOP_HIERARCHY)  {
		count2++;
		break;
	    }
	}
    }

    /*
     * Search upwards from winPtr1 again, clearing the flag bits and
     * remembering how many levels up we had to go.
     */

    if (winPtr1 == NULL) {
	count1 = 0;
    } else {
	count1 = -1;
	for (i = 0, winPtr = winPtr1; winPtr != NULL;
		i++, winPtr = winPtr->parentPtr) {
	    winPtr->flags &= ~TK_GRAB_FLAG;
	    if (winPtr == ancestorPtr) {
		count1 = i;
	    }
	    if (winPtr->flags & TK_TOP_HIERARCHY) {
		if (count1 == -1) {
		    count1 = i+1;
		}
		break;
	    }
	}
    }

    *countPtr1 = count1;
    *countPtr2 = count2;
    return ancestorPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPositionInTree --
 *
 *	Compute where the given window is relative to a particular subtree of
 *	the window hierarchy.
 *
 * Results:
 *	Returns TK_GRAB_IN_TREE if the window is contained in the subtree.
 *	Returns TK_GRAB_ANCESTOR if the window is an ancestor of the subtree,
 *	in the same toplevel. Otherwise it returns TK_GRAB_EXCLUDED.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkPositionInTree(
    TkWindow *winPtr,		/* Window to be checked. */
    TkWindow *treePtr)		/* Root of tree to compare against. */
{
    TkWindow *winPtr2;

    for (winPtr2 = winPtr; winPtr2 != treePtr;
	   winPtr2 = winPtr2->parentPtr) {
	if (winPtr2 == NULL) {
	    for (winPtr2 = treePtr; winPtr2 != NULL;
		    winPtr2 = winPtr2->parentPtr) {
		if (winPtr2 == winPtr) {
		    return TK_GRAB_ANCESTOR;
		}
		if (winPtr2->flags & TK_TOP_HIERARCHY) {
		    break;
		}
	    }
	    return TK_GRAB_EXCLUDED;
	}
    }
    return TK_GRAB_IN_TREE;
}

/*
 *----------------------------------------------------------------------
 *
 * TkGrabState --
 *
 *	Given a window, this function returns a value that indicates the grab
 *	state of the application relative to the window.
 *
 * Results:
 *	The return value is one of three things:
 *	    TK_GRAB_NONE -	no grab is in effect.
 *	    TK_GRAB_IN_TREE -   there is a grab in effect, and winPtr is in
 *				the grabbed subtree.
 *	    TK_GRAB_ANCESTOR -  there is a grab in effect; winPtr is an
 *				ancestor of the grabbed window, in the same
 *				toplevel.
 *	    TK_GRAB_EXCLUDED -	there is a grab in effect; winPtr is outside
 *				the tree of the grab and is not an ancestor of
 *				the grabbed window in the same toplevel.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkGrabState(
    TkWindow *winPtr)		/* Window for which grab information is
				 * needed. */
{
    TkWindow *grabWinPtr = winPtr->dispPtr->grabWinPtr;

    if (grabWinPtr == NULL) {
	return TK_GRAB_NONE;
    }
    if ((winPtr->mainPtr != grabWinPtr->mainPtr)
	    && !(winPtr->dispPtr->grabFlags & GRAB_GLOBAL)) {
	return TK_GRAB_NONE;
    }

    return TkPositionInTree(winPtr, grabWinPtr);
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */
s_y_origin, NULL); oldBrush = SelectObject(dc, stipple); SetTextAlign(dcMem, TA_LEFT | TA_BASELINE); SetTextColor(dcMem, gc->foreground); SetBkMode(dcMem, TRANSPARENT); SetBkColor(dcMem, RGB(0, 0, 0)); /* * Compute the bounding box and create a compatible bitmap. */ GetTextExtentPoint(dcMem, source, numBytes, &size); GetTextMetrics(dcMem, &tm); size.cx -= tm.tmOverhang; bitmap = CreateCompatibleBitmap(dc, size.cx, size.cy); oldBitmap = SelectObject(dcMem, bitmap); /* * The following code is tricky because fonts are rendered in multiple * colors. First we draw onto a black background and copy the white * bits. Then we draw onto a white background and copy the black bits. * Both the foreground and background bits of the font are ANDed with * the stipple pattern as they are copied. */ PatBlt(dcMem, 0, 0, size.cx, size.cy, BLACKNESS); MultiFontTextOut(dc, fontPtr, source, numBytes, x, y); BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem, 0, 0, 0xEA02E9); PatBlt(dcMem, 0, 0, size.cx, size.cy, WHITENESS); MultiFontTextOut(dc, fontPtr, source, numBytes, x, y); BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem, 0, 0, 0x8A0E06); /* * Destroy the temporary bitmap and restore the device context. */ SelectObject(dcMem, oldBitmap); DeleteObject(bitmap); DeleteDC(dcMem); SelectObject(dc, oldBrush); DeleteObject(stipple); } else if (gc->function == GXcopy) { SetTextAlign(dc, TA_LEFT | TA_BASELINE); SetTextColor(dc, gc->foreground); SetBkMode(dc, TRANSPARENT); MultiFontTextOut(dc, fontPtr, source, numBytes, x, y); } else { HBITMAP oldBitmap, bitmap; HDC dcMem; TEXTMETRIC tm; SIZE size; dcMem = CreateCompatibleDC(dc); SetTextAlign(dcMem, TA_LEFT | TA_BASELINE); SetTextColor(dcMem, gc->foreground); SetBkMode(dcMem, TRANSPARENT); SetBkColor(dcMem, RGB(0, 0, 0)); /* * Compute the bounding box and create a compatible bitmap. */ GetTextExtentPoint(dcMem, source, numBytes, &size); GetTextMetrics(dcMem, &tm); size.cx -= tm.tmOverhang; bitmap = CreateCompatibleBitmap(dc, size.cx, size.cy); oldBitmap = SelectObject(dcMem, bitmap); MultiFontTextOut(dcMem, fontPtr, source, numBytes, 0, tm.tmAscent); BitBlt(dc, x, y - tm.tmAscent, size.cx, size.cy, dcMem, 0, 0, (DWORD) tkpWinBltModes[gc->function]); /* * Destroy the temporary bitmap and restore the device context. */ SelectObject(dcMem, oldBitmap); DeleteObject(bitmap); DeleteDC(dcMem); } TkWinReleaseDrawableDC(drawable, dc, &state); } /* *--------------------------------------------------------------------------- * * TkpDrawCharsInContext -- * * Draw a string of characters on the screen like Tk_DrawChars(), but * with access to all the characters on the line for context. On Windows * this context isn't consulted, so we just call Tk_DrawChars(). * * Results: * None. * * Side effects: * Information gets drawn on the screen. * *--------------------------------------------------------------------------- */ void TkpDrawCharsInContext( Display *display, /* Display on which to draw. */ Drawable drawable, /* Window or pixmap in which to draw. */ GC gc, /* Graphics context for drawing characters. */ Tk_Font tkfont, /* Font in which characters will be drawn; * must be the same as font used in GC. */ CONST char *source, /* UTF-8 string to be displayed. Need not be * '\0' terminated. All Tk meta-characters * (tabs, control characters, and newlines) * should be stripped out of the string that * is passed to this function. If they are not * stripped out, they will be displayed as * regular printing characters. */ int numBytes, /* Number of bytes in string. */ int rangeStart, /* Index of first byte to draw. */ int rangeLength, /* Length of range to draw in bytes. */ int x, int y) /* Coordinates at which to place origin of the * whole (not just the range) string when * drawing. */ { (void) numBytes; /*unused*/ Tk_DrawChars(display, drawable, gc, tkfont, source + rangeStart, rangeLength, x, y); } /* *------------------------------------------------------------------------- * * MultiFontTextOut -- * * Helper function for Tk_DrawChars. Draws characters, using the various * screen fonts in fontPtr to draw multilingual characters. Note: No * bidirectional support. * * Results: * None. * * Side effects: * Information gets drawn on the screen. Contents of fontPtr may be * modified if more subfonts were loaded in order to draw all the * multilingual characters in the given string. * *------------------------------------------------------------------------- */ static void MultiFontTextOut( HDC hdc, /* HDC to draw into. */ WinFont *fontPtr, /* Contains set of fonts to use when drawing * following string. */ CONST char *source, /* Potentially multilingual UTF-8 string. */ int numBytes, /* Length of string in bytes. */ int x, int y) /* Coordinates at which to place origin of * string when drawing. */ { Tcl_UniChar ch; SIZE size; HFONT oldFont; FontFamily *familyPtr; Tcl_DString runString; CONST char *p, *end, *next; SubFont *lastSubFontPtr, *thisSubFontPtr; TEXTMETRIC tm; lastSubFontPtr = &fontPtr->subFontArray[0]; oldFont = SelectObject(hdc, lastSubFontPtr->hFont); GetTextMetrics(hdc, &tm); end = source + numBytes; for (p = source; p < end; ) { next = p + Tcl_UtfToUniChar(p, &ch); thisSubFontPtr = FindSubFontForChar(fontPtr, ch, &lastSubFontPtr); if (thisSubFontPtr != lastSubFontPtr) { if (p > source) { familyPtr = lastSubFontPtr->familyPtr; Tcl_UtfToExternalDString(familyPtr->encoding, source, (int) (p - source), &runString); (*familyPtr->textOutProc)(hdc, x-(tm.tmOverhang/2), y, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString)>>familyPtr->isWideFont); (*familyPtr->getTextExtentPoint32Proc)(hdc, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString) >> familyPtr->isWideFont, &size); x += size.cx; Tcl_DStringFree(&runString); } lastSubFontPtr = thisSubFontPtr; source = p; SelectObject(hdc, lastSubFontPtr->hFont); GetTextMetrics(hdc, &tm); } p = next; } if (p > source) { familyPtr = lastSubFontPtr->familyPtr; Tcl_UtfToExternalDString(familyPtr->encoding, source, (int) (p - source), &runString); (*familyPtr->textOutProc)(hdc, x-(tm.tmOverhang/2), y, Tcl_DStringValue(&runString), Tcl_DStringLength(&runString) >> familyPtr->isWideFont); Tcl_DStringFree(&runString); } SelectObject(hdc, oldFont); } /* *--------------------------------------------------------------------------- * * InitFont -- * * Helper for TkpGetNativeFont() and TkpGetFontFromAttributes(). * Initializes the memory for a new WinFont that wraps the * platform-specific data. * * The caller is responsible for initializing the fields of the WinFont * that are used exclusively by the generic TkFont code, and for * releasing those fields before calling TkpDeleteFont(). * * Results: * Fills the WinFont structure. * * Side effects: * Memory allocated. * *--------------------------------------------------------------------------- */ static void InitFont( Tk_Window tkwin, /* Main window of interp in which font will be * used, for getting HDC. */ HFONT hFont, /* Windows token for font. */ int overstrike, /* The overstrike attribute of logfont used to * allocate this font. For some reason, the * TEXTMETRICs may contain incorrect info in * the tmStruckOut field. */ WinFont *fontPtr) /* Filled with information constructed from * the above arguments. */ { HDC hdc; HWND hwnd; HFONT oldFont; TEXTMETRIC tm; Window window; TkFontMetrics *fmPtr; Tcl_Encoding encoding; Tcl_DString faceString; TkFontAttributes *faPtr; char buf[LF_FACESIZE * sizeof(WCHAR)]; window = Tk_WindowId(tkwin); hwnd = (window == None) ? NULL : TkWinGetHWND(window); hdc = GetDC(hwnd); oldFont = SelectObject(hdc, hFont); GetTextMetrics(hdc, &tm); /* * On any version NT, there may fonts with international names. Use the * NT-only Unicode version of GetTextFace to get the font's name. If we * used the ANSI version on a non-internationalized version of NT, we * would get a font name with '?' replacing all the international * characters. * * On a non-internationalized verson of 95, fonts with international names * are not allowed, so the ANSI version of GetTextFace will work. On an * internationalized version of 95, there may be fonts with international * names; the ANSI version will work, fetching the name in the * international system code page. Can't use the Unicode version of * GetTextFace because it only exists under NT. */ if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) { GetTextFaceW(hdc, LF_FACESIZE, (WCHAR *) buf); } else { GetTextFaceA(hdc, LF_FACESIZE, (char *) buf); } Tcl_ExternalToUtfDString(systemEncoding, buf, -1, &faceString); fontPtr->font.fid = (Font) fontPtr; fontPtr->hwnd = hwnd; fontPtr->pixelSize = tm.tmHeight - tm.tmInternalLeading; faPtr = &fontPtr->font.fa; faPtr->family = Tk_GetUid(Tcl_DStringValue(&faceString)); faPtr->size = TkFontGetPoints(tkwin, -(fontPtr->pixelSize)); faPtr->weight = (tm.tmWeight > FW_MEDIUM) ? TK_FW_BOLD : TK_FW_NORMAL; faPtr->slant = (tm.tmItalic != 0) ? TK_FS_ITALIC : TK_FS_ROMAN; faPtr->underline = (tm.tmUnderlined != 0) ? 1 : 0; faPtr->overstrike = overstrike; fmPtr = &fontPtr->font.fm; fmPtr->ascent = tm.tmAscent; fmPtr->descent = tm.tmDescent; fmPtr->maxWidth = tm.tmMaxCharWidth; fmPtr->fixed = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH); fontPtr->numSubFonts = 1; fontPtr->subFontArray = fontPtr->staticSubFonts; InitSubFont(hdc, hFont, 1, &fontPtr->subFontArray[0]); encoding = fontPtr->subFontArray[0].familyPtr->encoding; if (encoding == TkWinGetUnicodeEncoding()) { GetCharWidthW(hdc, 0, BASE_CHARS - 1, fontPtr->widths); } else { GetCharWidthA(hdc, 0, BASE_CHARS - 1, fontPtr->widths); } Tcl_DStringFree(&faceString); SelectObject(hdc, oldFont); ReleaseDC(hwnd, hdc); } /* *------------------------------------------------------------------------- * * ReleaseFont -- * * Called to release the windows-specific contents of a TkFont. The * caller is responsible for freeing the memory used by the font itself. * * Results: * None. * * Side effects: * Memory is freed. * *--------------------------------------------------------------------------- */ static void ReleaseFont( WinFont *fontPtr) /* The font to delete. */ { int i; for (i = 0; i < fontPtr->numSubFonts; i++) { ReleaseSubFont(&fontPtr->subFontArray[i]); } if (fontPtr->subFontArray != fontPtr->staticSubFonts) { ckfree((char *) fontPtr->subFontArray); } } /* *------------------------------------------------------------------------- * * InitSubFont -- * * Wrap a screen font and load the FontFamily that represents it. Used to * prepare a SubFont so that characters can be mapped from UTF-8 to the * charset of the font. * * Results: * The subFontPtr is filled with information about the font. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void InitSubFont( HDC hdc, /* HDC in which font can be selected. */ HFONT hFont, /* The screen font. */ int base, /* Non-zero if this SubFont is being used as * the base font for a font object. */ SubFont *subFontPtr) /* Filled with SubFont constructed from above * attributes. */ { subFontPtr->hFont = hFont; subFontPtr->familyPtr = AllocFontFamily(hdc, hFont, base); subFontPtr->fontMap = subFontPtr->familyPtr->fontMap; } /* *------------------------------------------------------------------------- * * ReleaseSubFont -- * * Called to release the contents of a SubFont. The caller is responsible * for freeing the memory used by the SubFont itself. * * Results: * None. * * Side effects: * Memory and resources are freed. * *--------------------------------------------------------------------------- */ static void ReleaseSubFont( SubFont *subFontPtr) /* The SubFont to delete. */ { DeleteObject(subFontPtr->hFont); FreeFontFamily(subFontPtr->familyPtr); } /* *------------------------------------------------------------------------- * * AllocFontFamily -- * * Find the FontFamily structure associated with the given font name. The * information should be stored by the caller in a SubFont and used when * determining if that SubFont supports a character. * * Cannot use the string name used to construct the font as the key, * because the capitalization may not be canonical. Therefore use the * face name actually retrieved from the font metrics as the key. * * Results: * A pointer to a FontFamily. The reference count in the FontFamily is * automatically incremented. When the SubFont is released, the reference * count is decremented. When no SubFont is using this FontFamily, it may * be deleted. * * Side effects: * A new FontFamily structure will be allocated if this font family has * not been seen. TrueType character existence metrics are loaded into * the FontFamily structure. * *------------------------------------------------------------------------- */ static FontFamily * AllocFontFamily( HDC hdc, /* HDC in which font can be selected. */ HFONT hFont, /* Screen font whose FontFamily is to be * returned. */ int base) /* Non-zero if this font family is to be used * in the base font of a font object. */ { Tk_Uid faceName; FontFamily *familyPtr; Tcl_DString faceString; Tcl_Encoding encoding; char buf[LF_FACESIZE * sizeof(WCHAR)]; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); hFont = SelectObject(hdc, hFont); if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) { GetTextFaceW(hdc, LF_FACESIZE, (WCHAR *) buf); } else { GetTextFaceA(hdc, LF_FACESIZE, (char *) buf); } Tcl_ExternalToUtfDString(systemEncoding, buf, -1, &faceString); faceName = Tk_GetUid(Tcl_DStringValue(&faceString)); Tcl_DStringFree(&faceString); hFont = SelectObject(hdc, hFont); familyPtr = tsdPtr->fontFamilyList; for ( ; familyPtr != NULL; familyPtr = familyPtr->nextPtr) { if (familyPtr->faceName == faceName) { familyPtr->refCount++; return familyPtr; } } familyPtr = (FontFamily *) ckalloc(sizeof(FontFamily)); memset(familyPtr, 0, sizeof(FontFamily)); familyPtr->nextPtr = tsdPtr->fontFamilyList; tsdPtr->fontFamilyList = familyPtr; /* * Set key for this FontFamily. */ familyPtr->faceName = faceName; /* * An initial refCount of 2 means that FontFamily information will persist * even when the SubFont that loaded the FontFamily is released. Change it * to 1 to cause FontFamilies to be unloaded when not in use. */ familyPtr->refCount = 2; familyPtr->segCount = LoadFontRanges(hdc, hFont, &familyPtr->startCount, &familyPtr->endCount, &familyPtr->isSymbolFont); encoding = NULL; if (familyPtr->isSymbolFont != 0) { /* * Symbol fonts are handled specially. For instance, Unicode 0393 * (GREEK CAPITAL GAMMA) must be mapped to Symbol character 0047 * (GREEK CAPITAL GAMMA), because the Symbol font doesn't have a GREEK * CAPITAL GAMMA at location 0393. If Tk interpreted the Symbol font * using the Unicode encoding, it would decide that the Symbol font * has no GREEK CAPITAL GAMMA, because the Symbol encoding (of course) * reports that character 0393 doesn't exist. * * With non-symbol Windows fonts, such as Times New Roman, if the font * has a GREEK CAPITAL GAMMA, it will be found in the correct Unicode * location (0393); the GREEK CAPITAL GAMMA will not be off hiding at * some other location. */ encoding = Tcl_GetEncoding(NULL, faceName); } if (encoding == NULL) { encoding = Tcl_GetEncoding(NULL, "unicode"); familyPtr->textOutProc = (BOOL (WINAPI *)(HDC, int, int, TCHAR *, int)) TextOutW; familyPtr->getTextExtentPoint32Proc = (BOOL (WINAPI *)(HDC, TCHAR *, int, LPSIZE)) GetTextExtentPoint32W; familyPtr->isWideFont = 1; } else { familyPtr->textOutProc = (BOOL (WINAPI *)(HDC, int, int, TCHAR *, int)) TextOutA; familyPtr->getTextExtentPoint32Proc = (BOOL (WINAPI *)(HDC, TCHAR *, int, LPSIZE)) GetTextExtentPoint32A; familyPtr->isWideFont = 0; } familyPtr->encoding = encoding; return familyPtr; } /* *------------------------------------------------------------------------- * * FreeFontFamily -- * * Called to free a FontFamily when the SubFont is finished using it. * Frees the contents of the FontFamily and the memory used by the * FontFamily itself. * * Results: * None. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void FreeFontFamily( FontFamily *familyPtr) /* The FontFamily to delete. */ { int i; FontFamily **familyPtrPtr; ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); if (familyPtr == NULL) { return; } familyPtr->refCount--; if (familyPtr->refCount > 0) { return; } for (i = 0; i < FONTMAP_PAGES; i++) { if (familyPtr->fontMap[i] != NULL) { ckfree(familyPtr->fontMap[i]); } } if (familyPtr->startCount != NULL) { ckfree((char *) familyPtr->startCount); } if (familyPtr->endCount != NULL) { ckfree((char *) familyPtr->endCount); } if (familyPtr->encoding != TkWinGetUnicodeEncoding()) { Tcl_FreeEncoding(familyPtr->encoding); } /* * Delete from list. */ for (familyPtrPtr = &tsdPtr->fontFamilyList; ; ) { if (*familyPtrPtr == familyPtr) { *familyPtrPtr = familyPtr->nextPtr; break; } familyPtrPtr = &(*familyPtrPtr)->nextPtr; } ckfree((char *) familyPtr); } /* *------------------------------------------------------------------------- * * FindSubFontForChar -- * * Determine which screen font is necessary to use to display the given * character. If the font object does not have a screen font that can * display the character, another screen font may be loaded into the font * object, following a set of preferred fallback rules. * * Results: * The return value is the SubFont to use to display the given character. * * Side effects: * The contents of fontPtr are modified to cache the results of the * lookup and remember any SubFonts that were dynamically loaded. * *------------------------------------------------------------------------- */ static SubFont * FindSubFontForChar( WinFont *fontPtr, /* The font object with which the character * will be displayed. */ int ch, /* The Unicode character to be displayed. */ SubFont **subFontPtrPtr) /* Pointer to var to be fixed up if we * reallocate the subfont table. */ { HDC hdc; int i, j, k; CanUse canUse; char **aliases, **anyFallbacks; char ***fontFallbacks; char *fallbackName; SubFont *subFontPtr; Tcl_DString ds; if (ch < BASE_CHARS) { return &fontPtr->subFontArray[0]; } for (i = 0; i < fontPtr->numSubFonts; i++) { if (FontMapLookup(&fontPtr->subFontArray[i], ch)) { return &fontPtr->subFontArray[i]; } } /* * Keep track of all face names that we check, so we don't check some name * multiple times if it can be reached by multiple paths. */ Tcl_DStringInit(&ds); hdc = GetDC(fontPtr->hwnd); aliases = TkFontGetAliasList(fontPtr->font.fa.family); fontFallbacks = TkFontGetFallbacks(); for (i = 0; fontFallbacks[i] != NULL; i++) { for (j = 0; fontFallbacks[i][j] != NULL; j++) { fallbackName = fontFallbacks[i][j]; if (strcasecmp(fallbackName, fontPtr->font.fa.family) == 0) { /* * If the base font has a fallback... */ goto tryfallbacks; } else if (aliases != NULL) { /* * Or if an alias for the base font has a fallback... */ for (k = 0; aliases[k] != NULL; k++) { if (strcasecmp(aliases[k], fallbackName) == 0) { goto tryfallbacks; } } } } continue; /* * ...then see if we can use one of the fallbacks, or an alias for one * of the fallbacks. */ tryfallbacks: for (j = 0; fontFallbacks[i][j] != NULL; j++) { fallbackName = fontFallbacks[i][j]; subFontPtr = CanUseFallbackWithAliases(hdc, fontPtr, fallbackName, ch, &ds, subFontPtrPtr); if (subFontPtr != NULL) { goto end; } } } /* * See if we can use something from the global fallback list. */ anyFallbacks = TkFontGetGlobalClass(); for (i = 0; anyFallbacks[i] != NULL; i++) { fallbackName = anyFallbacks[i]; subFontPtr = CanUseFallbackWithAliases(hdc, fontPtr, fallbackName, ch, &ds, subFontPtrPtr); if (subFontPtr != NULL) { goto end; } } /* * Try all face names available in the whole system until we find one that * can be used. */ canUse.hdc = hdc; canUse.fontPtr = fontPtr; canUse.nameTriedPtr = &ds; canUse.ch = ch; canUse.subFontPtr = NULL; canUse.subFontPtrPtr = subFontPtrPtr; if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) { EnumFontFamiliesW(hdc, NULL, (FONTENUMPROCW) WinFontCanUseProc, (LPARAM) &canUse); } else { EnumFontFamiliesA(hdc, NULL, (FONTENUMPROCA) WinFontCanUseProc, (LPARAM) &canUse); } subFontPtr = canUse.subFontPtr; end: Tcl_DStringFree(&ds); if (subFontPtr == NULL) { /* * No font can display this character. We will use the base font and * have it display the "unknown" character. */ subFontPtr = &fontPtr->subFontArray[0]; FontMapInsert(subFontPtr, ch); } ReleaseDC(fontPtr->hwnd, hdc); return subFontPtr; } static int CALLBACK WinFontCanUseProc( ENUMLOGFONT *lfPtr, /* Logical-font data. */ NEWTEXTMETRIC *tmPtr, /* Physical-font data (not used). */ int fontType, /* Type of font (not used). */ LPARAM lParam) /* Result object to hold result. */ { int ch; HDC hdc; WinFont *fontPtr; CanUse *canUsePtr; char *fallbackName; SubFont *subFontPtr; Tcl_DString faceString; Tcl_DString *nameTriedPtr; canUsePtr = (CanUse *) lParam; ch = canUsePtr->ch; hdc = canUsePtr->hdc; fontPtr = canUsePtr->fontPtr; nameTriedPtr = canUsePtr->nameTriedPtr; fallbackName = lfPtr->elfLogFont.lfFaceName; Tcl_ExternalToUtfDString(systemEncoding, fallbackName, -1, &faceString); fallbackName = Tcl_DStringValue(&faceString); if (SeenName(fallbackName, nameTriedPtr) == 0) { subFontPtr = CanUseFallback(hdc, fontPtr, fallbackName, ch, canUsePtr->subFontPtrPtr); if (subFontPtr != NULL) { canUsePtr->subFontPtr = subFontPtr; Tcl_DStringFree(&faceString); return 0; } } Tcl_DStringFree(&faceString); return 1; } /* *------------------------------------------------------------------------- * * FontMapLookup -- * * See if the screen font can display the given character. * * Results: * The return value is 0 if the screen font cannot display the character, * non-zero otherwise. * * Side effects: * New pages are added to the font mapping cache whenever the character * belongs to a page that hasn't been seen before. When a page is loaded, * information about all the characters on that page is stored, not just * for the single character in question. * *------------------------------------------------------------------------- */ static int FontMapLookup( SubFont *subFontPtr, /* Contains font mapping cache to be queried * and possibly updated. */ int ch) /* Character to be tested. */ { int row, bitOffset; row = ch >> FONTMAP_SHIFT; if (subFontPtr->fontMap[row] == NULL) { FontMapLoadPage(subFontPtr, row); } bitOffset = ch & (FONTMAP_BITSPERPAGE - 1); return (subFontPtr->fontMap[row][bitOffset >> 3] >> (bitOffset & 7)) & 1; } /* *------------------------------------------------------------------------- * * FontMapInsert -- * * Tell the font mapping cache that the given screen font should be used * to display the specified character. This is called when no font on the * system can be be found that can display that character; we lie to the * font and tell it that it can display the character, otherwise we would * end up re-searching the entire fallback hierarchy every time that * character was seen. * * Results: * None. * * Side effects: * New pages are added to the font mapping cache whenever the character * belongs to a page that hasn't been seen before. When a page is loaded, * information about all the characters on that page is stored, not just * for the single character in question. * *------------------------------------------------------------------------- */ static void FontMapInsert( SubFont *subFontPtr, /* Contains font mapping cache to be * updated. */ int ch) /* Character to be added to cache. */ { int row, bitOffset; row = ch >> FONTMAP_SHIFT; if (subFontPtr->fontMap[row] == NULL) { FontMapLoadPage(subFontPtr, row); } bitOffset = ch & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } /* *------------------------------------------------------------------------- * * FontMapLoadPage -- * * Load information about all the characters on a given page. This * information consists of one bit per character that indicates whether * the associated HFONT can (1) or cannot (0) display the characters on * the page. * * Results: * None. * * Side effects: * Mempry allocated. * *------------------------------------------------------------------------- */ static void FontMapLoadPage( SubFont *subFontPtr, /* Contains font mapping cache to be * updated. */ int row) /* Index of the page to be loaded into the * cache. */ { FontFamily *familyPtr; Tcl_Encoding encoding; char src[TCL_UTF_MAX], buf[16]; USHORT *startCount, *endCount; int i, j, bitOffset, end, segCount; subFontPtr->fontMap[row] = (char *) ckalloc(FONTMAP_BITSPERPAGE / 8); memset(subFontPtr->fontMap[row], 0, FONTMAP_BITSPERPAGE / 8); familyPtr = subFontPtr->familyPtr; encoding = familyPtr->encoding; if (familyPtr->encoding == TkWinGetUnicodeEncoding()) { /* * Font is Unicode. Few fonts are going to have all characters, so * examine the TrueType character existence metrics to determine what * characters actually exist in this font. */ segCount = familyPtr->segCount; startCount = familyPtr->startCount; endCount = familyPtr->endCount; j = 0; end = (row + 1) << FONTMAP_SHIFT; for (i = row << FONTMAP_SHIFT; i < end; i++) { for ( ; j < segCount; j++) { if (endCount[j] >= i) { if (startCount[j] <= i) { bitOffset = i & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } break; } } } } else if (familyPtr->isSymbolFont) { /* * Assume that a symbol font with a known encoding has all the * characters that its encoding claims it supports. * * The test for "encoding == unicodeEncoding" must occur before this * case, to catch all symbol fonts (such as {Comic Sans MS} or * Wingdings) for which we don't have encoding information; those * symbol fonts are treated as if they were in the Unicode encoding * and their symbolic character existence metrics are treated as if * they were Unicode character existence metrics. This way, although * we don't know the proper Unicode -> symbol font mapping, we can * install the symbol font as the base font and access its glyphs. */ end = (row + 1) << FONTMAP_SHIFT; for (i = row << FONTMAP_SHIFT; i < end; i++) { if (Tcl_UtfToExternal(NULL, encoding, src, Tcl_UniCharToUtf(i, src), TCL_ENCODING_STOPONERROR, NULL, buf, sizeof(buf), NULL, NULL, NULL) != TCL_OK) { continue; } bitOffset = i & (FONTMAP_BITSPERPAGE - 1); subFontPtr->fontMap[row][bitOffset >> 3] |= 1 << (bitOffset & 7); } } } /* *--------------------------------------------------------------------------- * * CanUseFallbackWithAliases -- * * Helper function for FindSubFontForChar. Determine if the specified * face name (or an alias of the specified face name) can be used to * construct a screen font that can display the given character. * * Results: * See CanUseFallback(). * * Side effects: * If the name and/or one of its aliases was rejected, the rejected * string is recorded in nameTriedPtr so that it won't be tried again. * *--------------------------------------------------------------------------- */ static SubFont * CanUseFallbackWithAliases( HDC hdc, /* HDC in which font can be selected. */ WinFont *fontPtr, /* The font object that will own the new * screen font. */ char *faceName, /* Desired face name for new screen font. */ int ch, /* The Unicode character that the new screen * font must be able to display. */ Tcl_DString *nameTriedPtr, /* Records face names that have already been * tried. It is possible for the same face * name to be queried multiple times when * trying to find a suitable screen font. */ SubFont **subFontPtrPtr) /* Variable to fixup if we reallocate the * array of subfonts. */ { int i; char **aliases; SubFont *subFontPtr; if (SeenName(faceName, nameTriedPtr) == 0) { subFontPtr = CanUseFallback(hdc, fontPtr, faceName, ch, subFontPtrPtr); if (subFontPtr != NULL) { return subFontPtr; } } aliases = TkFontGetAliasList(faceName); if (aliases != NULL) { for (i = 0; aliases[i] != NULL; i++) { if (SeenName(aliases[i], nameTriedPtr) == 0) { subFontPtr = CanUseFallback(hdc, fontPtr, aliases[i], ch, subFontPtrPtr); if (subFontPtr != NULL) { return subFontPtr; } } } } return NULL; } /* *--------------------------------------------------------------------------- * * SeenName -- * * Used to determine we have already tried and rejected the given face * name when looking for a screen font that can support some Unicode * character. * * Results: * The return value is 0 if this face name has not already been seen, * non-zero otherwise. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static int SeenName( CONST char *name, /* The name to check. */ Tcl_DString *dsPtr) /* Contains names that have already been * seen. */ { CONST char *seen, *end; seen = Tcl_DStringValue(dsPtr); end = seen + Tcl_DStringLength(dsPtr); while (seen < end) { if (strcasecmp(seen, name) == 0) { return 1; } seen += strlen(seen) + 1; } Tcl_DStringAppend(dsPtr, (char *) name, (int) (strlen(name) + 1)); return 0; } /* *------------------------------------------------------------------------- * * CanUseFallback -- * * If the specified screen font has not already been loaded into the font * object, determine if it can display the given character. * * Results: * The return value is a pointer to a newly allocated SubFont, owned by * the font object. This SubFont can be used to display the given * character. The SubFont represents the screen font with the base set of * font attributes from the font object, but using the specified font * name. NULL is returned if the font object already holds a reference to * the specified physical font or if the specified physical font cannot * display the given character. * * Side effects: * The font object's subFontArray is updated to contain a reference to * the newly allocated SubFont. * *------------------------------------------------------------------------- */ static SubFont * CanUseFallback( HDC hdc, /* HDC in which font can be selected. */ WinFont *fontPtr, /* The font object that will own the new * screen font. */ char *faceName, /* Desired face name for new screen font. */ int ch, /* The Unicode character that the new screen * font must be able to display. */ SubFont **subFontPtrPtr) /* Variable to fix-up if we realloc the array * of subfonts. */ { int i; HFONT hFont; SubFont subFont; if (FamilyExists(hdc, faceName) == 0) { return NULL; } /* * Skip all fonts we've already used. */ for (i = 0; i < fontPtr->numSubFonts; i++) { if (faceName == fontPtr->subFontArray[i].familyPtr->faceName) { return NULL; } } /* * Load this font and see if it has the desired character. */ hFont = GetScreenFont(&fontPtr->font.fa, faceName, fontPtr->pixelSize); InitSubFont(hdc, hFont, 0, &subFont); if (((ch < 256) && (subFont.familyPtr->isSymbolFont)) || (FontMapLookup(&subFont, ch) == 0)) { /* * Don't use a symbol font as a fallback font for characters below * 256. */ ReleaseSubFont(&subFont); return NULL; } if (fontPtr->numSubFonts >= SUBFONT_SPACE) { SubFont *newPtr; newPtr = (SubFont *) ckalloc(sizeof(SubFont) * (fontPtr->numSubFonts + 1)); memcpy((char *) newPtr, fontPtr->subFontArray, fontPtr->numSubFonts * sizeof(SubFont)); if (fontPtr->subFontArray != fontPtr->staticSubFonts) { ckfree((char *) fontPtr->subFontArray); } /* * Fix up the variable pointed to by subFontPtrPtr so it still points * into the live array. [Bug 618872] */ *subFontPtrPtr = newPtr + (*subFontPtrPtr - fontPtr->subFontArray); fontPtr->subFontArray = newPtr; } fontPtr->subFontArray[fontPtr->numSubFonts] = subFont; fontPtr->numSubFonts++; return &fontPtr->subFontArray[fontPtr->numSubFonts - 1]; } /* *--------------------------------------------------------------------------- * * GetScreenFont -- * * Given the name and other attributes, construct an HFONT. This is where * all the alias and fallback substitution bottoms out. * * Results: * The screen font that corresponds to the attributes. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static HFONT GetScreenFont( CONST TkFontAttributes *faPtr, /* Desired font attributes for new HFONT. */ CONST char *faceName, /* Overrides font family specified in font * attributes. */ int pixelSize) /* Overrides size specified in font * attributes. */ { Tcl_DString ds; HFONT hFont; LOGFONTW lf; memset(&lf, 0, sizeof(lf)); lf.lfHeight = -pixelSize; lf.lfWidth = 0; lf.lfEscapement = 0; lf.lfOrientation = 0; lf.lfWeight = (faPtr->weight == TK_FW_NORMAL) ? FW_NORMAL : FW_BOLD; lf.lfItalic = faPtr->slant; lf.lfUnderline = faPtr->underline; lf.lfStrikeOut = faPtr->overstrike; lf.lfCharSet = DEFAULT_CHARSET; lf.lfOutPrecision = OUT_TT_PRECIS; lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; lf.lfQuality = DEFAULT_QUALITY; lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; Tcl_UtfToExternalDString(systemEncoding, faceName, -1, &ds); if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) { Tcl_UniChar *src, *dst; /* * We can only store up to LF_FACESIZE wide characters */ if ((size_t)Tcl_DStringLength(&ds) >= (LF_FACESIZE * sizeof(WCHAR))) { Tcl_DStringSetLength(&ds, LF_FACESIZE); } src = (Tcl_UniChar *) Tcl_DStringValue(&ds); dst = (Tcl_UniChar *) lf.lfFaceName; while (*src != '\0') { *dst++ = *src++; } *dst = '\0'; hFont = CreateFontIndirectW(&lf); } else { /* * We can only store up to LF_FACESIZE characters */ if (Tcl_DStringLength(&ds) >= LF_FACESIZE) { Tcl_DStringSetLength(&ds, LF_FACESIZE); } strcpy((char *) lf.lfFaceName, Tcl_DStringValue(&ds)); hFont = CreateFontIndirectA((LOGFONTA *) &lf); } Tcl_DStringFree(&ds); return hFont; } /* *------------------------------------------------------------------------- * * FamilyExists, FamilyOrAliasExists, WinFontExistsProc -- * * Determines if any physical screen font exists on the system with the * given family name. If the family exists, then it should be possible to * construct some physical screen font with that family name. * * Results: * The return value is 0 if the specified font family does not exist, * non-zero otherwise. * * Side effects: * None. * *------------------------------------------------------------------------- */ static int FamilyExists( HDC hdc, /* HDC in which font family will be used. */ CONST char *faceName) /* Font family to query. */ { int result; Tcl_DString faceString; /* * Just immediately rule out the following fonts, because they look so * ugly on windows. The caller's fallback mechanism will cause the * corresponding appropriate TrueType fonts to be selected. */ if (strcasecmp(faceName, "Courier") == 0) { return 0; } if (strcasecmp(faceName, "Times") == 0) { return 0; } if (strcasecmp(faceName, "Helvetica") == 0) { return 0; } Tcl_UtfToExternalDString(systemEncoding, faceName, -1, &faceString); /* * If the family exists, WinFontExistProc() will be called and * EnumFontFamilies() will return whatever WinFontExistProc() returns. If * the family doesn't exist, EnumFontFamilies() will just return a * non-zero value. */ if (TkWinGetPlatformId() == VER_PLATFORM_WIN32_NT) { result = EnumFontFamiliesW(hdc, (WCHAR*) Tcl_DStringValue(&faceString), (FONTENUMPROCW) WinFontExistProc, 0); } else { result = EnumFontFamiliesA(hdc, (char *) Tcl_DStringValue(&faceString), (FONTENUMPROCA) WinFontExistProc, 0); } Tcl_DStringFree(&faceString); return (result == 0); } static char * FamilyOrAliasExists( HDC hdc, CONST char *faceName) { char **aliases; int i; if (FamilyExists(hdc, faceName) != 0) { return (char *) faceName; } aliases = TkFontGetAliasList(faceName); if (aliases != NULL) { for (i = 0; aliases[i] != NULL; i++) { if (FamilyExists(hdc, aliases[i]) != 0) { return aliases[i]; } } } return NULL; } static int CALLBACK WinFontExistProc( ENUMLOGFONT *lfPtr, /* Logical-font data. */ NEWTEXTMETRIC *tmPtr, /* Physical-font data (not used). */ int fontType, /* Type of font (not used). */ LPARAM lParam) /* EnumFontData to hold result. */ { return 0; } /* * The following data structures are used when querying a TrueType font file * to determine which characters the font supports. */ #pragma pack(1) /* Structures are byte aligned in file. */ #define CMAPHEX 0x636d6170 /* Key for character map resource. */ typedef struct CMAPTABLE { USHORT version; /* Table version number (0). */ USHORT numTables; /* Number of encoding tables following. */ } CMAPTABLE; typedef struct ENCODINGTABLE { USHORT platform; /* Platform for which data is targeted. 3 * means data is for Windows. */ USHORT encoding; /* How characters in font are encoded. 1 means * that the following subtable is keyed based * on Unicode. */ ULONG offset; /* Byte offset from beginning of CMAPTABLE to * the subtable for this encoding. */ } ENCODINGTABLE; typedef struct ANYTABLE { USHORT format; /* Format number. */ USHORT length; /* The actual length in bytes of this * subtable. */ USHORT version; /* Version number (starts at 0). */ } ANYTABLE; typedef struct BYTETABLE { USHORT format; /* Format number is set to 0. */ USHORT length; /* The actual length in bytes of this * subtable. */ USHORT version; /* Version number (starts at 0). */ BYTE glyphIdArray[256]; /* Array that maps up to 256 single-byte char * codes to glyph indices. */ } BYTETABLE; typedef struct SUBHEADER { USHORT firstCode; /* First valid low byte for subHeader. */ USHORT entryCount; /* Number valid low bytes for subHeader. */ SHORT idDelta; /* Constant adder to get base glyph index. */ USHORT idRangeOffset; /* Byte offset from here to appropriate * glyphIndexArray. */ } SUBHEADER; typedef struct HIBYTETABLE { USHORT format; /* Format number is set to 2. */ USHORT length; /* The actual length in bytes of this * subtable. */ USHORT version; /* Version number (starts at 0). */ USHORT subHeaderKeys[256]; /* Maps high bytes to subHeaders: value is * subHeader index * 8. */ #if 0 SUBHEADER subHeaders[]; /* Variable-length array of SUBHEADERs. */ USHORT glyphIndexArray[]; /* Variable-length array containing subarrays * used for mapping the low byte of 2-byte * characters. */ #endif } HIBYTETABLE; typedef struct SEGMENTTABLE { USHORT format; /* Format number is set to 4. */ USHORT length; /* The actual length in bytes of this * subtable. */ USHORT version; /* Version number (starts at 0). */ USHORT segCountX2; /* 2 x segCount. */ USHORT searchRange; /* 2 x (2**floor(log2(segCount))). */ USHORT entrySelector; /* log2(searchRange/2). */ USHORT rangeShift; /* 2 x segCount - searchRange. */ #if 0 USHORT endCount[segCount] /* End characterCode for each segment. */ USHORT reservedPad; /* Set to 0. */ USHORT startCount[segCount];/* Start character code for each segment. */ USHORT idDelta[segCount]; /* Delta for all character in segment. */ USHORT idRangeOffset[segCount]; /* Offsets into glyphIdArray or 0. */ USHORT glyphIdArray[] /* Glyph index array. */ #endif } SEGMENTTABLE; typedef struct TRIMMEDTABLE { USHORT format; /* Format number is set to 6. */ USHORT length; /* The actual length in bytes of this * subtable. */ USHORT version; /* Version number (starts at 0). */ USHORT firstCode; /* First character code of subrange. */ USHORT entryCount; /* Number of character codes in subrange. */ #if 0 USHORT glyphIdArray[]; /* Array of glyph index values for * character codes in the range. */ #endif } TRIMMEDTABLE; typedef union SUBTABLE { ANYTABLE any; BYTETABLE byte; HIBYTETABLE hiByte; SEGMENTTABLE segment; TRIMMEDTABLE trimmed; } SUBTABLE; #pragma pack() /* *------------------------------------------------------------------------- * * LoadFontRanges -- * * Given an HFONT, get the information about the characters that this * font can display. * * Results: * If the font has no Unicode character information, the return value is * 0 and *startCountPtr and *endCountPtr are filled with NULL. Otherwise, * *startCountPtr and *endCountPtr are set to pointers to arrays of * TrueType character existence information and the return value is the * length of the arrays (the two arrays are always the same length as * each other). * * Side effects: * None. * *------------------------------------------------------------------------- */ static int LoadFontRanges( HDC hdc, /* HDC into which font can be selected. */ HFONT hFont, /* HFONT to query. */ USHORT **startCountPtr, /* Filled with malloced pointer to character * range information. */ USHORT **endCountPtr, /* Filled with malloced pointer to character * range information. */ int *symbolPtr) { int n, i, swapped, offset, cbData, segCount; DWORD cmapKey; USHORT *startCount, *endCount; CMAPTABLE cmapTable; ENCODINGTABLE encTable; SUBTABLE subTable; char *s; segCount = 0; startCount = NULL; endCount = NULL; *symbolPtr = 0; hFont = SelectObject(hdc, hFont); i = 0; s = (char *) &i; *s = '\1'; swapped = 0; if (i == 1) { swapped = 1; } cmapKey = CMAPHEX; if (swapped) { SwapLong(&cmapKey); } n = GetFontData(hdc, cmapKey, 0, &cmapTable, sizeof(cmapTable)); if (n != (int)GDI_ERROR) { if (swapped) { SwapShort(&cmapTable.numTables); } for (i = 0; i < cmapTable.numTables; i++) { offset = sizeof(cmapTable) + i * sizeof(encTable); GetFontData(hdc, cmapKey, (DWORD) offset, &encTable, sizeof(encTable)); if (swapped) { SwapShort(&encTable.platform); SwapShort(&encTable.encoding); SwapLong(&encTable.offset); } if (encTable.platform != 3) { /* * Not Microsoft encoding. */ continue; } if (encTable.encoding == 0) { *symbolPtr = 1; } else if (encTable.encoding != 1) { continue; } GetFontData(hdc, cmapKey, (DWORD) encTable.offset, &subTable, sizeof(subTable)); if (swapped) { SwapShort(&subTable.any.format); } if (subTable.any.format == 4) { if (swapped) { SwapShort(&subTable.segment.segCountX2); } segCount = subTable.segment.segCountX2 / 2; cbData = segCount * sizeof(USHORT); startCount = (USHORT *) ckalloc((unsigned)cbData); endCount = (USHORT *) ckalloc((unsigned)cbData); offset = encTable.offset + sizeof(subTable.segment); GetFontData(hdc, cmapKey, (DWORD) offset, endCount, cbData); offset += cbData + sizeof(USHORT); GetFontData(hdc, cmapKey, (DWORD) offset, startCount, cbData); if (swapped) { for (i = 0; i < segCount; i++) { SwapShort(&endCount[i]); SwapShort(&startCount[i]); } } if (*symbolPtr != 0) { /* * Empirically determined: When a symbol font is loaded, * the character existence metrics obtained from the * system are mildly wrong. If the real range of the * symbol font is from 0020 to 00FE, then the metrics are * reported as F020 to F0FE. When we load a symbol font, * we must fix the character existence metrics. * * Symbol fonts should only use the symbol encoding for * 8-bit characters [note Bug: 2406] */ for (i = 0; i < segCount; i++) { if (((startCount[i] & 0xff00) == 0xf000) && ((endCount[i] & 0xff00) == 0xf000)) { startCount[i] &= 0xff; endCount[i] &= 0xff; } } } } } } else if (GetTextCharset(hdc) == ANSI_CHARSET) { /* * Bitmap font. We should also support ranges for the other *_CHARSET * values. */ segCount = 1; cbData = segCount * sizeof(USHORT); startCount = (USHORT *) ckalloc((unsigned) cbData); endCount = (USHORT *) ckalloc((unsigned) cbData); startCount[0] = 0x0000; endCount[0] = 0x00ff; } SelectObject(hdc, hFont); *startCountPtr = startCount; *endCountPtr = endCount; return segCount; } /* *------------------------------------------------------------------------- * * SwapShort, SwapLong -- * * Helper functions to convert the data loaded from TrueType font files * to Intel byte ordering. * * Results: * Bytes of input value are swapped and stored back in argument. * * Side effects: * None. * *------------------------------------------------------------------------- */ static void SwapShort( PUSHORT p) { *p = (SHORT)(HIBYTE(*p) + (LOBYTE(*p) << 8)); } static void SwapLong( PULONG p) { ULONG temp; temp = (LONG) ((BYTE) *p); temp <<= 8; *p >>=8; temp += (LONG) ((BYTE) *p); temp <<= 8; *p >>=8; temp += (LONG) ((BYTE) *p); temp <<= 8; *p >>=8; temp += (LONG) ((BYTE) *p); *p = temp; } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */