Tk Source Code

Check-in [991b8f0e]
Login
Bounty program for improvements to Tcl and certain Tcl packages.
Tcl 2019 Conference, Houston/TX, US, Nov 4-8
Send your abstracts to tclconference@googlegroups.com
or submit via the online form by Sep 9.

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Source readability run: macosx/*
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256:991b8f0eda5afabaa2124b523f0fd1a6e88d175fc0bd77bed65fb85fdf8c0c9b
User & Date: dkf 2019-04-16 13:22:46
Context
2019-04-17
20:00
merge trunk Closed-Leaf check-in: fd66f9ef user: fvogel tags: bug-aa846938ef
15:10
Merge with (nearly) empty diff. check-in: 5bd3db74 user: culler tags: trunk
2019-04-16
13:22
Source readability run: macosx/* check-in: 991b8f0e user: dkf tags: trunk
12:59
Guard against interpreters being killed out from under our feet when calling Tcl. check-in: 3ca7d19e user: dkf tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to macosx/tkMacOSXButton.c.

1
2
3
4
5
6
7
8
9
10
11
12
..
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
....
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
....
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
....
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
....
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
....
1166
1167
1168
1169
1170
1171
1172

1173
1174
1175
1176

1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
/*
 * tkMacOSXButton.c --
 *
 *	This file implements the Macintosh specific portion of the
 *	button widgets.
 *
 * Copyright (c) 1996-1997 by Sun Microsystems, Inc.
 * Copyright 2001, Apple Computer, Inc.
 * Copyright (c) 2006-2007 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2007 Revar Desmera.
 * Copyright 2015 Kevin Walzer/WordTech Communications LLC.
 * Copyright 2015 Marc Culler.
................................................................................
    Tcl_TimerToken defaultPulseHandler;
} MacButton;

/*
 * Forward declarations for procedures defined later in this file:
 */


static void ButtonBackgroundDrawCB (const HIRect *btnbounds, MacButton *ptr,
        SInt16 depth, Boolean isColorDev);

static void ButtonContentDrawCB (const HIRect *bounds, ThemeButtonKind kind,
        const HIThemeButtonDrawInfo *info, MacButton *ptr, SInt16 depth,
	Boolean isColorDev);
static void ButtonEventProc(ClientData clientData, XEvent *eventPtr);

static void TkMacOSXComputeButtonParams (TkButton * butPtr, ThemeButtonKind* btnkind,

	HIThemeButtonDrawInfo* drawinfo);
static int TkMacOSXComputeButtonDrawParams (TkButton * butPtr, DrawParams * dpPtr);

static void TkMacOSXDrawButton (MacButton *butPtr, GC gc, Pixmap pixmap);

static void DrawButtonImageAndText(TkButton* butPtr);
static void PulseDefaultButtonProc(ClientData clientData);


/*
 * The class procedure table for the button widgets.
 */

const Tk_ClassProcs tkpButtonProcs = {
    sizeof(Tk_ClassProcs),	/* size */
    TkButtonWorldChanged,	/* worldChangedProc */
};

static int bCount;

/*
 *----------------------------------------------------------------------
 *
 * TkpButtonSetDefaults --
 *
 *	This procedure is invoked before option tables are created for
 *	buttons. It modifies some of the default values to match the current
 *	values defined for this platform.
 *
 * Results:
 *	Some of the default values in *specPtr are modified.
 *
 * Side effects:
 *	Updates some of.
 *
 *----------------------------------------------------------------------
 */

void
TkpButtonSetDefaults()
{
/*No-op.*/
}

 
/*
 *----------------------------------------------------------------------
 *
 * TkpCreateButton --
 *
 *	Allocate a new TkButton structure.
................................................................................
 *----------------------------------------------------------------------
 */

TkButton *
TkpCreateButton(
    Tk_Window tkwin)
{
    MacButton *macButtonPtr = (MacButton *) ckalloc(sizeof(MacButton));

    Tk_CreateEventHandler(tkwin, ActivateMask,
	    ButtonEventProc, (ClientData) macButtonPtr);
    macButtonPtr->id = bCount++;
    macButtonPtr->flags = FIRST_DRAW;
    macButtonPtr->btnkind = kThemePushButton;
    macButtonPtr->defaultPulseHandler = NULL;
    bzero(&macButtonPtr->drawinfo, sizeof(macButtonPtr->drawinfo));
    bzero(&macButtonPtr->lastdrawinfo, sizeof(macButtonPtr->lastdrawinfo));

    return (TkButton *)macButtonPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayButton --
 *
 *	This procedure is invoked to display a button widget. It is
 *	normally invoked as an idle handler.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the button in its
 *	current mode. The REDRAW_PENDING flag is cleared.
 *
 *----------------------------------------------------------------------
 */

void
TkpDisplayButton(
    ClientData clientData)	/* Information about widget. */
{
    MacButton *macButtonPtr = (MacButton *) clientData;
    TkButton *butPtr = (TkButton *) clientData;
    Tk_Window tkwin = butPtr->tkwin;
    Pixmap pixmap;
    DrawParams* dpPtr = &macButtonPtr->drawParams;
    int needhighlight = 0;

    butPtr->flags &= ~REDRAW_PENDING;
    if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
	return;
    }
    pixmap = (Pixmap) Tk_WindowId(tkwin);
    TkMacOSXSetUpClippingRgn(Tk_WindowId(tkwin));

    if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr) ) {
	macButtonPtr->useTkText = 0;
    } else {
	macButtonPtr->useTkText = 1;
    }


    /*
     * Set up clipping region. Make sure the we are using the port
     * for this button, or we will set the wrong window's clip.
     */

    if (macButtonPtr->useTkText) {
	if (butPtr->type == TYPE_BUTTON) {
	    Tk_Fill3DRectangle(tkwin, pixmap, butPtr->highlightBorder, 0, 0,
		    Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
	} else {
	    Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
		    Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
	}


        /* Display image or bitmap or text for labels or custom controls.  */


	DrawButtonImageAndText(butPtr);
        needhighlight  = 1;
    } else {

        /* Draw the native portion of the buttons. */


        TkMacOSXDrawButton(macButtonPtr, dpPtr->gc, pixmap);


        /* Draw highlight border, if needed. */


        if (butPtr->highlightWidth < 3) {
            needhighlight = 1;
        }
    }


    /* Draw highlight border, if needed. */
    if (needhighlight) {


        if ((butPtr->flags & GOT_FOCUS)) {
            Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
                Tk_Width(tkwin), Tk_Height(tkwin),
                butPtr->highlightWidth, TK_RELIEF_SOLID);
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpComputeButtonGeometry --
 *
 *	After changes in a button's text or bitmap, this procedure
 *	recomputes the button's geometry and passes this information
 *	along to the geometry manager for the window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The button's window may change size.
 *
................................................................................

void
TkpComputeButtonGeometry(
    TkButton *butPtr)		/* Button whose geometry may have changed. */
{
    int width = 0, height = 0, charWidth = 1, haveImage = 0, haveText = 0;
    int txtWidth = 0, txtHeight = 0;
    MacButton *mbPtr = (MacButton*)butPtr;
    Tk_FontMetrics fm;
    char *text = Tcl_GetString(butPtr->textPtr);

    TkMacOSXComputeButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);

    /*
     * If the indicator is on, get its size.
     */

    if (butPtr->indicatorOn) {
      switch (butPtr->type) {
      case TYPE_RADIO_BUTTON:
	GetThemeMetric(kThemeMetricRadioButtonWidth, (SInt32 *)&butPtr->indicatorDiameter);

	  break;
      case TYPE_CHECK_BUTTON:
	GetThemeMetric(kThemeMetricCheckBoxWidth, (SInt32 *)&butPtr->indicatorDiameter);

	  break;
      default:
	break;
      }


      /* Allow 2px extra space next to the indicator. */


      butPtr->indicatorSpace = butPtr->indicatorDiameter + 2;
    } else {
      butPtr->indicatorSpace = 0;
      butPtr->indicatorDiameter = 0;
    }

    if (butPtr->image != NULL) {
	Tk_SizeOfImage(butPtr->image, &width, &height);
	haveImage = 1;
    } else if (butPtr->bitmap != None) {
	Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
................................................................................
	txtWidth = butPtr->textWidth + 2*butPtr->padX;
	txtHeight = butPtr->textHeight + 2*butPtr->padY;
	haveText = 1;
    }

    if (haveImage && haveText) { /* Image and Text */
	switch ((enum compound) butPtr->compound) {
	    case COMPOUND_TOP:
	    case COMPOUND_BOTTOM:

		/*
		 * Image is above or below text.
		 */

		height += txtHeight + butPtr->padY;
		width = (width > txtWidth ? width : txtWidth);
		break;
	    case COMPOUND_LEFT:
	    case COMPOUND_RIGHT:

		/*
		 * Image is left or right of text.
		 */

		width += txtWidth + 2*butPtr->padX;
		height = (height > txtHeight ? height : txtHeight);
		break;
	    case COMPOUND_CENTER:

		/*
		 * Image and text are superimposed.
		 */

		width = (width > txtWidth ? width : txtWidth);
		height = (height > txtHeight ? height : txtHeight);
		break;
	    default:
		break;
	}
	width += butPtr->indicatorSpace;
    } else if (haveImage) { /* Image only */
	width = butPtr->width > 0 ? butPtr->width : width + butPtr->indicatorSpace;
	height = butPtr->height > 0 ? butPtr->height : height;
	if (butPtr->type == TYPE_BUTTON) {

	    /* Allow room to shift the image. */

	    width += 2;
	    height += 2;
	}
    } else { /* Text only */
        width = txtWidth + butPtr->indicatorSpace;
	height = txtHeight;
	if (butPtr->width > 0) {
................................................................................
    }

    butPtr->inset = butPtr->borderWidth + butPtr->highlightWidth;

    width += butPtr->inset*2;
    height += butPtr->inset*2;
    if ([NSApp macMinorVersion] == 6) {
      width += 12;
    }
    if (mbPtr->btnkind == kThemePushButton) {
        HIRect tmpRect;
    	HIRect contBounds;

	/*
	 * A PushButton has a minimum size.  We make sure that we
	 * are not underestimating the size by requesting the content
	 * size of a Pushbutton whose overall size is our content size
	 * expanded by the standard padding.
	 */
	
	tmpRect = CGRectMake(0, 0, width + 2*HI_PADX, height + 2*HI_PADY);
        HIThemeGetButtonContentBounds(&tmpRect, &mbPtr->drawinfo, &contBounds);
        if (height < contBounds.size.height) {
	    height = contBounds.size.height;
        }
................................................................................
        }
	height += 2*HI_PADY;
	width += 2*HI_PADX;
    }
    Tk_GeometryRequest(butPtr->tkwin, width, height);
    Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset);
}

/*
 *----------------------------------------------------------------------
 *
 * DrawButtonImageAndText --
 *
 *        Draws the image and text associated with a button or label.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        The image and text are drawn.
 *
 *----------------------------------------------------------------------
 */
static void
DrawButtonImageAndText(
    TkButton* butPtr)
{

    MacButton *mbPtr = (MacButton*)butPtr;
    Tk_Window  tkwin  = butPtr->tkwin;
    Pixmap     pixmap;
    int        haveImage = 0;
    int        haveText = 0;
    int        imageWidth = 0;
    int        imageHeight = 0;
    int        imageXOffset = 0;
    int        imageYOffset = 0;
    int        textXOffset = 0;
    int        textYOffset = 0;
    int        width = 0;
    int        height = 0;
    int        fullWidth = 0;
    int        fullHeight = 0;
    int        pressed = 0;


    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }

    DrawParams* dpPtr = &mbPtr->drawParams;
    pixmap = (Pixmap)Tk_WindowId(tkwin);

    if (butPtr->image != None) {
        Tk_SizeOfImage(butPtr->image, &width, &height);
        haveImage = 1;
    } else if (butPtr->bitmap != None) {
        Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
        haveImage = 1;
    }

    imageWidth  = width;
    imageHeight = height;

    if (mbPtr->drawinfo.state == kThemeStatePressed) {

        /* Offset bitmaps by a bit when the button is pressed. */


        pressed = 1;
    }

    haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0);
    if (haveImage && haveText) { /* Image and Text */
        int x;
        int y;
        textXOffset = 0;
        textYOffset = 0;
        fullWidth = 0;
        fullHeight = 0;

        switch ((enum compound) butPtr->compound) {
	case COMPOUND_TOP:
	case COMPOUND_BOTTOM: {
	  /* Image is above or below text */
	  if (butPtr->compound == COMPOUND_TOP) {
	    textYOffset = height + butPtr->padY;
	  } else {
	    imageYOffset = butPtr->textHeight + butPtr->padY;
	  }
	  fullHeight = height + butPtr->textHeight + butPtr->padY;
	  fullWidth = (width > butPtr->textWidth ? width :
		       butPtr->textWidth);
	  textXOffset = (fullWidth - butPtr->textWidth)/2;
	  imageXOffset = (fullWidth - width)/2;
	  break;
	}
	case COMPOUND_LEFT:
	case COMPOUND_RIGHT: {
	  /*
	   * Image is left or right of text
	   */

	  if (butPtr->compound == COMPOUND_LEFT) {
	    textXOffset = width + butPtr->padX;
	  } else {
	    imageXOffset = butPtr->textWidth + butPtr->padX;
	  }
	  fullWidth = butPtr->textWidth + butPtr->padX + width;
	  fullHeight = (height > butPtr->textHeight ? height :
                        butPtr->textHeight);
	  textYOffset = (fullHeight - butPtr->textHeight)/2;
	  imageYOffset = (fullHeight - height)/2;
	  break;
	}
	case COMPOUND_CENTER: {
	  /*
	   * Image and text are superimposed
	   */

	  fullWidth = (width > butPtr->textWidth ? width :
		       butPtr->textWidth);
	  fullHeight = (height > butPtr->textHeight ? height :
                        butPtr->textHeight);
	  textXOffset = (fullWidth - butPtr->textWidth)/2;
	  imageXOffset = (fullWidth - width)/2;
	  textYOffset = (fullHeight - butPtr->textHeight)/2;
	  imageYOffset = (fullHeight - height)/2;
	  break;
	}
	default:
	  break;
	}

        TkComputeAnchor(butPtr->anchor, tkwin,
                butPtr->padX + butPtr->borderWidth,
                butPtr->padY + butPtr->borderWidth,
                fullWidth + butPtr->indicatorSpace, fullHeight, &x, &y);
	x += butPtr->indicatorSpace;
................................................................................
            x += dpPtr->offset;
            y += dpPtr->offset;
        }
        imageXOffset += x;
        imageYOffset += y;

        if (butPtr->image != NULL) {
	  if ((butPtr->selectImage != NULL) &&
	      (butPtr->flags & SELECTED)) {
	    Tk_RedrawImage(butPtr->selectImage, 0, 0,
			   width, height, pixmap, imageXOffset, imageYOffset);
	  } else if ((butPtr->tristateImage != NULL) &&
		     (butPtr->flags & TRISTATED)) {
	    Tk_RedrawImage(butPtr->tristateImage, 0, 0,
			   width, height, pixmap, imageXOffset, imageYOffset);
	  } else {
	    Tk_RedrawImage(butPtr->image, 0, 0, width,
			   height, pixmap, imageXOffset, imageYOffset);
	  }
        } else {
	  XSetClipOrigin(butPtr->display, dpPtr->gc,
			 imageXOffset, imageYOffset);
	  XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc,
		     0, 0, (unsigned int) width, (unsigned int) height,
		     imageXOffset, imageYOffset, 1);
	  XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
        }

	y += 1; /* Tweak to match native buttons. */
        Tk_DrawTextLayout(butPtr->display, pixmap,
                dpPtr->gc, butPtr->textLayout,
                x + textXOffset, y + textYOffset, 0, -1);
        Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc,
                butPtr->textLayout,
                x + textXOffset, y + textYOffset,
                butPtr->underline);
    } else if (haveImage) { /* Image only */
        int x = 0;
	int y;

	TkComputeAnchor(butPtr->anchor, tkwin,
			butPtr->padX + butPtr->borderWidth,
			butPtr->padY + butPtr->borderWidth,
			width + butPtr->indicatorSpace,
			height, &x, &y);
        x += butPtr->indicatorSpace;
	if (pressed) {
	  x += dpPtr->offset;
	  y += dpPtr->offset;
	}
	imageXOffset += x;
	imageYOffset += y;

	if (butPtr->image != NULL) {

	  if ((butPtr->selectImage != NULL) &&
	      (butPtr->flags & SELECTED)) {
	    Tk_RedrawImage(butPtr->selectImage, 0, 0, width,
			   height, pixmap, imageXOffset, imageYOffset);
	  } else if ((butPtr->tristateImage != NULL) &&
		     (butPtr->flags & TRISTATED)) {
	    Tk_RedrawImage(butPtr->tristateImage, 0, 0, width,
			   height, pixmap, imageXOffset, imageYOffset);
	  } else {
	    Tk_RedrawImage(butPtr->image, 0, 0, width, height,
			   pixmap, imageXOffset, imageYOffset);
	  }
	} else {
	  XSetClipOrigin(butPtr->display, dpPtr->gc, x, y);
	  XCopyPlane(butPtr->display, butPtr->bitmap,
		     pixmap, dpPtr->gc,
		     0, 0, (unsigned int) width,
		     (unsigned int) height,
		     imageXOffset, imageYOffset, 1);
	  XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
	}
    } else { /* Text only */
        int x, y;

	TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY,
			butPtr->textWidth + butPtr->indicatorSpace,
			  butPtr->textHeight, &x, &y);
	x += butPtr->indicatorSpace;
	y += 1; /* Tweak to match native buttons */
	Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc, butPtr->textLayout,
			  x, y, 0, -1);
    }

    /*
     * If the button is disabled with a stipple rather than a special
     * foreground color, generate the stippled effect.  If the widget
     * is selected and we use a different background color when selected,
     * must temporarily modify the GC so the stippling is the right color.
     */

    if (mbPtr->useTkText) {
        if ((butPtr->state == STATE_DISABLED)
                && ((butPtr->disabledFg == NULL) || (butPtr->image != NULL))) {
            if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn
                    && (butPtr->selectBorder != NULL)) {
................................................................................

        /*
         * Draw the border and traversal highlight last.  This way, if the
         * button's contents overflow they'll be covered up by the border.
         */

        if (dpPtr->relief != TK_RELIEF_FLAT) {
            int inset = butPtr->highlightWidth;

            Tk_Draw3DRectangle(tkwin, pixmap, dpPtr->border, inset, inset,
                Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset,
                butPtr->borderWidth, dpPtr->relief);
        }
    }

   }




/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyButton --
 *
 *	Free data structures associated with the button control.
 *
................................................................................
 */

void
TkpDestroyButton(
    TkButton *butPtr)
{
    MacButton *mbPtr = (MacButton *) butPtr; /* Mac button. */

    if (mbPtr->defaultPulseHandler) {
        Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler);
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * TkMacOSXDrawButton --
 *
 *        This function draws the tk button using Mac controls
 *        In addition, this code may apply custom colors passed
 *        in the TkButton.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *      The control is created, or reinitialised as needed
 *
................................................................................
TkMacOSXDrawButton(
    MacButton *mbPtr,    /* Mac button. */
    GC gc,               /* The GC we are drawing into - needed for
                          * the bevel button */
    Pixmap pixmap)       /* The pixmap we are drawing into - needed
                          * for the bevel button */
{
    TkButton * butPtr = ( TkButton *)mbPtr;
    TkWindow * winPtr;
    HIRect      cntrRect;
    TkMacOSXDrawingContext dc;
    DrawParams* dpPtr = &mbPtr->drawParams;
    int useNewerHITools = 1;

    winPtr = (TkWindow *)butPtr->tkwin;

    TkMacOSXComputeButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);

    cntrRect = CGRectMake(winPtr->privatePtr->xOff,
			  winPtr->privatePtr->yOff,
			  Tk_Width(butPtr->tkwin),
			  Tk_Height(butPtr->tkwin));

     cntrRect = CGRectInset(cntrRect,  butPtr->inset, butPtr->inset);

    if (useNewerHITools == 1) {
        HIRect contHIRec;
        static HIThemeButtonDrawInfo hiinfo;

        ButtonBackgroundDrawCB(&cntrRect, mbPtr, 32, true);

	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}

        hiinfo.version = 0;
        hiinfo.state = mbPtr->drawinfo.state;
        hiinfo.kind  = mbPtr->btnkind;
        hiinfo.value = mbPtr->drawinfo.value;
        hiinfo.adornment = mbPtr->drawinfo.adornment;
        hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent();
        if (hiinfo.animation.time.start == 0) {
            hiinfo.animation.time.start = hiinfo.animation.time.current;
        }

	/*
	 * To avoid buttons with white text on a white background, we always
	 * set the state to inactive in Dark Mode.  It isn't perfect but
	 * it is usable.  Using a ttk::button would be a better choice,
	 * however.
	 */

	if (TkMacOSXInDarkMode(butPtr->tkwin)) {
	    hiinfo.state = kThemeStateInactive;
	}
	HIThemeDrawButton(&cntrRect, &hiinfo, dc.context, kHIThemeOrientationNormal,
			  &contHIRec);

	TkMacOSXRestoreDrawingContext(&dc);
        ButtonContentDrawCB(&contHIRec, mbPtr->btnkind, &mbPtr->drawinfo,
			    (MacButton *)mbPtr, 32, true);

    } else {
	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}

	TkMacOSXRestoreDrawingContext(&dc);
    }
................................................................................
}
 
/*
 *--------------------------------------------------------------
 *
 * ButtonBackgroundDrawCB --
 *
 *        This function draws the background that
 *        lies under checkboxes and radiobuttons.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        The background gets updated to the current color.
 *
 *--------------------------------------------------------------
 */

static void
ButtonBackgroundDrawCB (
    const HIRect * btnbounds,
    MacButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    MacButton* mbPtr = (MacButton*)ptr;
    TkButton* butPtr = (TkButton*)mbPtr;
    Tk_Window  tkwin  = butPtr->tkwin;
    Pixmap pixmap;
    int usehlborder = 0;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }
    pixmap = (Pixmap)Tk_WindowId(tkwin);

    if (butPtr->type != TYPE_LABEL) {
        switch (mbPtr->btnkind) {
            case kThemeSmallBevelButton:
            case kThemeBevelButton:
            case kThemeRoundedBevelButton:
            case kThemePushButton:
                usehlborder = 1;
                break;
        }
    }
    if (usehlborder) {
        Tk_Fill3DRectangle(tkwin, pixmap, butPtr->highlightBorder, 0, 0,
            Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
    } else {
        Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
................................................................................
    const HIRect * btnbounds,
    ThemeButtonKind kind,
    const HIThemeButtonDrawInfo *drawinfo,
    MacButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    TkButton  *butPtr = (TkButton *)ptr;
    Tk_Window  tkwin  = butPtr->tkwin;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }

    /*
     * Overlay Tk elements over button native region: drawing elements
     * within button boundaries/native region causes unpredictable metrics.
     */

    DrawButtonImageAndText( butPtr);
}
 
/*
 *--------------------------------------------------------------
 *
 * ButtonEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various
 *	events on buttons.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When it gets exposed, it is redisplayed.
 *
................................................................................
 */

static void
ButtonEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkButton *buttonPtr = (TkButton *) clientData;
    MacButton *mbPtr = (MacButton *) clientData;

    if (eventPtr->type == ActivateNotify
	    || eventPtr->type == DeactivateNotify) {
	if ((buttonPtr->tkwin == NULL) || (!Tk_IsMapped(buttonPtr->tkwin))) {
	    return;
	}
	if (eventPtr->type == ActivateNotify) {
	    mbPtr->flags |= ACTIVE;
	} else {
	    mbPtr->flags &= ~ACTIVE;
	}
	if ((buttonPtr->flags & REDRAW_PENDING) == 0) {
	    Tcl_DoWhenIdle(TkpDisplayButton, (ClientData) buttonPtr);
	    buttonPtr->flags |= REDRAW_PENDING;
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeButtonParams --
 *
 *      This procedure computes the various parameters used
 *        when creating a Carbon Appearance control.
 *	These are determined by the various tk button parameters
 *
 * Results:
 *	None.
 *
 * Side effects:
 *        Sets the btnkind and drawinfo parameters
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXComputeButtonParams(
        TkButton * butPtr,
        ThemeButtonKind* btnkind,
	HIThemeButtonDrawInfo *drawinfo)
{
    MacButton *mbPtr = (MacButton *)butPtr;

    if (butPtr->borderWidth <= 2) {
        *btnkind = kThemeSmallBevelButton;
    } else if (butPtr->borderWidth == 3) {
        *btnkind = kThemeBevelButton;
    } else if (butPtr->borderWidth == 4) {
        *btnkind = kThemeRoundedBevelButton;
    } else {
        *btnkind = kThemePushButton;
    }

    if ((butPtr->image == None) && (butPtr->bitmap == None)) {
        switch (butPtr->type) {
            case TYPE_BUTTON:
                *btnkind = kThemePushButton;
                break;
            case TYPE_RADIO_BUTTON:
                if (butPtr->borderWidth <= 1) {
                    *btnkind = kThemeSmallRadioButton;
		} else {
                    *btnkind = kThemeRadioButton;
		}
		break;
	    case TYPE_CHECK_BUTTON:
                if (butPtr->borderWidth <= 1) {
                    *btnkind = kThemeSmallCheckBox;
	        } else {
                    *btnkind = kThemeCheckBox;
		}
		break;
	}
    }

    if (butPtr->indicatorOn) {
        switch (butPtr->type) {
            case TYPE_RADIO_BUTTON:
                if (butPtr->borderWidth <= 1) {
                    *btnkind = kThemeSmallRadioButton;
                } else {
                    *btnkind = kThemeRadioButton;
                }
                break;
            case TYPE_CHECK_BUTTON:
                if (butPtr->borderWidth <= 1) {
                    *btnkind = kThemeSmallCheckBox;
                } else {
                    *btnkind = kThemeCheckBox;
                }
                break;
        }
    } else {
        if (butPtr->type == TYPE_RADIO_BUTTON ||
	    butPtr->type == TYPE_CHECK_BUTTON
	) {
	    if (*btnkind == kThemePushButton) {
		*btnkind = kThemeBevelButton;
	    }
        }
    }

    if (butPtr->flags & SELECTED) {
................................................................................
    }

    drawinfo->adornment = kThemeAdornmentNone;
    if (butPtr->defaultState == DEFAULT_ACTIVE) {
        drawinfo->adornment |= kThemeAdornmentDefault;
        if (!mbPtr->defaultPulseHandler) {
            mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler(
                    PULSE_TIMER_MSECS, PulseDefaultButtonProc,
                    (ClientData) butPtr);
        }
    } else if (mbPtr->defaultPulseHandler) {
        Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler);
    }
    if (butPtr->highlightWidth >= 3) {
        if ((butPtr->flags & GOT_FOCUS)) {
            drawinfo->adornment |= kThemeAdornmentFocus;
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeButtonDrawParams --
 *
 *	This procedure computes the various parameters used
 *	when drawing a button
 *	These are determined by the various tk button parameters
 *
 * Results:
 *	1 if control will be used, 0 otherwise.
 *
 * Side effects:
 *	Sets the button draw parameters
 *
................................................................................
 */

static int
TkMacOSXComputeButtonDrawParams(
    TkButton *butPtr,
    DrawParams *dpPtr)
{
    MacButton *mbPtr = (MacButton *)butPtr;

    dpPtr->hasImageOrBitmap = ((butPtr->image != NULL)
	    || (butPtr->bitmap != None));

    if (butPtr->type != TYPE_LABEL) {
        dpPtr->offset = 0;
        if (dpPtr->hasImageOrBitmap) {
            switch (mbPtr->btnkind) {
                case kThemeSmallBevelButton:
                case kThemeBevelButton:
                case kThemeRoundedBevelButton:
                case kThemePushButton:
                    dpPtr->offset = 1;
                    break;
            }
        }
    }

    dpPtr->border = butPtr->normalBorder;
    if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) {
	dpPtr->gc = butPtr->disabledGC;
................................................................................

    if ((butPtr->flags & SELECTED) && (butPtr->state != STATE_ACTIVE)
	    && (butPtr->selectBorder != NULL) && !butPtr->indicatorOn) {
	dpPtr->border = butPtr->selectBorder;
    }

    /*
     * Override the relief specified for the button if this is a
     * checkbutton or radiobutton and there's no indicator.
     */

    dpPtr->relief = butPtr->relief;

    if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) {
	if (!dpPtr->hasImageOrBitmap) {
	    dpPtr->relief = (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN
		    : TK_RELIEF_RAISED;
	}
    }

    if (butPtr->type != TYPE_LABEL &&
	(butPtr->type == TYPE_BUTTON ||
	 butPtr->indicatorOn         ||
	 dpPtr->hasImageOrBitmap)) {
	
	/*
	 * Draw this widget as a native control.
	 */
	
	return 1;
    } else {

	/*
	 * Draw this widget from scratch.
	 */
	
	return 0;
    }
}
................................................................................
 *     None.
 *
 * Side effects:
 *     Sets a timer to run itself again.
 *
 *--------------------------------------------------------------
 */

static void
PulseDefaultButtonProc(ClientData clientData)
{
    MacButton *mbPtr = (MacButton *)clientData;

    TkpDisplayButton(clientData);
    mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler(
            PULSE_TIMER_MSECS, PulseDefaultButtonProc, clientData);
}

/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */



|
|







 







<
|
|
>
|
|
|
|
>
|
>
|
|
>
|
>
|
|
<











|





|
|
|













|

<







 







|


|







|







|
|





|
|








|
|












|





<

|
|











>
|
>
>

|

>
|
>
>


>
|
>
>





>
|
<
>
>
|
|


<








|
|
|







 







|










|
|
|
>
|
|
|
>
|
|
|
|
>
>
|
>
>
|

|
|







 







|
|
<
|
|
|

|
|
|
|
|
<
|
|
|

|
|
|
|
<
|
|
|

|
|
|
|
|






>
|
>







 







|






|
|
|
|







 







|





|


|


|





|


|
|
|
|
<
|
<
|
<
|
<
|
<
|
<
<
<





|
|









|



>
|
>
>





|
<
<
<
<
<



|
|
|
|
|
|
|
|
|
<
|
|
|
<

|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|

|
|
|
|
|
|
|
|
|
<

|







 







|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|











|
<
>

|
|
|
<


|
|





<
|
|
|
|
|
|
|
|
|
|
|
|

|
|
<
|
<
|
|



>

|
|


|
|




|
|
|







 







|
>
|
|
|


|
|
<
<
<
<







 







>










|
|
<







 







|
|
|

|


<
<


|
<
<
|

|













|









|
|
<





|
|



|
<







 







|
|









>

|
|




|
|
|






|



|
|
|
|
|
|







 







|
|






|
|

>








|
|







 







|
|












|










|
|
|












|
|
|

|













|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|





|
|
|
|
|
|
|
|
|
|
|
|
|
|



|
<







 







|
<







 







|
<
|







 







|








|
|
|
|
|
|







 







|
|











|
<
<
|
<



|


<







 







>



|
>




|








1
2
3
4
5
6
7
8
9
10
11
12
..
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
...
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
...
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
...
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
...
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
...
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
...
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
...
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678




679
680
681
682
683
684
685
...
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
...
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
...
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
...
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
...
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
....
1037
1038
1039
1040
1041
1042
1043
1044

1045
1046
1047
1048
1049
1050
1051
....
1054
1055
1056
1057
1058
1059
1060
1061

1062
1063
1064
1065
1066
1067
1068
1069
....
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
....
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
....
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
/*
 * tkMacOSXButton.c --
 *
 *	This file implements the Macintosh specific portion of the button
 *	widgets.
 *
 * Copyright (c) 1996-1997 by Sun Microsystems, Inc.
 * Copyright 2001, Apple Computer, Inc.
 * Copyright (c) 2006-2007 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2007 Revar Desmera.
 * Copyright 2015 Kevin Walzer/WordTech Communications LLC.
 * Copyright 2015 Marc Culler.
................................................................................
    Tcl_TimerToken defaultPulseHandler;
} MacButton;

/*
 * Forward declarations for procedures defined later in this file:
 */


static void		ButtonBackgroundDrawCB(const HIRect *btnbounds,
			    MacButton *ptr, SInt16 depth, Boolean isColorDev);
static void		ButtonContentDrawCB(const HIRect *bounds,
			    ThemeButtonKind kind,
			    const HIThemeButtonDrawInfo *info, MacButton *ptr,
			    SInt16 depth, Boolean isColorDev);
static void		ButtonEventProc(ClientData clientData,
			    XEvent *eventPtr);
static void		TkMacOSXComputeButtonParams(TkButton *butPtr,
			    ThemeButtonKind *btnkind,
			    HIThemeButtonDrawInfo *drawinfo);
static int		TkMacOSXComputeButtonDrawParams(TkButton *butPtr,
			    DrawParams * dpPtr);
static void		TkMacOSXDrawButton(MacButton *butPtr, GC gc,
			    Pixmap pixmap);
static void		DrawButtonImageAndText(TkButton *butPtr);
static void		PulseDefaultButtonProc(ClientData clientData);


/*
 * The class procedure table for the button widgets.
 */

const Tk_ClassProcs tkpButtonProcs = {
    sizeof(Tk_ClassProcs),	/* size */
    TkButtonWorldChanged,	/* worldChangedProc */
};

static int bCount;
 
/*
 *----------------------------------------------------------------------
 *
 * TkpButtonSetDefaults --
 *
 *	This procedure is invoked before option tables are created for buttons.
 *	It modifies some of the default values to match the current values
 *	defined for this platform.
 *
 * Results:
 *	Some of the default values in *specPtr are modified.
 *
 * Side effects:
 *	Updates some of.
 *
 *----------------------------------------------------------------------
 */

void
TkpButtonSetDefaults()
{
    /*No-op.*/
}

 
/*
 *----------------------------------------------------------------------
 *
 * TkpCreateButton --
 *
 *	Allocate a new TkButton structure.
................................................................................
 *----------------------------------------------------------------------
 */

TkButton *
TkpCreateButton(
    Tk_Window tkwin)
{
    MacButton *macButtonPtr = ckalloc(sizeof(MacButton));

    Tk_CreateEventHandler(tkwin, ActivateMask,
	    ButtonEventProc, macButtonPtr);
    macButtonPtr->id = bCount++;
    macButtonPtr->flags = FIRST_DRAW;
    macButtonPtr->btnkind = kThemePushButton;
    macButtonPtr->defaultPulseHandler = NULL;
    bzero(&macButtonPtr->drawinfo, sizeof(macButtonPtr->drawinfo));
    bzero(&macButtonPtr->lastdrawinfo, sizeof(macButtonPtr->lastdrawinfo));

    return (TkButton *) macButtonPtr;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayButton --
 *
 *	This procedure is invoked to display a button widget. It is normally
 *	invoked as an idle handler.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the button in its current mode. The
 *	REDRAW_PENDING flag is cleared.
 *
 *----------------------------------------------------------------------
 */

void
TkpDisplayButton(
    ClientData clientData)	/* Information about widget. */
{
    MacButton *macButtonPtr = clientData;
    TkButton *butPtr = clientData;
    Tk_Window tkwin = butPtr->tkwin;
    Pixmap pixmap;
    DrawParams* dpPtr = &macButtonPtr->drawParams;
    int needhighlight = 0;

    butPtr->flags &= ~REDRAW_PENDING;
    if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
	return;
    }
    pixmap = (Pixmap) Tk_WindowId(tkwin);
    TkMacOSXSetUpClippingRgn(Tk_WindowId(tkwin));

    if (TkMacOSXComputeButtonDrawParams(butPtr, dpPtr)) {
	macButtonPtr->useTkText = 0;
    } else {
	macButtonPtr->useTkText = 1;
    }


    /*
     * Set up clipping region. Make sure the we are using the port for this
     * button, or we will set the wrong window's clip.
     */

    if (macButtonPtr->useTkText) {
	if (butPtr->type == TYPE_BUTTON) {
	    Tk_Fill3DRectangle(tkwin, pixmap, butPtr->highlightBorder, 0, 0,
		    Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
	} else {
	    Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
		    Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
	}

        /*
	 * Display image or bitmap or text for labels or custom controls.
	 */

	DrawButtonImageAndText(butPtr);
        needhighlight = 1;
    } else {
        /*
	 * Draw the native portion of the buttons.
	 */

        TkMacOSXDrawButton(macButtonPtr, dpPtr->gc, pixmap);

        /*
	 * Ask for the highlight border, if needed.
	 */

        if (butPtr->highlightWidth < 3) {
            needhighlight = 1;
        }
    }

    /*
     * Draw highlight border.

     */

    if (needhighlight && (butPtr->flags & GOT_FOCUS)) {
	Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
                Tk_Width(tkwin), Tk_Height(tkwin),
                butPtr->highlightWidth, TK_RELIEF_SOLID);

    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpComputeButtonGeometry --
 *
 *	After changes in a button's text or bitmap, this procedure recomputes
 *	the button's geometry and passes this information along to the geometry
 *	manager for the window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The button's window may change size.
 *
................................................................................

void
TkpComputeButtonGeometry(
    TkButton *butPtr)		/* Button whose geometry may have changed. */
{
    int width = 0, height = 0, charWidth = 1, haveImage = 0, haveText = 0;
    int txtWidth = 0, txtHeight = 0;
    MacButton *mbPtr = (MacButton *) butPtr;
    Tk_FontMetrics fm;
    char *text = Tcl_GetString(butPtr->textPtr);

    TkMacOSXComputeButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);

    /*
     * If the indicator is on, get its size.
     */

    if (butPtr->indicatorOn) {
	switch (butPtr->type) {
	case TYPE_RADIO_BUTTON:
	    GetThemeMetric(kThemeMetricRadioButtonWidth,
		    (SInt32 *) &butPtr->indicatorDiameter);
	    break;
	case TYPE_CHECK_BUTTON:
	    GetThemeMetric(kThemeMetricCheckBoxWidth,
		    (SInt32 *) &butPtr->indicatorDiameter);
	    break;
	default:
	    break;
	}

	/*
	 * Allow 2px extra space next to the indicator.
	 */

	butPtr->indicatorSpace = butPtr->indicatorDiameter + 2;
    } else {
	butPtr->indicatorSpace = 0;
	butPtr->indicatorDiameter = 0;
    }

    if (butPtr->image != NULL) {
	Tk_SizeOfImage(butPtr->image, &width, &height);
	haveImage = 1;
    } else if (butPtr->bitmap != None) {
	Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
................................................................................
	txtWidth = butPtr->textWidth + 2*butPtr->padX;
	txtHeight = butPtr->textHeight + 2*butPtr->padY;
	haveText = 1;
    }

    if (haveImage && haveText) { /* Image and Text */
	switch ((enum compound) butPtr->compound) {
	case COMPOUND_TOP:
	case COMPOUND_BOTTOM:

	    /*
	     * Image is above or below text.
	     */

	    height += txtHeight + butPtr->padY;
	    width = (width > txtWidth ? width : txtWidth);
	    break;
	case COMPOUND_LEFT:
	case COMPOUND_RIGHT:

	    /*
	     * Image is left or right of text.
	     */

	    width += txtWidth + 2*butPtr->padX;
	    height = (height > txtHeight ? height : txtHeight);
	    break;
	case COMPOUND_CENTER:

	    /*
	     * Image and text are superimposed.
	     */

	    width = (width > txtWidth ? width : txtWidth);
	    height = (height > txtHeight ? height : txtHeight);
	    break;
	default:
	    break;
	}
	width += butPtr->indicatorSpace;
    } else if (haveImage) { /* Image only */
	width = butPtr->width > 0 ? butPtr->width : width + butPtr->indicatorSpace;
	height = butPtr->height > 0 ? butPtr->height : height;
	if (butPtr->type == TYPE_BUTTON) {
	    /*
	     * Allow room to shift the image.
	     */
	    width += 2;
	    height += 2;
	}
    } else { /* Text only */
        width = txtWidth + butPtr->indicatorSpace;
	height = txtHeight;
	if (butPtr->width > 0) {
................................................................................
    }

    butPtr->inset = butPtr->borderWidth + butPtr->highlightWidth;

    width += butPtr->inset*2;
    height += butPtr->inset*2;
    if ([NSApp macMinorVersion] == 6) {
	width += 12;
    }
    if (mbPtr->btnkind == kThemePushButton) {
        HIRect tmpRect;
    	HIRect contBounds;

	/*
	 * A PushButton has a minimum size.  We make sure that we are not
	 * underestimating the size by requesting the content size of a
	 * Pushbutton whose overall size is our content size expanded by the
	 * standard padding.
	 */
	
	tmpRect = CGRectMake(0, 0, width + 2*HI_PADX, height + 2*HI_PADY);
        HIThemeGetButtonContentBounds(&tmpRect, &mbPtr->drawinfo, &contBounds);
        if (height < contBounds.size.height) {
	    height = contBounds.size.height;
        }
................................................................................
        }
	height += 2*HI_PADY;
	width += 2*HI_PADX;
    }
    Tk_GeometryRequest(butPtr->tkwin, width, height);
    Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset);
}
 
/*
 *----------------------------------------------------------------------
 *
 * DrawButtonImageAndText --
 *
 *	Draws the image and text associated with a button or label.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The image and text are drawn.
 *
 *----------------------------------------------------------------------
 */
static void
DrawButtonImageAndText(
    TkButton *butPtr)
{

    MacButton *mbPtr = (MacButton *) butPtr;
    Tk_Window tkwin = butPtr->tkwin;
    Pixmap pixmap;
    int haveImage = 0, haveText = 0, pressed = 0;

    int imageWidth = 0, imageHeight = 0;

    int imageXOffset = 0, imageYOffset = 0;

    int textXOffset = 0, textYOffset = 0;

    int width = 0, height = 0;

    int fullWidth = 0, fullHeight = 0;




    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }

    DrawParams *dpPtr = &mbPtr->drawParams;
    pixmap = (Pixmap) Tk_WindowId(tkwin);

    if (butPtr->image != None) {
        Tk_SizeOfImage(butPtr->image, &width, &height);
        haveImage = 1;
    } else if (butPtr->bitmap != None) {
        Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
        haveImage = 1;
    }

    imageWidth = width;
    imageHeight = height;

    if (mbPtr->drawinfo.state == kThemeStatePressed) {
        /*
	 * Offset bitmaps by a bit when the button is pressed.
	 */

        pressed = 1;
    }

    haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0);
    if (haveImage && haveText) { /* Image and Text */
        int x, y;






        switch ((enum compound) butPtr->compound) {
	case COMPOUND_TOP:
	case COMPOUND_BOTTOM:
	    /* Image is above or below text */
	    if (butPtr->compound == COMPOUND_TOP) {
		textYOffset = height + butPtr->padY;
	    } else {
		imageYOffset = butPtr->textHeight + butPtr->padY;
	    }
	    fullHeight = height + butPtr->textHeight + butPtr->padY;
	    fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth);

	    textXOffset = (fullWidth - butPtr->textWidth)/2;
	    imageXOffset = (fullWidth - width)/2;
	    break;

	case COMPOUND_LEFT:
	case COMPOUND_RIGHT:
	    /*
	     * Image is left or right of text
	     */

	    if (butPtr->compound == COMPOUND_LEFT) {
		textXOffset = width + butPtr->padX;
	    } else {
		imageXOffset = butPtr->textWidth + butPtr->padX;
	    }
	    fullWidth = butPtr->textWidth + butPtr->padX + width;
	    fullHeight = (height > butPtr->textHeight ? height :
		    butPtr->textHeight);
	    textYOffset = (fullHeight - butPtr->textHeight)/2;
	    imageYOffset = (fullHeight - height)/2;
	    break;

	case COMPOUND_CENTER:
	    /*
	     * Image and text are superimposed
	     */

	    fullWidth = (width > butPtr->textWidth ? width :
		    butPtr->textWidth);
	    fullHeight = (height > butPtr->textHeight ? height :
		    butPtr->textHeight);
	    textXOffset = (fullWidth - butPtr->textWidth)/2;
	    imageXOffset = (fullWidth - width)/2;
	    textYOffset = (fullHeight - butPtr->textHeight)/2;
	    imageYOffset = (fullHeight - height)/2;
	    break;

	default:
	    break;
	}

        TkComputeAnchor(butPtr->anchor, tkwin,
                butPtr->padX + butPtr->borderWidth,
                butPtr->padY + butPtr->borderWidth,
                fullWidth + butPtr->indicatorSpace, fullHeight, &x, &y);
	x += butPtr->indicatorSpace;
................................................................................
            x += dpPtr->offset;
            y += dpPtr->offset;
        }
        imageXOffset += x;
        imageYOffset += y;

        if (butPtr->image != NULL) {
	    if ((butPtr->selectImage != NULL) &&
		    (butPtr->flags & SELECTED)) {
		Tk_RedrawImage(butPtr->selectImage, 0, 0,
			width, height, pixmap, imageXOffset, imageYOffset);
	    } else if ((butPtr->tristateImage != NULL) &&
		    (butPtr->flags & TRISTATED)) {
		Tk_RedrawImage(butPtr->tristateImage, 0, 0,
			width, height, pixmap, imageXOffset, imageYOffset);
	    } else {
		Tk_RedrawImage(butPtr->image, 0, 0, width,
			height, pixmap, imageXOffset, imageYOffset);
	    }
        } else {
	    XSetClipOrigin(butPtr->display, dpPtr->gc,
		    imageXOffset, imageYOffset);
	    XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc,
		    0, 0, (unsigned int) width, (unsigned int) height,
		    imageXOffset, imageYOffset, 1);
	    XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
        }

	y += 1; /* Tweak to match native buttons. */
        Tk_DrawTextLayout(butPtr->display, pixmap,
                dpPtr->gc, butPtr->textLayout,
                x + textXOffset, y + textYOffset, 0, -1);
        Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc,
                butPtr->textLayout,
                x + textXOffset, y + textYOffset,
                butPtr->underline);
    } else if (haveImage) { /* Image only */
        int x = 0, y;


	TkComputeAnchor(butPtr->anchor, tkwin,
		butPtr->padX + butPtr->borderWidth,
		butPtr->padY + butPtr->borderWidth,
		width + butPtr->indicatorSpace, height, &x, &y);

        x += butPtr->indicatorSpace;
	if (pressed) {
	    x += dpPtr->offset;
	    y += dpPtr->offset;
	}
	imageXOffset += x;
	imageYOffset += y;

	if (butPtr->image != NULL) {

	    if ((butPtr->selectImage != NULL) &&
		    (butPtr->flags & SELECTED)) {
		Tk_RedrawImage(butPtr->selectImage, 0, 0, width,
			height, pixmap, imageXOffset, imageYOffset);
	    } else if ((butPtr->tristateImage != NULL) &&
		    (butPtr->flags & TRISTATED)) {
		Tk_RedrawImage(butPtr->tristateImage, 0, 0, width,
			height, pixmap, imageXOffset, imageYOffset);
	    } else {
		Tk_RedrawImage(butPtr->image, 0, 0, width, height,
			pixmap, imageXOffset, imageYOffset);
	    }
	} else {
	    XSetClipOrigin(butPtr->display, dpPtr->gc, x, y);
	    XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc,

		    0, 0, (unsigned int) width, (unsigned int) height,

		    imageXOffset, imageYOffset, 1);
	    XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
	}
    } else { /* Text only */
        int x, y;

	TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY,
		butPtr->textWidth + butPtr->indicatorSpace,
		butPtr->textHeight, &x, &y);
	x += butPtr->indicatorSpace;
	y += 1; /* Tweak to match native buttons */
	Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc,
		butPtr->textLayout, x, y, 0, -1);
    }

    /*
     * If the button is disabled with a stipple rather than a special
     * foreground color, generate the stippled effect.  If the widget is
     * selected and we use a different background color when selected, must
     * temporarily modify the GC so the stippling is the right color.
     */

    if (mbPtr->useTkText) {
        if ((butPtr->state == STATE_DISABLED)
                && ((butPtr->disabledFg == NULL) || (butPtr->image != NULL))) {
            if ((butPtr->flags & SELECTED) && !butPtr->indicatorOn
                    && (butPtr->selectBorder != NULL)) {
................................................................................

        /*
         * Draw the border and traversal highlight last.  This way, if the
         * button's contents overflow they'll be covered up by the border.
         */

        if (dpPtr->relief != TK_RELIEF_FLAT) {
	    int inset = butPtr->highlightWidth;

	    Tk_Draw3DRectangle(tkwin, pixmap, dpPtr->border, inset, inset,
		    Tk_Width(tkwin) - 2*inset, Tk_Height(tkwin) - 2*inset,
		    butPtr->borderWidth, dpPtr->relief);
        }
    }
}
 




/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyButton --
 *
 *	Free data structures associated with the button control.
 *
................................................................................
 */

void
TkpDestroyButton(
    TkButton *butPtr)
{
    MacButton *mbPtr = (MacButton *) butPtr; /* Mac button. */

    if (mbPtr->defaultPulseHandler) {
        Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler);
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * TkMacOSXDrawButton --
 *
 *        This function draws the tk button using Mac controls. In addition,
 *        this code may apply custom colors passed in the TkButton.

 *
 * Results:
 *        None.
 *
 * Side effects:
 *      The control is created, or reinitialised as needed
 *
................................................................................
TkMacOSXDrawButton(
    MacButton *mbPtr,    /* Mac button. */
    GC gc,               /* The GC we are drawing into - needed for
                          * the bevel button */
    Pixmap pixmap)       /* The pixmap we are drawing into - needed
                          * for the bevel button */
{
    TkButton *butPtr = (TkButton *) mbPtr;
    TkWindow *winPtr = (TkWindow *) butPtr->tkwin;
    HIRect cntrRect;
    TkMacOSXDrawingContext dc;
    DrawParams *dpPtr = &mbPtr->drawParams;
    int useNewerHITools = 1;



    TkMacOSXComputeButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);

    cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff,


	    Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin));

    cntrRect = CGRectInset(cntrRect, butPtr->inset, butPtr->inset);

    if (useNewerHITools == 1) {
        HIRect contHIRec;
        static HIThemeButtonDrawInfo hiinfo;

        ButtonBackgroundDrawCB(&cntrRect, mbPtr, 32, true);

	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}

        hiinfo.version = 0;
        hiinfo.state = mbPtr->drawinfo.state;
        hiinfo.kind = mbPtr->btnkind;
        hiinfo.value = mbPtr->drawinfo.value;
        hiinfo.adornment = mbPtr->drawinfo.adornment;
        hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent();
        if (hiinfo.animation.time.start == 0) {
            hiinfo.animation.time.start = hiinfo.animation.time.current;
        }

	/*
	 * To avoid buttons with white text on a white background, we always
	 * set the state to inactive in Dark Mode.  It isn't perfect but it is
	 * usable.  Using a ttk::button would be a better choice, however.

	 */

	if (TkMacOSXInDarkMode(butPtr->tkwin)) {
	    hiinfo.state = kThemeStateInactive;
	}
	HIThemeDrawButton(&cntrRect, &hiinfo, dc.context,
		kHIThemeOrientationNormal, &contHIRec);

	TkMacOSXRestoreDrawingContext(&dc);
        ButtonContentDrawCB(&contHIRec, mbPtr->btnkind, &mbPtr->drawinfo,
		(MacButton *) mbPtr, 32, true);

    } else {
	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}

	TkMacOSXRestoreDrawingContext(&dc);
    }
................................................................................
}
 
/*
 *--------------------------------------------------------------
 *
 * ButtonBackgroundDrawCB --
 *
 *        This function draws the background that lies under checkboxes and
 *        radiobuttons.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        The background gets updated to the current color.
 *
 *--------------------------------------------------------------
 */

static void
ButtonBackgroundDrawCB(
    const HIRect *btnbounds,
    MacButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    MacButton *mbPtr = (MacButton *) ptr;
    TkButton *butPtr = (TkButton *) mbPtr;
    Tk_Window tkwin = butPtr->tkwin;
    Pixmap pixmap;
    int usehlborder = 0;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }
    pixmap = (Pixmap) Tk_WindowId(tkwin);

    if (butPtr->type != TYPE_LABEL) {
        switch (mbPtr->btnkind) {
	case kThemeSmallBevelButton:
	case kThemeBevelButton:
	case kThemeRoundedBevelButton:
	case kThemePushButton:
	    usehlborder = 1;
	    break;
        }
    }
    if (usehlborder) {
        Tk_Fill3DRectangle(tkwin, pixmap, butPtr->highlightBorder, 0, 0,
            Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
    } else {
        Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
................................................................................
    const HIRect * btnbounds,
    ThemeButtonKind kind,
    const HIThemeButtonDrawInfo *drawinfo,
    MacButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    TkButton *butPtr = (TkButton *) ptr;
    Tk_Window tkwin = butPtr->tkwin;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }

    /*
     * Overlay Tk elements over button native region: drawing elements within
     * button boundaries/native region causes unpredictable metrics.
     */

    DrawButtonImageAndText( butPtr);
}
 
/*
 *--------------------------------------------------------------
 *
 * ButtonEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various events on
 *	buttons.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When it gets exposed, it is redisplayed.
 *
................................................................................
 */

static void
ButtonEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkButton *buttonPtr = clientData;
    MacButton *mbPtr = clientData;

    if (eventPtr->type == ActivateNotify
	    || eventPtr->type == DeactivateNotify) {
	if ((buttonPtr->tkwin == NULL) || (!Tk_IsMapped(buttonPtr->tkwin))) {
	    return;
	}
	if (eventPtr->type == ActivateNotify) {
	    mbPtr->flags |= ACTIVE;
	} else {
	    mbPtr->flags &= ~ACTIVE;
	}
	if ((buttonPtr->flags & REDRAW_PENDING) == 0) {
	    Tcl_DoWhenIdle(TkpDisplayButton, buttonPtr);
	    buttonPtr->flags |= REDRAW_PENDING;
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeButtonParams --
 *
 *      This procedure computes the various parameters used when creating a
 *      Carbon Appearance control.  These are determined by the various tk
 *      button parameters
 *
 * Results:
 *	None.
 *
 * Side effects:
 *        Sets the btnkind and drawinfo parameters
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXComputeButtonParams(
    TkButton *butPtr,
    ThemeButtonKind *btnkind,
    HIThemeButtonDrawInfo *drawinfo)
{
    MacButton *mbPtr = (MacButton *) butPtr;

    if (butPtr->borderWidth <= 2) {
        *btnkind = kThemeSmallBevelButton;
    } else if (butPtr->borderWidth == 3) {
        *btnkind = kThemeBevelButton;
    } else if (butPtr->borderWidth == 4) {
        *btnkind = kThemeRoundedBevelButton;
    } else {
        *btnkind = kThemePushButton;
    }

    if ((butPtr->image == None) && (butPtr->bitmap == None)) {
        switch (butPtr->type) {
	case TYPE_BUTTON:
	    *btnkind = kThemePushButton;
	    break;
	case TYPE_RADIO_BUTTON:
	    if (butPtr->borderWidth <= 1) {
		*btnkind = kThemeSmallRadioButton;
	    } else {
		*btnkind = kThemeRadioButton;
	    }
	    break;
	case TYPE_CHECK_BUTTON:
	    if (butPtr->borderWidth <= 1) {
		*btnkind = kThemeSmallCheckBox;
	    } else {
		*btnkind = kThemeCheckBox;
	    }
	    break;
	}
    }

    if (butPtr->indicatorOn) {
        switch (butPtr->type) {
	case TYPE_RADIO_BUTTON:
	    if (butPtr->borderWidth <= 1) {
		*btnkind = kThemeSmallRadioButton;
	    } else {
		*btnkind = kThemeRadioButton;
	    }
	    break;
	case TYPE_CHECK_BUTTON:
	    if (butPtr->borderWidth <= 1) {
		*btnkind = kThemeSmallCheckBox;
	    } else {
		*btnkind = kThemeCheckBox;
	    }
	    break;
        }
    } else {
        if (butPtr->type == TYPE_RADIO_BUTTON ||
		butPtr->type == TYPE_CHECK_BUTTON) {

	    if (*btnkind == kThemePushButton) {
		*btnkind = kThemeBevelButton;
	    }
        }
    }

    if (butPtr->flags & SELECTED) {
................................................................................
    }

    drawinfo->adornment = kThemeAdornmentNone;
    if (butPtr->defaultState == DEFAULT_ACTIVE) {
        drawinfo->adornment |= kThemeAdornmentDefault;
        if (!mbPtr->defaultPulseHandler) {
            mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler(
                    PULSE_TIMER_MSECS, PulseDefaultButtonProc, butPtr);

        }
    } else if (mbPtr->defaultPulseHandler) {
        Tcl_DeleteTimerHandler(mbPtr->defaultPulseHandler);
    }
    if (butPtr->highlightWidth >= 3) {
        if ((butPtr->flags & GOT_FOCUS)) {
            drawinfo->adornment |= kThemeAdornmentFocus;
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeButtonDrawParams --
 *
 *	This procedure computes the various parameters used when drawing a

 *	button. These are determined by the various tk button parameters
 *
 * Results:
 *	1 if control will be used, 0 otherwise.
 *
 * Side effects:
 *	Sets the button draw parameters
 *
................................................................................
 */

static int
TkMacOSXComputeButtonDrawParams(
    TkButton *butPtr,
    DrawParams *dpPtr)
{
    MacButton *mbPtr = (MacButton *) butPtr;

    dpPtr->hasImageOrBitmap = ((butPtr->image != NULL)
	    || (butPtr->bitmap != None));

    if (butPtr->type != TYPE_LABEL) {
        dpPtr->offset = 0;
        if (dpPtr->hasImageOrBitmap) {
            switch (mbPtr->btnkind) {
	    case kThemeSmallBevelButton:
	    case kThemeBevelButton:
	    case kThemeRoundedBevelButton:
	    case kThemePushButton:
		dpPtr->offset = 1;
		break;
            }
        }
    }

    dpPtr->border = butPtr->normalBorder;
    if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) {
	dpPtr->gc = butPtr->disabledGC;
................................................................................

    if ((butPtr->flags & SELECTED) && (butPtr->state != STATE_ACTIVE)
	    && (butPtr->selectBorder != NULL) && !butPtr->indicatorOn) {
	dpPtr->border = butPtr->selectBorder;
    }

    /*
     * Override the relief specified for the button if this is a checkbutton or
     * radiobutton and there's no indicator.
     */

    dpPtr->relief = butPtr->relief;

    if ((butPtr->type >= TYPE_CHECK_BUTTON) && !butPtr->indicatorOn) {
	if (!dpPtr->hasImageOrBitmap) {
	    dpPtr->relief = (butPtr->flags & SELECTED) ? TK_RELIEF_SUNKEN
		    : TK_RELIEF_RAISED;
	}
    }

    if (butPtr->type != TYPE_LABEL && (butPtr->type == TYPE_BUTTON ||


	    butPtr->indicatorOn || dpPtr->hasImageOrBitmap)) {

	/*
	 * Draw this widget as a native control.
	 */

	return 1;
    } else {

	/*
	 * Draw this widget from scratch.
	 */
	
	return 0;
    }
}
................................................................................
 *     None.
 *
 * Side effects:
 *     Sets a timer to run itself again.
 *
 *--------------------------------------------------------------
 */

static void
PulseDefaultButtonProc(ClientData clientData)
{
    MacButton *mbPtr = clientData;

    TkpDisplayButton(clientData);
    mbPtr->defaultPulseHandler = Tcl_CreateTimerHandler(
            PULSE_TIMER_MSECS, PulseDefaultButtonProc, clientData);
}
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */

Changes to macosx/tkMacOSXClipboard.c.

119
120
121
122
123
124
125


126
127
128
129
130
131
132
133
134
...
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
				 * returned. */
    Tk_GetSelProc *proc,	/* Procedure to call to process the selection,
				 * once it has been retrieved. */
    ClientData clientData)	/* Arbitrary value to pass to proc. */
{
    int result = TCL_ERROR;
    TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr;



    int haveExternalClip = ([[NSPasteboard generalPasteboard] changeCount] != changeCount);
    if (dispPtr && (haveExternalClip || dispPtr->clipboardActive)
	        && selection == dispPtr->clipboardAtom
	        && (target == XA_STRING || target == dispPtr->utf8Atom)) {
	NSString *string = nil;
	NSPasteboard *pb = [NSPasteboard generalPasteboard];
	NSString *type = [pb availableTypeFromArray:[NSArray arrayWithObject:
		NSStringPboardType]];
................................................................................
{
    TkDisplay *dispPtr = TkGetDisplayList();

    if (dispPtr && selection == dispPtr->clipboardAtom) {
	clipboardOwner = owner ? Tk_IdToWindow(display, owner) : NULL;
	if (!dispPtr->clipboardActive) {
	    NSPasteboard *pb = [NSPasteboard generalPasteboard];

	    changeCount = [pb declareTypes:[NSArray array] owner:NSApp];
	}
    }
    return Success;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSelDeadWindow --
 *
 *	This function is invoked just before a TkWindow is deleted. It
 *	performs selection-related cleanup.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	clipboardOwner is cleared.
 *







>
>

<







 







>











|
|







119
120
121
122
123
124
125
126
127
128

129
130
131
132
133
134
135
...
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
				 * returned. */
    Tk_GetSelProc *proc,	/* Procedure to call to process the selection,
				 * once it has been retrieved. */
    ClientData clientData)	/* Arbitrary value to pass to proc. */
{
    int result = TCL_ERROR;
    TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr;
    int haveExternalClip =
	    ([[NSPasteboard generalPasteboard] changeCount] != changeCount);


    if (dispPtr && (haveExternalClip || dispPtr->clipboardActive)
	        && selection == dispPtr->clipboardAtom
	        && (target == XA_STRING || target == dispPtr->utf8Atom)) {
	NSString *string = nil;
	NSPasteboard *pb = [NSPasteboard generalPasteboard];
	NSString *type = [pb availableTypeFromArray:[NSArray arrayWithObject:
		NSStringPboardType]];
................................................................................
{
    TkDisplay *dispPtr = TkGetDisplayList();

    if (dispPtr && selection == dispPtr->clipboardAtom) {
	clipboardOwner = owner ? Tk_IdToWindow(display, owner) : NULL;
	if (!dispPtr->clipboardActive) {
	    NSPasteboard *pb = [NSPasteboard generalPasteboard];

	    changeCount = [pb declareTypes:[NSArray array] owner:NSApp];
	}
    }
    return Success;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSelDeadWindow --
 *
 *	This function is invoked just before a TkWindow is deleted. It performs
 *	selection-related cleanup.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	clipboardOwner is cleared.
 *

Changes to macosx/tkMacOSXCursor.c.

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
...
274
275
276
277
278
279
280

281
282
283
284
285
286
287
...
295
296
297
298
299
300
301

302


303


304

305
306
307
308
309

310
311
312
313
314
315
316
    {NULL}
};

/*
 * Declarations of static variables used in this file.
 */

static TkMacOSXCursor * gCurrentCursor = NULL;
				/* A pointer to the current cursor. */
static int gResizeOverride = false;
				/* A boolean indicating whether we should use
				 * the resize cursor during installations. */
static int gTkOwnsCursor = true;/* A boolean indicating whether Tk owns the
				 * cursor. If not (for instance, in the case
				 * where a Tk window is embedded in another
				 * app's window, and the cursor is out of the
				 * tk window, we will not attempt to adjust
				 * the cursor. */

/*
 * Declarations of procedures local to this file
 */

static void FindCursorByName(TkMacOSXCursor *macCursorPtr, const char *string);
................................................................................
		NSBitmapImageRep *bitmapImageRep = NULL;
		CGImageRef img = NULL, mask = NULL, maskedImg = NULL;
		static const CGFloat decodeWB[] = {1, 0};
		CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(
			kCGColorSpaceGenericGray);
		CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
			bitmap, pix*pix/8, NULL);

		if (provider) {
		    img = CGImageCreate(pix, pix, 1, 1, pix/8, colorspace,
			    kCGBitmapByteOrderDefault, provider, decodeWB, 0,
			    kCGRenderingIntentDefault);
		    CFRelease(provider);
		}
		provider = CGDataProviderCreateWithData(NULL, bitmap +
................................................................................
		    maskedImg = CGImageCreateWithMask(img, mask);
		}
		if (maskedImg) {
		    bitmapImageRep = [[NSBitmapImageRep alloc]
			    initWithCGImage:maskedImg];
		    CFRelease(maskedImg);
		}

		if (mask) { CFRelease(mask); }


		if (img)  { CFRelease(img); }


		if (colorspace) { CFRelease(colorspace); }

		if (bitmapImageRep) {
		    image = [[NSImage alloc] initWithSize:NSMakeSize(pix, pix)];
		    [image addRepresentation:bitmapImageRep];
		    [bitmapImageRep release];
		}

		uint16_t *hotSpotData = (uint16_t*)(bitmap + 2*pix*pix/8);
		hotSpot.y = CFSwapInt16BigToHost(*hotSpotData++);
		hotSpot.x = CFSwapInt16BigToHost(*hotSpotData);
		haveHotSpot = 1;
		break;
	    }
	    }







|








|







 







>







 







>
|
>
>
|
>
>
|
>





>







181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
...
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
    {NULL}
};

/*
 * Declarations of static variables used in this file.
 */

static TkMacOSXCursor *gCurrentCursor = NULL;
				/* A pointer to the current cursor. */
static int gResizeOverride = false;
				/* A boolean indicating whether we should use
				 * the resize cursor during installations. */
static int gTkOwnsCursor = true;/* A boolean indicating whether Tk owns the
				 * cursor. If not (for instance, in the case
				 * where a Tk window is embedded in another
				 * app's window, and the cursor is out of the
				 * Tk window, we will not attempt to adjust
				 * the cursor. */

/*
 * Declarations of procedures local to this file
 */

static void FindCursorByName(TkMacOSXCursor *macCursorPtr, const char *string);
................................................................................
		NSBitmapImageRep *bitmapImageRep = NULL;
		CGImageRef img = NULL, mask = NULL, maskedImg = NULL;
		static const CGFloat decodeWB[] = {1, 0};
		CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(
			kCGColorSpaceGenericGray);
		CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
			bitmap, pix*pix/8, NULL);

		if (provider) {
		    img = CGImageCreate(pix, pix, 1, 1, pix/8, colorspace,
			    kCGBitmapByteOrderDefault, provider, decodeWB, 0,
			    kCGRenderingIntentDefault);
		    CFRelease(provider);
		}
		provider = CGDataProviderCreateWithData(NULL, bitmap +
................................................................................
		    maskedImg = CGImageCreateWithMask(img, mask);
		}
		if (maskedImg) {
		    bitmapImageRep = [[NSBitmapImageRep alloc]
			    initWithCGImage:maskedImg];
		    CFRelease(maskedImg);
		}
		if (mask) {
		    CFRelease(mask);
		}
		if (img) {
		    CFRelease(img);
		}
		if (colorspace) {
		    CFRelease(colorspace);
		}
		if (bitmapImageRep) {
		    image = [[NSImage alloc] initWithSize:NSMakeSize(pix, pix)];
		    [image addRepresentation:bitmapImageRep];
		    [bitmapImageRep release];
		}

		uint16_t *hotSpotData = (uint16_t*)(bitmap + 2*pix*pix/8);
		hotSpot.y = CFSwapInt16BigToHost(*hotSpotData++);
		hotSpot.x = CFSwapInt16BigToHost(*hotSpotData);
		haveHotSpot = 1;
		break;
	    }
	    }

Changes to macosx/tkMacOSXDialog.c.

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
...
162
163
164
165
166
167
168
169
170
171



172


173
174
175
176
177
178
179
...
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
...
268
269
270
271
272
273
274


275
276
277



278
279

280
281
282
283
284
285
286
287
...
289
290
291
292
293
294
295

296
297
298
299
300
301
302
303
...
380
381
382
383
384
385
386

387
388
389
390
391
392
393
...
411
412
413
414
415
416
417

418
419






420

421
422
423
424
425
426
427

428
429
430
431
432
433
434
...
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
...
627
628
629
630
631
632
633

634
635
636
637

638
639

640
641
642
643
644
645
646
647
...
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
...
689
690
691
692
693
694
695

696


697
698
699
700
701
702
703
...
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
...
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
...
902
903
904
905
906
907
908

909
910
911
912


913
914

915
916
917
918
919
920
921
922
...
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
...
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
....
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
....
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
....
1374
1375
1376
1377
1378
1379
1380
1381

1382
1383
1384
1385
1386
1387
1388
....
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
....
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434

1435
1436
1437
1438
1439
1440
1441
....
1467
1468
1469
1470
1471
1472
1473
1474



1475
1476
1477
1478
1479
1480
1481
....
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
....
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
....
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
....
1818
1819
1820
1821
1822
1823
1824
1825

1826
1827
1828
1829
1830
1831
1832
....
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
....
1874
1875
1876
1877
1878
1879
1880

1881
1882

1883
1884
1885
1886
1887
1888
1889
....
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
....
1913
1914
1915
1916
1917
1918
1919

1920
1921
1922
1923
1924
1925
1926
....
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008

#if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
#define modalOK     NSOKButton
#define modalCancel NSCancelButton
#else
#define modalOK     NSModalResponseOK
#define modalCancel NSModalResponseCancel
#endif
#define modalOther  -1
#define modalError  -2


/*Vars for filtering in "open file" and "save file" dialogs.*/


typedef struct {

    bool doFileTypes; // show the accessory view which displays the filter menu
    bool preselectFilter; // a filter was selected by the typevariable

    bool userHasSelectedFilter; // The user has changed the filter in the accessory view


    NSMutableArray *fileTypeNames; // array of names, e.g. "Text document"

    NSMutableArray *fileTypeExtensions; // array of allowed extensions per name, e.g. "txt", "doc"

    NSMutableArray *fileTypeLabels; // displayed string, e.g. "Text document (.txt, .doc)"

    NSMutableArray *fileTypeAllowsAll; // boolean if the all pattern (*.*) is included


    NSMutableArray *allowedExtensions; // set of all allowed extensions
    bool allowedExtensionsAllowAll; // set of all allowed extensions includes *.*


    NSUInteger fileTypeIndex; // index of currently selected filter

} filepanelFilterInfo;

filepanelFilterInfo filterInfo;

NSOpenPanel *openpanel;
NSSavePanel *savepanel;

static const char *const colorOptionStrings[] = {
    "-initialcolor", "-parent", "-title", NULL
};
enum colorOptions {
    COLOR_INITIAL, COLOR_PARENT, COLOR_TITLE
};
................................................................................
    [TYPE_OKCANCEL] =		{3, 4, 0},
    [TYPE_RETRYCANCEL] =	{1, 4, 0},
    [TYPE_YESNO] =		{6, 5, 0},
    [TYPE_YESNOCANCEL] =	{6, 5, 4},
};

/*
 * Construct a file URL from directory and filename.  Either may
 * be nil.  If both are nil, returns nil.
 */



static NSURL *getFileURL(NSString *directory, NSString *filename) {


    NSURL *url = nil;
    if (directory) {
	url = [NSURL fileURLWithPath:directory isDirectory:YES];
    }
    if (filename) {
	url = [NSURL URLWithString:filename relativeToURL:url];
    }
................................................................................
    }
    if (callbackInfo->cmdObj) {
	Tcl_DecrRefCount(callbackInfo->cmdObj);
	ckfree(callbackInfo);
    }
}


- (void) tkAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode
	contextInfo: (void *) contextInfo
{
    AlertCallbackInfo *callbackInfo = contextInfo;

    if (returnCode >= NSAlertFirstButtonReturn) {
	Tcl_Obj *resultObj = Tcl_NewStringObj(alertButtonStrings[
................................................................................

- (void)selectFormat:(id)sender  {
    NSPopUpButton *button      = (NSPopUpButton *)sender;
    filterInfo.fileTypeIndex   = [button indexOfSelectedItem];

    if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterInfo.fileTypeIndex] boolValue]) {
	[openpanel setAllowsOtherFileTypes:YES];


	/* setAllowsOtherFileTypes might have no effect; it's inherited from the
	 * NSSavePanel, where it has the effect that it does not append an extension
	 * Setting the allowed file types to nil allows selecting any file */



	[openpanel setAllowedFileTypes:nil];
    } else {

	NSMutableArray *allowedtypes = [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex];
	[openpanel setAllowedFileTypes:allowedtypes];
	[openpanel setAllowsOtherFileTypes:NO];
    }

    filterInfo.userHasSelectedFilter = true;
}

................................................................................
    NSPopUpButton *button     = (NSPopUpButton *)sender;
    filterInfo.fileTypeIndex  = [button indexOfSelectedItem];

    if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterInfo.fileTypeIndex] boolValue]) {
	[savepanel setAllowsOtherFileTypes:YES];
	[savepanel setAllowedFileTypes:nil];
    } else {

	NSMutableArray *allowedtypes = [filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex];
	[savepanel setAllowedFileTypes:allowedtypes];
	[savepanel setAllowsOtherFileTypes:NO];
    }

    filterInfo.userHasSelectedFilter = true;
}

................................................................................
    [colorPanel orderOut:NSApp];
    [colorPanel setContinuous:NO];
    [colorPanel setBecomesKeyOnlyIfNeeded:NO];
    [colorPanel setShowsAlpha: NO];
    [colorPanel _setUseModalAppearance:YES];
    if (title) {
	NSString *s = [[NSString alloc] initWithUTF8String:title];

	[colorPanel setTitle:s];
	[s release];
    }
    if (initialColor) {
	[colorPanel setColor:initialColor];
    }
    returnCode = [NSApp runModalForWindow:colorPanel];
................................................................................
    }
    result = TCL_OK;

end:
    return result;
}


/* dissect the -filetype nested lists and store the information
 * in the filterInfo structure */






int parseFileFilters(Tcl_Interp *interp, Tcl_Obj *fileTypesPtr, Tcl_Obj *typeVariablePtr) {


    if (!fileTypesPtr) {
	filterInfo.doFileTypes = false;
	return TCL_OK;
    }

    FileFilterList fl;

    TkInitFileFilters(&fl);
    if (TkGetFileFilters(interp, &fl, fileTypesPtr, 0) != TCL_OK) {
	TkFreeFileFilters(&fl);
	return TCL_ERROR;
    }

    filterInfo.doFileTypes = (fl.filters != NULL);
................................................................................

    filterInfo.allowedExtensions = [NSMutableArray array];
    filterInfo.allowedExtensionsAllowAll = NO;

    if (filterInfo.doFileTypes) {
	for (FileFilter *filterPtr = fl.filters; filterPtr;
		filterPtr = filterPtr->next) {
	    NSString * name = [[NSString alloc] initWithUTF8String: filterPtr -> name];

	    [filterInfo.fileTypeNames addObject:name];
	    [name release];
	    NSMutableArray * clauseextensions = [NSMutableArray array];
	    NSMutableArray * displayextensions = [NSMutableArray array];
	    bool allowsAll = NO;

	    for (FileFilterClause *clausePtr = filterPtr->clauses; clausePtr;
		    clausePtr = clausePtr->next) {

		for (GlobPattern *globPtr = clausePtr->patterns; globPtr;
			globPtr = globPtr->next) {
		    const char *str = globPtr->pattern;
		    while (*str && (*str == '*' || *str == '.')) {
		    	str++;
		     }
		    if (*str) {
			NSString *extension = [[NSString alloc] initWithUTF8String:str];
			if (![filterInfo.allowedExtensions containsObject:extension]) {
			    [filterInfo.allowedExtensions addObject:extension];
			}

			[clauseextensions addObject:extension];
			[displayextensions addObject:[@"." stringByAppendingString:extension]];

			[extension release];
		    } else {

			// it is the all pattern (*, .* or *.*)


			allowsAll = YES;
			filterInfo.allowedExtensionsAllowAll = YES;
			[displayextensions addObject:@"*"];
		    }
		}
	    }
	    [filterInfo.fileTypeExtensions addObject:clauseextensions];
	    [filterInfo.fileTypeAllowsAll addObject:[NSNumber numberWithBool:allowsAll]];

	    NSMutableString * label = [[NSMutableString alloc] initWithString:name];
	    [label appendString:@" ("];
	    [label appendString:[displayextensions componentsJoinedByString:@", "]];
	    [label appendString:@")"];
	    [filterInfo.fileTypeLabels addObject:label];
	    [label release];

	}




	/* Check if the typevariable exists and matches one of the names */
	filterInfo.preselectFilter = false;
	filterInfo.userHasSelectedFilter = false;
	if (typeVariablePtr) {

	    /* extract the variable content as a NSString */


	    Tcl_Obj *selectedFileTypeObj = Tcl_ObjGetVar2(interp, typeVariablePtr, NULL, TCL_GLOBAL_ONLY);



	    /* check that the typevariable exists */


	    if (selectedFileTypeObj != NULL) {

		const char *selectedFileType = Tcl_GetString(selectedFileTypeObj);

		NSString *selectedFileTypeStr = [[NSString alloc] initWithUTF8String:selectedFileType];

		NSUInteger index = [filterInfo.fileTypeNames indexOfObject:selectedFileTypeStr];

		if (index != NSNotFound) {
		    filterInfo.fileTypeIndex = index;
		    filterInfo.preselectFilter = true;
		}
	    }
	}
................................................................................

    }

    TkFreeFileFilters(&fl);
    return TCL_OK;
}



bool filterCompatible(NSString *extension, int filterIndex) {



    NSMutableArray *allowedExtensions = [filterInfo.fileTypeExtensions objectAtIndex: filterIndex];


    /* If this contains the all pattern, accept any extension */


    if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterIndex] boolValue]) {
	return true;
    }

    return [allowedExtensions containsObject: extension];
}

 
/*
 *----------------------------------------------------------------------
 *
 * Tk_GetOpenFileObjCmd --
 *
 *	This procedure implements the "open file" dialog box for the Mac
................................................................................
	    break;
	}
    }

    if (title) {
	[openpanel setTitle:title];


	/* From OSX 10.11, the title string is silently ignored in the open panel.
	 * Prepend the title to the message in this case
	 * NOTE should be conditional on OSX version, but
	 * -mmacosx-version-min does not revert this behaviour*/


	if (message) {

	    NSString *fullmessage = [[NSString alloc] initWithFormat:@"%@\n%@",title,message];
	    [message release];
	    [title release];
	    message = fullmessage;
	} else {
	    message = title;
	}
    }
................................................................................
    [openpanel setAllowsMultipleSelection:multiple];

    if (parseFileFilters(interp, fileTypesPtr, typeVariablePtr) != TCL_OK) {
	goto end;
    }

    if (filterInfo.doFileTypes) {

	NSView  *accessoryView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)];
	NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)];


	[label setEditable:NO];
	[label setStringValue:@"Filter:"];
	[label setBordered:NO];
	[label setBezeled:NO];
	[label setDrawsBackground:NO];


	NSPopUpButton *popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 240, 22.0) pullsDown:NO];

	[popupButton addItemsWithTitles:filterInfo.fileTypeLabels];
	[popupButton setAction:@selector(selectFormat:)];

	[accessoryView addSubview:label];
	[accessoryView addSubview:popupButton];

	if (filterInfo.preselectFilter) {

	    /* A specific filter was selected from the typevariable. Select it and
	     * open the accessory view */


	    [popupButton selectItemAtIndex:filterInfo.fileTypeIndex];


	    /* on OSX > 10.11, the optons are not visible by default. Ergo allow all file types

	    [openpanel setAllowedFileTypes:filterInfo.fileTypeExtensions[filterInfo.fileTypeIndex]];
	    */
	    [openpanel setAllowedFileTypes:filterInfo.allowedExtensions];
	} else {
	    [openpanel setAllowedFileTypes:filterInfo.allowedExtensions];
	}

................................................................................
	    [openpanel setAllowsOtherFileTypes:YES];
	} else {
	    [openpanel setAllowsOtherFileTypes:NO];
	}

	[openpanel setAccessoryView:accessoryView];
    } else {

	/* No filters are given. Allow picking all files */


	[openpanel setAllowsOtherFileTypes:YES];
    }

    if (cmdObj) {
	callbackInfo = ckalloc(sizeof(FilePanelCallbackInfo));
	if (Tcl_IsShared(cmdObj)) {
	    cmdObj = Tcl_DuplicateObj(cmdObj);
................................................................................

    callbackInfo->cmdObj = cmdObj;
    callbackInfo->interp = interp;
    callbackInfo->multiple = multiple;
    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
	if (directory || filename ) {
	    NSURL * fileURL = getFileURL(directory, filename);

	    [openpanel setDirectoryURL:fileURL];
	}

	[openpanel beginSheetModalForWindow:parent
	       completionHandler:^(NSInteger returnCode)
	       { [NSApp tkFilePanelDidEnd:openpanel
		       returnCode:returnCode
		       contextInfo:callbackInfo ]; } ];

	modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:openpanel];

    } else {
	if (directory || filename ) {
	    NSURL * fileURL = getFileURL(directory, filename);

	    [openpanel setDirectoryURL:fileURL];
	}

	modalReturnCode = [openpanel runModal];
	[NSApp tkFilePanelDidEnd:openpanel returnCode:modalReturnCode
		contextInfo:callbackInfo];
    }
    result = (modalReturnCode != modalError) ? TCL_OK : TCL_ERROR;
    if (parentIsKey) {
	[parent makeKeyWindow];
    }

    if ((typeVariablePtr && (modalReturnCode == NSOKButton)) &&
	filterInfo.doFileTypes) {
	/*
	 * The -typevariable must be set to the selected file type, if the dialog was not cancelled

	 */

	NSUInteger selectedFilterIndex = filterInfo.fileTypeIndex;
	NSString *selectedFilter = NULL;

	if (filterInfo.userHasSelectedFilter) {
	    selectedFilterIndex = filterInfo.fileTypeIndex;
	    selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex];
	} else {

	    /* Difficult case: the user has not touched the filter settings, but we must
	     * return something in the typevariable. First check if the preselected type is compatible

	     * with the selected file, otherwise choose the first compatible type from the list,
	     * finally fall back to the empty string */


	    NSURL *selectedFile;

	    if (multiple) {

		// Use the first file in the case of multiple selection
		// Anyway it is not overly useful here

		selectedFile = [[openpanel URLs] objectAtIndex:0];
	    } else {
		selectedFile = [openpanel URL];
	    }

	    NSString *extension = [selectedFile pathExtension];

	    if (filterInfo.preselectFilter &&
		filterCompatible(extension, filterInfo.fileTypeIndex)) {
		selectedFilterIndex = filterInfo.fileTypeIndex;  // The preselection from the typevariable
		selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex];
	    } else {
		// scan the list
		NSUInteger i;

		for (i = 0; i < [filterInfo.fileTypeNames count]; i++) {
		    if (filterCompatible(extension, i)) {
			selectedFilterIndex = i;
			break;
		    }
		}
		if (i == selectedFilterIndex) {
		    selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex];
		} else {
		    selectedFilter = @"";
		}

	    }
	}

	Tcl_ObjSetVar2(interp, typeVariablePtr, NULL,
		Tcl_NewStringObj([selectedFilter UTF8String], -1), TCL_GLOBAL_ONLY);

    }


  end:
    return result;
}

 
/*
 *----------------------------------------------------------------------
 *
 * Tk_GetSaveFileObjCmd --
 *
 *	This procedure implements the "save file" dialog box for the Mac
................................................................................
 *	platform. See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See user documentation.

 *----------------------------------------------------------------------
 */

int
Tk_GetSaveFileObjCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
................................................................................
    int index, len;
    Tcl_Obj *cmdObj = NULL, *typeVariablePtr = NULL, *fileTypesPtr = NULL;
    FilePanelCallbackInfo callbackInfoStruct;
    FilePanelCallbackInfo *callbackInfo = &callbackInfoStruct;
    NSString *directory = nil, *filename = nil, *defaultType = nil;
    NSString *message = nil, *title = nil;
    NSWindow *parent;
    savepanel =  [NSSavePanel savePanel];
    NSInteger modalReturnCode = modalError;
    BOOL parentIsKey = NO;

    for (i = 1; i < objc; i += 2) {
	if (Tcl_GetIndexFromObjStruct(interp, objv[i], saveOptionStrings,
		sizeof(char *), "option", TCL_EXACT, &index) != TCL_OK) {
	    goto end;
................................................................................
		break;
	}
    }

    if (title) {
	[savepanel setTitle:title];


	/* From OSX 10.11, the title string is silently ignored, if the save panel is a sheet.
	 * Prepend the title to the message in this case
	 * NOTE should be conditional on OSX version, but
	 * -mmacosx-version-min does not revert this behaviour*/


	if (haveParentOption) {
	    if (message) {

		NSString *fullmessage = [[NSString alloc] initWithFormat:@"%@\n%@",title,message];
		[message release];
		[title release];
		message = fullmessage;
	    } else {
		message = title;
	    }
	}
................................................................................
    }

    if (parseFileFilters(interp, fileTypesPtr, typeVariablePtr) != TCL_OK) {
	goto end;
    }

    if (filterInfo.doFileTypes) {

	NSView  *accessoryView = [[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)];
	NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)];


	[label setEditable:NO];
	[label setStringValue:NSLocalizedString(@"Format:", nil)];
	[label setBordered:NO];
	[label setBezeled:NO];
	[label setDrawsBackground:NO];


	NSPopUpButton *popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 340, 22.0) pullsDown:NO];

	[popupButton addItemsWithTitles:filterInfo.fileTypeLabels];
	[popupButton selectItemAtIndex:filterInfo.fileTypeIndex];
	[popupButton setAction:@selector(saveFormat:)];

	[accessoryView addSubview:label];
	[accessoryView addSubview:popupButton];

	[savepanel setAccessoryView:accessoryView];

	[savepanel setAllowedFileTypes:[filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]];
	[savepanel setAllowsOtherFileTypes:filterInfo.allowedExtensionsAllowAll];
    } else if (defaultType) {

	/* If no filetypes are given, defaultextension is an alternative way
	 * to specify the attached extension. Just propose this extension,
	 * but don't display an accessory view */


	NSMutableArray *AllowedFileTypes = [NSMutableArray array];

	[AllowedFileTypes addObject:defaultType];
	[savepanel setAllowedFileTypes:AllowedFileTypes];
	[savepanel setAllowsOtherFileTypes:YES];
    }

    [savepanel setCanSelectHiddenExtension:YES];
    [savepanel setExtensionHidden:NO];
................................................................................
    }
    callbackInfo->cmdObj = cmdObj;
    callbackInfo->interp = interp;
    callbackInfo->multiple = 0;

    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
       parentIsKey = [parent isKeyWindow];
       if (directory) {
	    [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	}


	   /*check for file name, otherwise set to empty string; crashes with uncaught exception if set to nil*/



	if (filename) {
	    [savepanel setNameFieldStringValue:filename];
	} else {
	    [savepanel setNameFieldStringValue:@""];
	}
	[savepanel beginSheetModalForWindow:parent
	       completionHandler:^(NSInteger returnCode)
	       { [NSApp tkFilePanelDidEnd:savepanel
		       returnCode:returnCode
		       contextInfo:callbackInfo ]; } ];

	modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:savepanel];

    } else {
	if (directory) {
	    [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	}


	 /*check for file name, otherwise set to empty string; crashes with uncaught exception if set to nil*/



	if (filename) {
	    [savepanel setNameFieldStringValue:filename];
	} else {
	    [savepanel setNameFieldStringValue:@""];
	}
	modalReturnCode = [savepanel runModal];
	[NSApp tkFilePanelDidEnd:savepanel returnCode:modalReturnCode
................................................................................
		contextInfo:callbackInfo];
    }
    result = (modalReturnCode != modalError) ? TCL_OK : TCL_ERROR;
    if (parentIsKey) {
	[parent makeKeyWindow];
    }

    if ((typeVariablePtr && (modalReturnCode == NSOKButton)) && filterInfo.doFileTypes) {

	/*
	 * The -typevariable must be set to the selected file type, if the dialog was not cancelled

	 */


	NSString * selectedFilter = [filterInfo.fileTypeNames objectAtIndex:filterInfo.fileTypeIndex];
	Tcl_ObjSetVar2(interp, typeVariablePtr, NULL,
		Tcl_NewStringObj([selectedFilter UTF8String], -1), TCL_GLOBAL_ONLY);

    }


  end:
    return result;
}
 
/*
 *----------------------------------------------------------------------
................................................................................
	    cmdObj = Tcl_DuplicateObj(cmdObj);
	}
	Tcl_IncrRefCount(cmdObj);
    }
    callbackInfo->cmdObj = cmdObj;
    callbackInfo->interp = interp;
    callbackInfo->multiple = 0;


    /*check for directory value, set to root if not specified; otherwise crashes with exception because of nil string parameter*/



    if (!directory) {
	directory = @"/";
    }
    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
	[panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	[panel beginSheetModalForWindow:parent
	       completionHandler:^(NSInteger returnCode)
	       { [NSApp tkFilePanelDidEnd:panel
		       returnCode:returnCode
		       contextInfo:callbackInfo ]; } ];

	modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:panel];
    } else {
	[panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	modalReturnCode = [panel runModal];
	[NSApp tkFilePanelDidEnd:panel returnCode:modalReturnCode
		contextInfo:callbackInfo];
    }
................................................................................

    /*
     * This replaces the old about dialog with a standard alert that displays
     * correctly on 10.14.
     */

    NSString *version =  @"Tcl " TCL_PATCH_LEVEL " & Tk " TCL_PATCH_LEVEL;
    NSString *url =   @"www.tcl-lang.org";
    NSTextView *credits = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,300,300)];
    NSFont *font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
    NSDictionary *textAttributes = [NSDictionary dictionaryWithObject:font
					        forKey:NSFontAttributeName];

    [credits insertText: [[NSAttributedString alloc]
		 initWithString:[NSString stringWithFormat: @"\n"
		"Tcl and Tk are distributed under a modified BSD license: "
		"www.tcl.tk/software/tcltk/license.html\n\n"
		"%1$C 1987-%2$@ Tcl Core Team and Contributers.\n\n"
		"%1$C 2011-%2$@ Kevin Walzer/WordTech Communications LLC.\n\n"
		"%1$C 2014-%2$@ Marc Culler.\n\n"
		"%1$C 2002-2012 Daniel A. Steffen.\n\n"
		"%1$C 2001-2009 Apple Inc.\n\n"
		"%1$C 2001-2002 Jim Ingham & Ian Reid\n\n"
		"%1$C 1998-2000 Jim Ingham & Ray Johnson\n\n"
		"%1$C 1998-2000 Scriptics Inc.\n\n"
		"%1$C 1996-1997 Sun Microsystems Inc.", 0xA9, year]
	     attributes:textAttributes]
             replacementRange:NSMakeRange(0,0)];
    [credits setDrawsBackground:NO];
    [credits setEditable:NO];

     NSAlert *about = [[NSAlert alloc] init];

    [[about window] setTitle:@"About Tcl & Tk"];
    [about setMessageText: version];
    [about setInformativeText:url];
    about.accessoryView = credits;
    [about runModal];
    [about release];
}
................................................................................
    if (indexDefaultOption) {
	/*
	 * Any '-default' option needs to know the '-type' option, which is
	 * why we do this here.
	 */

	if (Tcl_GetIndexFromObjStruct(interp, objv[indexDefaultOption + 1],
		alertButtonStrings, sizeof(char *), "-default value", TCL_EXACT, &index) != TCL_OK) {

	    goto end;
	}

	/*
	 * Need to map from "ok" etc. to 1, 2, 3, right to left.
	 */

................................................................................
	    goto end;
	}
    }
    [alert setIcon:[NSApp applicationIconImage]];
    [alert setAlertStyle:alertStyles[iconIndex]];
    i = 0;
    while (i < 3 && alertButtonNames[typeIndex][i]) {
	[alert addButtonWithTitle:(NSString*)alertButtonNames[typeIndex][i++]];
    }
    buttons = [alert buttons];
    for (NSButton *b in buttons) {
	NSString *ke = [b keyEquivalent];

	if (([ke isEqualToString:@"\r"] || [ke isEqualToString:@"\033"]) &&
		![b keyEquivalentModifierMask]) {
................................................................................
    callbackInfo->interp = interp;
    callbackInfo->typeIndex = typeIndex;
    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1090
 	[alert beginSheetModalForWindow:parent
	       completionHandler:^(NSModalResponse returnCode)
	       { [NSApp tkAlertDidEnd:alert
			returnCode:returnCode
			contextInfo:callbackInfo ]; } ];

#else
	[alert beginSheetModalForWindow:parent
	       modalDelegate:NSApp
	       didEndSelector:@selector(tkAlertDidEnd:returnCode:contextInfo:)
	       contextInfo:callbackInfo];
#endif
	modalReturnCode = cmdObj ? 0 :
................................................................................

typedef struct FontchooserData {
    Tcl_Obj *titleObj;
    Tcl_Obj *cmdObj;
    Tk_Window parent;
} FontchooserData;

enum FontchooserEvent { FontchooserClosed, FontchooserSelection };




static void		FontchooserEvent(int kind);
static Tcl_Obj *	FontchooserCget(FontchooserData *fcdPtr,
			    int optionIndex);
static int		FontchooserConfigureCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
			    Tcl_Obj *const objv[]);
................................................................................
@end
 
/*
 *----------------------------------------------------------------------
 *
 * FontchooserEvent --
 *
 *	This processes events generated by user interaction with the
 *	font panel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Additional events may be place on the Tk event queue.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * FontchooserCget --
 *
 *	Helper for the FontchooserConfigure command to return the
 *	current value of any of the options (which may be NULL in
 *	the structure)
 *
 * Results:
 *	Tcl object of option value.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * FontchooserConfigureCmd --
 *
 *	Implementation of the 'tk fontchooser configure' ensemble command.
 *	See the user documentation for what it does.
 *
 * Results:
 *	See the user documentation.
 *
 * Side effects:
 *	Per-interp data structure may be modified
 *
................................................................................
	    NSFontPanel *fp = [fm fontPanel:NO];

	    [fp setPanelFont:fontPanelFont isMultiple:NO];
	    [fm setSelectedFont:fontPanelFont isMultiple:NO];
	    [fm setSelectedAttributes:fontPanelFontAttributes
		    isMultiple:NO];
	    if ([fp isVisible]) {
		TkSendVirtualEvent(fcdPtr->parent, "TkFontchooserFontChanged", NULL);

	    }
	    break;
	case FontchooserCmd:
	    if (fcdPtr->cmdObj) {
		Tcl_DecrRefCount(fcdPtr->cmdObj);
	    }
	    Tcl_GetStringFromObj(objv[i+1], &len);
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * FontchooserShowCmd --
 *
 *	Implements the 'tk fontchooser show' ensemble command. The
 *	per-interp configuration data for the dialog is held in an interp
 *	associated structure.
 *
 * Results:
 *	See the user documentation.
 *
 * Side effects:
 *	Font Panel may be shown.
 *
................................................................................
	    NULL);

    if (fcdPtr->parent == None) {
	fcdPtr->parent = (Tk_Window) clientData;
	Tk_CreateEventHandler(fcdPtr->parent, StructureNotifyMask,
		FontchooserParentEventHandler, fcdPtr);
    }

    NSFontManager *fm = [NSFontManager sharedFontManager];
    NSFontPanel *fp = [fm fontPanel:YES];

    if ([fp delegate] != NSApp) {
	[fp setDelegate:NSApp];
    }
    if (![fp isVisible]) {
	[fm orderFrontFontPanel:NSApp];
	TkSendVirtualEvent(fcdPtr->parent, "TkFontchooserVisibility", NULL);
    }
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * FontchooserHideCmd --
 *
 *	Implementation of the 'tk fontchooser hide' ensemble. See the
 *	user documentation for details.
 *
 * Results:
 *	See the user documentation.
 *
 * Side effects:
 *	Font Panel may be hidden.
 *
................................................................................
FontchooserHideCmd(
    ClientData clientData,	/* Main window */
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *const objv[])
{
    NSFontPanel *fp = [[NSFontManager sharedFontManager] fontPanel:NO];

    if ([fp isVisible]) {
	[fp orderOut:NSApp];
    }
    return TCL_OK;
}
 
/*
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * TkInitFontchooser --
 *
 *	Associate the font chooser configuration data with the Tcl
 *	interpreter. There is one font chooser per interp.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	per-interp configuration data is destroyed.
 *







|



>
|
>
>

>
|
|
>
|
<
>
|
>
|
>
|
>
|
<
>
|
|
<
>
|
>


|
<
|
|







 







|
|

>
>
>
|
>
>







 







<







 







>
>
|
|
|
>
>
>


>
|







 







>
|







 







>







 







>
|
|
>
>
>
>
>
>
|
>







>







 







|
>


|
|










|











>
|
>
>









|





|
|
>
>
>

<



>
|
>
>
|
>

>
|
>
>

>
|
>
|
>
|







 







>
>
|
>
>
>
|

>
|
>
>






<







 







>
|
|
|
|
>


>
|







 







>
|
|
>
>






>
|
>







>
|
|
>
>

>
>
|
>







 







>
|
>
>







 







|
|
>




|
|

|
>
|
>

|
|
>












|
|

|
>

>


>




>
|
|
>
|
|
>
>

>

>
|
|
>






>

|





>











<




|
>

<




<







 







>







 







|







 







>
|
|
|
|
>
>


>
|







 







>
|
|
>
>






>
|
>












>
|
|
|
>
>

>







 







|
|


>
>
|
>
>
>






|
|

|
>
|
>




>
>
|
>
>
>







 







|
>

|
>

>
>
|

|
>

<







 







>
>
|
>
>
>








|
|
|
|
>







 







|




>













|
|


>
|
>







 







|
>







 







|







 







|
|
|
|
>







 







|
>
>
>







 







|
|







 







|
|
<







 







|
|







 







|
>







 







|
|
|







 







>


>







 







|
|







 







>







 







|
|







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
...
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
...
238
239
240
241
242
243
244

245
246
247
248
249
250
251
...
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
...
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
...
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
...
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
...
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
...
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
...
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
...
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
...
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
...
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
...
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
....
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
....
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
....
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
....
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
....
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
....
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
....
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
....
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
....
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
....
1746
1747
1748
1749
1750
1751
1752
1753
1754

1755
1756
1757
1758
1759
1760
1761
....
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
....
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
....
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
....
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
....
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
....
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
....
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138

#if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
#define modalOK     NSOKButton
#define modalCancel NSCancelButton
#else
#define modalOK     NSModalResponseOK
#define modalCancel NSModalResponseCancel
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < 1090
#define modalOther  -1
#define modalError  -2

/*
 * Vars for filtering in "open file" and "save file" dialogs.
 */

typedef struct {
    bool doFileTypes;			/* Show the accessory view which
					 * displays the filter menu */
    bool preselectFilter;		/* A filter was selected by the
					 * typevariable. */
    bool userHasSelectedFilter;		/* The user has changed the filter in

					 * the accessory view. */
    NSMutableArray *fileTypeNames;	/* Array of names, e.g. "Text
					 * document". */
    NSMutableArray *fileTypeExtensions;	/* Array of allowed extensions per
					 * name, e.g. "txt", "doc". */
    NSMutableArray *fileTypeLabels;	/* Displayed string, e.g. "Text
					 * document (.txt, .doc)". */ 
    NSMutableArray *fileTypeAllowsAll;	/* Boolean if the all pattern (*.*) is

					 * included. */
    NSMutableArray *allowedExtensions;	/* Set of all allowed extensions. */
    bool allowedExtensionsAllowAll;	/* Set of all allowed extensions

					 * includes *.* */
    NSUInteger fileTypeIndex;		/* Index of currently selected
					 * filter. */
} filepanelFilterInfo;

static filepanelFilterInfo filterInfo;

static NSOpenPanel *openpanel;
static NSSavePanel *savepanel;

static const char *const colorOptionStrings[] = {
    "-initialcolor", "-parent", "-title", NULL
};
enum colorOptions {
    COLOR_INITIAL, COLOR_PARENT, COLOR_TITLE
};
................................................................................
    [TYPE_OKCANCEL] =		{3, 4, 0},
    [TYPE_RETRYCANCEL] =	{1, 4, 0},
    [TYPE_YESNO] =		{6, 5, 0},
    [TYPE_YESNOCANCEL] =	{6, 5, 4},
};

/*
 * Construct a file URL from directory and filename. Either may be nil. If both
 * are nil, returns nil.
 */

static NSURL *
getFileURL(
    NSString *directory,
    NSString *filename)
{
    NSURL *url = nil;
    if (directory) {
	url = [NSURL fileURLWithPath:directory isDirectory:YES];
    }
    if (filename) {
	url = [NSURL URLWithString:filename relativeToURL:url];
    }
................................................................................
    }
    if (callbackInfo->cmdObj) {
	Tcl_DecrRefCount(callbackInfo->cmdObj);
	ckfree(callbackInfo);
    }
}


- (void) tkAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode
	contextInfo: (void *) contextInfo
{
    AlertCallbackInfo *callbackInfo = contextInfo;

    if (returnCode >= NSAlertFirstButtonReturn) {
	Tcl_Obj *resultObj = Tcl_NewStringObj(alertButtonStrings[
................................................................................

- (void)selectFormat:(id)sender  {
    NSPopUpButton *button      = (NSPopUpButton *)sender;
    filterInfo.fileTypeIndex   = [button indexOfSelectedItem];

    if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterInfo.fileTypeIndex] boolValue]) {
	[openpanel setAllowsOtherFileTypes:YES];

	/*
	 * setAllowsOtherFileTypes might have no effect; it's inherited from
	 * the NSSavePanel, where it has the effect that it does not append an
	 * extension. Setting the allowed file types to nil allows selecting
	 * any file.
	 */

	[openpanel setAllowedFileTypes:nil];
    } else {
	NSMutableArray *allowedtypes =
		[filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex];
	[openpanel setAllowedFileTypes:allowedtypes];
	[openpanel setAllowsOtherFileTypes:NO];
    }

    filterInfo.userHasSelectedFilter = true;
}

................................................................................
    NSPopUpButton *button     = (NSPopUpButton *)sender;
    filterInfo.fileTypeIndex  = [button indexOfSelectedItem];

    if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterInfo.fileTypeIndex] boolValue]) {
	[savepanel setAllowsOtherFileTypes:YES];
	[savepanel setAllowedFileTypes:nil];
    } else {
	NSMutableArray *allowedtypes =
		[filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex];
	[savepanel setAllowedFileTypes:allowedtypes];
	[savepanel setAllowsOtherFileTypes:NO];
    }

    filterInfo.userHasSelectedFilter = true;
}

................................................................................
    [colorPanel orderOut:NSApp];
    [colorPanel setContinuous:NO];
    [colorPanel setBecomesKeyOnlyIfNeeded:NO];
    [colorPanel setShowsAlpha: NO];
    [colorPanel _setUseModalAppearance:YES];
    if (title) {
	NSString *s = [[NSString alloc] initWithUTF8String:title];

	[colorPanel setTitle:s];
	[s release];
    }
    if (initialColor) {
	[colorPanel setColor:initialColor];
    }
    returnCode = [NSApp runModalForWindow:colorPanel];
................................................................................
    }
    result = TCL_OK;

end:
    return result;
}

/*
 * Dissect the -filetype nested lists and store the information in the
 * filterInfo structure.
 */

static int
parseFileFilters(
    Tcl_Interp *interp,
    Tcl_Obj *fileTypesPtr,
    Tcl_Obj *typeVariablePtr)
{

    if (!fileTypesPtr) {
	filterInfo.doFileTypes = false;
	return TCL_OK;
    }

    FileFilterList fl;

    TkInitFileFilters(&fl);
    if (TkGetFileFilters(interp, &fl, fileTypesPtr, 0) != TCL_OK) {
	TkFreeFileFilters(&fl);
	return TCL_ERROR;
    }

    filterInfo.doFileTypes = (fl.filters != NULL);
................................................................................

    filterInfo.allowedExtensions = [NSMutableArray array];
    filterInfo.allowedExtensionsAllowAll = NO;

    if (filterInfo.doFileTypes) {
	for (FileFilter *filterPtr = fl.filters; filterPtr;
		filterPtr = filterPtr->next) {
	    NSString *name = [[NSString alloc] initWithUTF8String: filterPtr->name];

	    [filterInfo.fileTypeNames addObject:name];
	    [name release];
	    NSMutableArray *clauseextensions = [NSMutableArray array];
	    NSMutableArray *displayextensions = [NSMutableArray array];
	    bool allowsAll = NO;

	    for (FileFilterClause *clausePtr = filterPtr->clauses; clausePtr;
		    clausePtr = clausePtr->next) {

		for (GlobPattern *globPtr = clausePtr->patterns; globPtr;
			globPtr = globPtr->next) {
		    const char *str = globPtr->pattern;
		    while (*str && (*str == '*' || *str == '.')) {
		    	str++;
		    }
		    if (*str) {
			NSString *extension = [[NSString alloc] initWithUTF8String:str];
			if (![filterInfo.allowedExtensions containsObject:extension]) {
			    [filterInfo.allowedExtensions addObject:extension];
			}

			[clauseextensions addObject:extension];
			[displayextensions addObject:[@"." stringByAppendingString:extension]];

			[extension release];
		    } else {
			/*
			 * It is the all pattern (*, .* or *.*)
			 */

			allowsAll = YES;
			filterInfo.allowedExtensionsAllowAll = YES;
			[displayextensions addObject:@"*"];
		    }
		}
	    }
	    [filterInfo.fileTypeExtensions addObject:clauseextensions];
	    [filterInfo.fileTypeAllowsAll addObject:[NSNumber numberWithBool:allowsAll]];

	    NSMutableString *label = [[NSMutableString alloc] initWithString:name];
	    [label appendString:@" ("];
	    [label appendString:[displayextensions componentsJoinedByString:@", "]];
	    [label appendString:@")"];
	    [filterInfo.fileTypeLabels addObject:label];
	    [label release];
	}

	/*
	 * Check if the typevariable exists and matches one of the names.
	 */


	filterInfo.preselectFilter = false;
	filterInfo.userHasSelectedFilter = false;
	if (typeVariablePtr) {
	    /*
	     * Extract the variable content as a NSString.
	     */

	    Tcl_Obj *selectedFileTypeObj = Tcl_ObjGetVar2(interp,
		    typeVariablePtr, NULL, TCL_GLOBAL_ONLY);

	    /*
	     * Check that the typevariable exists.
	     */

	    if (selectedFileTypeObj != NULL) {
		const char *selectedFileType =
			Tcl_GetString(selectedFileTypeObj);
		NSString *selectedFileTypeStr =
			[[NSString alloc] initWithUTF8String:selectedFileType];
		NSUInteger index =
			[filterInfo.fileTypeNames indexOfObject:selectedFileTypeStr];

		if (index != NSNotFound) {
		    filterInfo.fileTypeIndex = index;
		    filterInfo.preselectFilter = true;
		}
	    }
	}
................................................................................

    }

    TkFreeFileFilters(&fl);
    return TCL_OK;
}

static bool
filterCompatible(
    NSString *extension,
    int filterIndex)
{
    NSMutableArray *allowedExtensions =
	    [filterInfo.fileTypeExtensions objectAtIndex: filterIndex];

    /*
     * If this contains the all pattern, accept any extension.
     */

    if ([[filterInfo.fileTypeAllowsAll objectAtIndex:filterIndex] boolValue]) {
	return true;
    }

    return [allowedExtensions containsObject: extension];
}

 
/*
 *----------------------------------------------------------------------
 *
 * Tk_GetOpenFileObjCmd --
 *
 *	This procedure implements the "open file" dialog box for the Mac
................................................................................
	    break;
	}
    }

    if (title) {
	[openpanel setTitle:title];

	/*
	 * From OSX 10.11, the title string is silently ignored in the open
	 * panel.  Prepend the title to the message in this case.  NOTE should
	 * be conditional on OSX version, but -mmacosx-version-min does not
	 * revert this behaviour
	 */

	if (message) {
	    NSString *fullmessage =
		    [[NSString alloc] initWithFormat:@"%@\n%@", title, message];
	    [message release];
	    [title release];
	    message = fullmessage;
	} else {
	    message = title;
	}
    }
................................................................................
    [openpanel setAllowsMultipleSelection:multiple];

    if (parseFileFilters(interp, fileTypesPtr, typeVariablePtr) != TCL_OK) {
	goto end;
    }

    if (filterInfo.doFileTypes) {
	NSView *accessoryView = [[NSView alloc]
		initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)];
	NSTextField *label = [[NSTextField alloc]
		initWithFrame:NSMakeRect(0, 0, 60, 22)];

	[label setEditable:NO];
	[label setStringValue:@"Filter:"];
	[label setBordered:NO];
	[label setBezeled:NO];
	[label setDrawsBackground:NO];

	NSPopUpButton *popupButton = [[NSPopUpButton alloc]
		initWithFrame:NSMakeRect(50.0, 2, 240, 22.0) pullsDown:NO];

	[popupButton addItemsWithTitles:filterInfo.fileTypeLabels];
	[popupButton setAction:@selector(selectFormat:)];

	[accessoryView addSubview:label];
	[accessoryView addSubview:popupButton];

	if (filterInfo.preselectFilter) {
	    /*
	     * A specific filter was selected from the typevariable. Select it
	     * and open the accessory view.
	     */

	    [popupButton selectItemAtIndex:filterInfo.fileTypeIndex];

	    /*
	     * On OSX > 10.11, the options are not visible by default. Ergo
	     * allow all file types
	    [openpanel setAllowedFileTypes:filterInfo.fileTypeExtensions[filterInfo.fileTypeIndex]];
	    */
	    [openpanel setAllowedFileTypes:filterInfo.allowedExtensions];
	} else {
	    [openpanel setAllowedFileTypes:filterInfo.allowedExtensions];
	}

................................................................................
	    [openpanel setAllowsOtherFileTypes:YES];
	} else {
	    [openpanel setAllowsOtherFileTypes:NO];
	}

	[openpanel setAccessoryView:accessoryView];
    } else {
	/*
	 * No filters are given. Allow picking all files.
	 */

	[openpanel setAllowsOtherFileTypes:YES];
    }

    if (cmdObj) {
	callbackInfo = ckalloc(sizeof(FilePanelCallbackInfo));
	if (Tcl_IsShared(cmdObj)) {
	    cmdObj = Tcl_DuplicateObj(cmdObj);
................................................................................

    callbackInfo->cmdObj = cmdObj;
    callbackInfo->interp = interp;
    callbackInfo->multiple = multiple;
    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
	if (directory || filename) {
	    NSURL *fileURL = getFileURL(directory, filename);

	    [openpanel setDirectoryURL:fileURL];
	}

	[openpanel beginSheetModalForWindow:parent
	       completionHandler:^(NSInteger returnCode) {
	    [NSApp tkFilePanelDidEnd:openpanel
		       returnCode:returnCode
		       contextInfo:callbackInfo ];
	}];
	modalReturnCode = cmdObj ? modalOther :
		[NSApp runModalForWindow:openpanel];
    } else {
	if (directory || filename) {
	    NSURL *fileURL = getFileURL(directory, filename);

	    [openpanel setDirectoryURL:fileURL];
	}

	modalReturnCode = [openpanel runModal];
	[NSApp tkFilePanelDidEnd:openpanel returnCode:modalReturnCode
		contextInfo:callbackInfo];
    }
    result = (modalReturnCode != modalError) ? TCL_OK : TCL_ERROR;
    if (parentIsKey) {
	[parent makeKeyWindow];
    }

    if ((typeVariablePtr && (modalReturnCode == NSOKButton))
	    && filterInfo.doFileTypes) {
	/*
	 * The -typevariable must be set to the selected file type, if the
	 * dialog was not cancelled.
	 */

	NSUInteger selectedFilterIndex = filterInfo.fileTypeIndex;
	NSString *selectedFilter = NULL;

	if (filterInfo.userHasSelectedFilter) {
	    selectedFilterIndex = filterInfo.fileTypeIndex;
	    selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex];
	} else {
	    /*
	     * Difficult case: the user has not touched the filter settings,
	     * but we must return something in the typevariable. First check if
	     * the preselected type is compatible with the selected file,
	     * otherwise choose the first compatible type from the list,
	     * finally fall back to the empty string.
	     */

	    NSURL *selectedFile;

	    if (multiple) {
		/*
		 * Use the first file in the case of multiple selection.
		 * Anyway it is not overly useful here.
		 */
		selectedFile = [[openpanel URLs] objectAtIndex:0];
	    } else {
		selectedFile = [openpanel URL];
	    }

	    NSString *extension = [selectedFile pathExtension];

	    if (filterInfo.preselectFilter &&
		    filterCompatible(extension, filterInfo.fileTypeIndex)) {
		selectedFilterIndex = filterInfo.fileTypeIndex;  // The preselection from the typevariable
		selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex];
	    } else {
		// scan the list
		NSUInteger i;

		for (i = 0; i < [filterInfo.fileTypeNames count]; i++) {
		    if (filterCompatible(extension, i)) {
			selectedFilterIndex = i;
			break;
		    }
		}
		if (i == selectedFilterIndex) {
		    selectedFilter = [filterInfo.fileTypeNames objectAtIndex:selectedFilterIndex];
		} else {
		    selectedFilter = @"";
		}

	    }
	}

	Tcl_ObjSetVar2(interp, typeVariablePtr, NULL,
		Tcl_NewStringObj([selectedFilter UTF8String], -1),
		TCL_GLOBAL_ONLY);
    }


  end:
    return result;
}

 
/*
 *----------------------------------------------------------------------
 *
 * Tk_GetSaveFileObjCmd --
 *
 *	This procedure implements the "save file" dialog box for the Mac
................................................................................
 *	platform. See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See user documentation.
 *
 *----------------------------------------------------------------------
 */

int
Tk_GetSaveFileObjCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
................................................................................
    int index, len;
    Tcl_Obj *cmdObj = NULL, *typeVariablePtr = NULL, *fileTypesPtr = NULL;
    FilePanelCallbackInfo callbackInfoStruct;
    FilePanelCallbackInfo *callbackInfo = &callbackInfoStruct;
    NSString *directory = nil, *filename = nil, *defaultType = nil;
    NSString *message = nil, *title = nil;
    NSWindow *parent;
    savepanel = [NSSavePanel savePanel];
    NSInteger modalReturnCode = modalError;
    BOOL parentIsKey = NO;

    for (i = 1; i < objc; i += 2) {
	if (Tcl_GetIndexFromObjStruct(interp, objv[i], saveOptionStrings,
		sizeof(char *), "option", TCL_EXACT, &index) != TCL_OK) {
	    goto end;
................................................................................
		break;
	}
    }

    if (title) {
	[savepanel setTitle:title];

	/*
	 * From OSX 10.11, the title string is silently ignored, if the save
	 * panel is a sheet.  Prepend the title to the message in this case.
	 * NOTE: should be conditional on OSX version, but -mmacosx-version-min
	 * does not revert this behaviour.
	 */

	if (haveParentOption) {
	    if (message) {
		NSString *fullmessage =
		    [[NSString alloc] initWithFormat:@"%@\n%@",title,message];
		[message release];
		[title release];
		message = fullmessage;
	    } else {
		message = title;
	    }
	}
................................................................................
    }

    if (parseFileFilters(interp, fileTypesPtr, typeVariablePtr) != TCL_OK) {
	goto end;
    }

    if (filterInfo.doFileTypes) {
	NSView *accessoryView = [[NSView alloc]
		initWithFrame:NSMakeRect(0.0, 0.0, 300, 32.0)];
	NSTextField *label = [[NSTextField alloc]
		initWithFrame:NSMakeRect(0, 0, 60, 22)];

	[label setEditable:NO];
	[label setStringValue:NSLocalizedString(@"Format:", nil)];
	[label setBordered:NO];
	[label setBezeled:NO];
	[label setDrawsBackground:NO];

	NSPopUpButton *popupButton = [[NSPopUpButton alloc]
		initWithFrame:NSMakeRect(50.0, 2, 340, 22.0) pullsDown:NO];

	[popupButton addItemsWithTitles:filterInfo.fileTypeLabels];
	[popupButton selectItemAtIndex:filterInfo.fileTypeIndex];
	[popupButton setAction:@selector(saveFormat:)];

	[accessoryView addSubview:label];
	[accessoryView addSubview:popupButton];

	[savepanel setAccessoryView:accessoryView];

	[savepanel setAllowedFileTypes:[filterInfo.fileTypeExtensions objectAtIndex:filterInfo.fileTypeIndex]];
	[savepanel setAllowsOtherFileTypes:filterInfo.allowedExtensionsAllowAll];
    } else if (defaultType) {
	/*
	 * If no filetypes are given, defaultextension is an alternative way to
	 * specify the attached extension. Just propose this extension, but
	 * don't display an accessory view.
	 */

	NSMutableArray *AllowedFileTypes = [NSMutableArray array];

	[AllowedFileTypes addObject:defaultType];
	[savepanel setAllowedFileTypes:AllowedFileTypes];
	[savepanel setAllowsOtherFileTypes:YES];
    }

    [savepanel setCanSelectHiddenExtension:YES];
    [savepanel setExtensionHidden:NO];
................................................................................
    }
    callbackInfo->cmdObj = cmdObj;
    callbackInfo->interp = interp;
    callbackInfo->multiple = 0;

    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
	if (directory) {
	    [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	}

	/*
	 * Check for file name, otherwise set to empty string; crashes with
	 * uncaught exception if set to nil.
	 */

	if (filename) {
	    [savepanel setNameFieldStringValue:filename];
	} else {
	    [savepanel setNameFieldStringValue:@""];
	}
	[savepanel beginSheetModalForWindow:parent
		completionHandler:^(NSInteger returnCode) {
	    [NSApp tkFilePanelDidEnd:savepanel
		       returnCode:returnCode
		       contextInfo:callbackInfo];
	}];
	modalReturnCode = cmdObj ? modalOther :
		[NSApp runModalForWindow:savepanel];
    } else {
	if (directory) {
	    [savepanel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	}

	/*
	 * Check for file name, otherwise set to empty string; crashes with
	 * uncaught exception if set to nil.
	 */

	if (filename) {
	    [savepanel setNameFieldStringValue:filename];
	} else {
	    [savepanel setNameFieldStringValue:@""];
	}
	modalReturnCode = [savepanel runModal];
	[NSApp tkFilePanelDidEnd:savepanel returnCode:modalReturnCode
................................................................................
		contextInfo:callbackInfo];
    }
    result = (modalReturnCode != modalError) ? TCL_OK : TCL_ERROR;
    if (parentIsKey) {
	[parent makeKeyWindow];
    }

    if (typeVariablePtr && (modalReturnCode == NSOKButton)
	    && filterInfo.doFileTypes) {
	/*
	 * The -typevariable must be set to the selected file type, if the
	 * dialog was not cancelled.
	 */

	NSString *selectedFilter =
	    [filterInfo.fileTypeNames objectAtIndex:filterInfo.fileTypeIndex];
	Tcl_ObjSetVar2(interp, typeVariablePtr, NULL,
		Tcl_NewStringObj([selectedFilter UTF8String], -1),
		TCL_GLOBAL_ONLY);
    }


  end:
    return result;
}
 
/*
 *----------------------------------------------------------------------
................................................................................
	    cmdObj = Tcl_DuplicateObj(cmdObj);
	}
	Tcl_IncrRefCount(cmdObj);
    }
    callbackInfo->cmdObj = cmdObj;
    callbackInfo->interp = interp;
    callbackInfo->multiple = 0;

    /*
     * Check for directory value, set to root if not specified; otherwise
     * crashes with exception because of nil string parameter.
     */

    if (!directory) {
	directory = @"/";
    }
    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
	[panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	[panel beginSheetModalForWindow:parent
		completionHandler:^(NSInteger returnCode) {
	    [NSApp tkFilePanelDidEnd:panel
		    returnCode:returnCode
		    contextInfo:callbackInfo];
	}];
	modalReturnCode = cmdObj ? modalOther : [NSApp runModalForWindow:panel];
    } else {
	[panel setDirectoryURL:[NSURL fileURLWithPath:directory isDirectory:YES]];
	modalReturnCode = [panel runModal];
	[NSApp tkFilePanelDidEnd:panel returnCode:modalReturnCode
		contextInfo:callbackInfo];
    }
................................................................................

    /*
     * This replaces the old about dialog with a standard alert that displays
     * correctly on 10.14.
     */

    NSString *version =  @"Tcl " TCL_PATCH_LEVEL " & Tk " TCL_PATCH_LEVEL;
    NSString *url = @"www.tcl-lang.org";
    NSTextView *credits = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,300,300)];
    NSFont *font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
    NSDictionary *textAttributes = [NSDictionary dictionaryWithObject:font
					        forKey:NSFontAttributeName];

    [credits insertText: [[NSAttributedString alloc]
		 initWithString:[NSString stringWithFormat: @"\n"
		"Tcl and Tk are distributed under a modified BSD license: "
		"www.tcl.tk/software/tcltk/license.html\n\n"
		"%1$C 1987-%2$@ Tcl Core Team and Contributers.\n\n"
		"%1$C 2011-%2$@ Kevin Walzer/WordTech Communications LLC.\n\n"
		"%1$C 2014-%2$@ Marc Culler.\n\n"
		"%1$C 2002-2012 Daniel A. Steffen.\n\n"
		"%1$C 2001-2009 Apple Inc.\n\n"
		"%1$C 2001-2002 Jim Ingham & Ian Reid\n\n"
		"%1$C 1998-2000 Jim Ingham & Ray Johnson\n\n"
		"%1$C 1998-2000 Scriptics Inc.\n\n"
		"%1$C 1996-1997 Sun Microsystems Inc.", 0xA9, year]
	    attributes:textAttributes]
            replacementRange:NSMakeRange(0,0)];
    [credits setDrawsBackground:NO];
    [credits setEditable:NO];

    NSAlert *about = [[NSAlert alloc] init];

    [[about window] setTitle:@"About Tcl & Tk"];
    [about setMessageText: version];
    [about setInformativeText:url];
    about.accessoryView = credits;
    [about runModal];
    [about release];
}
................................................................................
    if (indexDefaultOption) {
	/*
	 * Any '-default' option needs to know the '-type' option, which is
	 * why we do this here.
	 */

	if (Tcl_GetIndexFromObjStruct(interp, objv[indexDefaultOption + 1],
		alertButtonStrings, sizeof(char *), "-default value",
		TCL_EXACT, &index) != TCL_OK) {
	    goto end;
	}

	/*
	 * Need to map from "ok" etc. to 1, 2, 3, right to left.
	 */

................................................................................
	    goto end;
	}
    }
    [alert setIcon:[NSApp applicationIconImage]];
    [alert setAlertStyle:alertStyles[iconIndex]];
    i = 0;
    while (i < 3 && alertButtonNames[typeIndex][i]) {
	[alert addButtonWithTitle:(NSString*) alertButtonNames[typeIndex][i++]];
    }
    buttons = [alert buttons];
    for (NSButton *b in buttons) {
	NSString *ke = [b keyEquivalent];

	if (([ke isEqualToString:@"\r"] || [ke isEqualToString:@"\033"]) &&
		![b keyEquivalentModifierMask]) {
................................................................................
    callbackInfo->interp = interp;
    callbackInfo->typeIndex = typeIndex;
    parent = TkMacOSXDrawableWindow(((TkWindow *) tkwin)->window);
    if (haveParentOption && parent && ![parent attachedSheet]) {
	parentIsKey = [parent isKeyWindow];
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1090
 	[alert beginSheetModalForWindow:parent
	       completionHandler:^(NSModalResponse returnCode) {
	    [NSApp tkAlertDidEnd:alert
		    returnCode:returnCode
		    contextInfo:callbackInfo];
	}];
#else
	[alert beginSheetModalForWindow:parent
	       modalDelegate:NSApp
	       didEndSelector:@selector(tkAlertDidEnd:returnCode:contextInfo:)
	       contextInfo:callbackInfo];
#endif
	modalReturnCode = cmdObj ? 0 :
................................................................................

typedef struct FontchooserData {
    Tcl_Obj *titleObj;
    Tcl_Obj *cmdObj;
    Tk_Window parent;
} FontchooserData;

enum FontchooserEvent {
    FontchooserClosed,
    FontchooserSelection
};

static void		FontchooserEvent(int kind);
static Tcl_Obj *	FontchooserCget(FontchooserData *fcdPtr,
			    int optionIndex);
static int		FontchooserConfigureCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
			    Tcl_Obj *const objv[]);
................................................................................
@end
 
/*
 *----------------------------------------------------------------------
 *
 * FontchooserEvent --
 *
 *	This processes events generated by user interaction with the font
 *	panel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Additional events may be place on the Tk event queue.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * FontchooserCget --
 *
 *	Helper for the FontchooserConfigure command to return the current value
 *	of any of the options (which may be NULL in the structure).

 *
 * Results:
 *	Tcl object of option value.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * FontchooserConfigureCmd --
 *
 *	Implementation of the 'tk fontchooser configure' ensemble command.  See
 *	the user documentation for what it does.
 *
 * Results:
 *	See the user documentation.
 *
 * Side effects:
 *	Per-interp data structure may be modified
 *
................................................................................
	    NSFontPanel *fp = [fm fontPanel:NO];

	    [fp setPanelFont:fontPanelFont isMultiple:NO];
	    [fm setSelectedFont:fontPanelFont isMultiple:NO];
	    [fm setSelectedAttributes:fontPanelFontAttributes
		    isMultiple:NO];
	    if ([fp isVisible]) {
		TkSendVirtualEvent(fcdPtr->parent,
			"TkFontchooserFontChanged", NULL);
	    }
	    break;
	case FontchooserCmd:
	    if (fcdPtr->cmdObj) {
		Tcl_DecrRefCount(fcdPtr->cmdObj);
	    }
	    Tcl_GetStringFromObj(objv[i+1], &len);
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * FontchooserShowCmd --
 *
 *	Implements the 'tk fontchooser show' ensemble command. The per-interp
 *	configuration data for the dialog is held in an interp associated
 *	structure.
 *
 * Results:
 *	See the user documentation.
 *
 * Side effects:
 *	Font Panel may be shown.
 *
................................................................................
	    NULL);

    if (fcdPtr->parent == None) {
	fcdPtr->parent = (Tk_Window) clientData;
	Tk_CreateEventHandler(fcdPtr->parent, StructureNotifyMask,
		FontchooserParentEventHandler, fcdPtr);
    }

    NSFontManager *fm = [NSFontManager sharedFontManager];
    NSFontPanel *fp = [fm fontPanel:YES];

    if ([fp delegate] != NSApp) {
	[fp setDelegate:NSApp];
    }
    if (![fp isVisible]) {
	[fm orderFrontFontPanel:NSApp];
	TkSendVirtualEvent(fcdPtr->parent, "TkFontchooserVisibility", NULL);
    }
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * FontchooserHideCmd --
 *
 *	Implementation of the 'tk fontchooser hide' ensemble. See the user
 *	documentation for details.
 *
 * Results:
 *	See the user documentation.
 *
 * Side effects:
 *	Font Panel may be hidden.
 *
................................................................................
FontchooserHideCmd(
    ClientData clientData,	/* Main window */
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *const objv[])
{
    NSFontPanel *fp = [[NSFontManager sharedFontManager] fontPanel:NO];

    if ([fp isVisible]) {
	[fp orderOut:NSApp];
    }
    return TCL_OK;
}
 
/*
................................................................................
}
 
/*
 * ----------------------------------------------------------------------
 *
 * TkInitFontchooser --
 *
 *	Associate the font chooser configuration data with the Tcl interpreter.
 *	There is one font chooser per interp.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	per-interp configuration data is destroyed.
 *

Changes to macosx/tkMacOSXDraw.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
..
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
...
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
...
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
...
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
...
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
...
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
...
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
...
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
...
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
...
626
627
628
629
630
631
632
633

634
635
636
637
638
639
640
641
...
651
652
653
654
655
656
657

658
659
660
661
662

663
664
665
666
667
668
669
...
732
733
734
735
736
737
738

739
740
741
742
743
744

745
746
747
748
749
750
751
...
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
...
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
...
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
....
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
....
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
....
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
....
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
....
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
....
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
....
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
....
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
....
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614


1615


1616
1617

1618


1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649


1650
1651

1652
1653
1654
1655
1656
1657
1658
....
1715
1716
1717
1718
1719
1720
1721

1722

1723
1724
1725
1726
1727
1728
1729
....
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
....
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
....
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
....
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
....
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
....
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
/*
 * tkMacOSXDraw.c --
 *
 *	This file contains functions that perform drawing to
 *	Xlib windows. Most of the functions simple emulate
 *	Xlib functions.
 *
 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
 * Copyright 2001-2009, Apple Inc.
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2014 Marc Culler.
 *
 * See the file "license.terms" for information on usage and redistribution
................................................................................
/*
#ifdef TK_MAC_DEBUG
#define TK_MAC_DEBUG_DRAWING
#define TK_MAC_DEBUG_IMAGE_DRAWING
#endif
*/

#define radians(d) ((d) * (M_PI/180.0))

/*
 * Non-antialiased CG drawing looks better and more like X11 drawing when using
 * very fine lines, so decrease all linewidths by the following constant.
 */
#define NON_AA_CG_OFFSET .999

static int cgAntiAliasLimit = 0;
#define notAA(w) ((w) < cgAntiAliasLimit)

static int useThemedToplevel = 0;
static int useThemedFrame = 0;

/*
 * Prototypes for functions used only in this file.
 */
................................................................................
 *      implementation does not work correctly.  Originally it relied on
 *      [NSBitmapImageRep initWithFocusedViewRect:view_rect] which was
 *      deprecated by Apple in OSX 10.14 and also required the use of other
 *      deprecated functions such as [NSView lockFocus]. Apple's suggested
 *      replacement is [NSView cacheDisplayInRect: toBitmapImageRep:] and that
 *      is what is being used here.  However, that method only works when the
 *      view has a valid CGContext, and a view is only guaranteed to have a
 *      valid context during a call to [NSView drawRect].  To further
 *      complicate matters, cacheDisplayInRect calls [NSView drawRect].
 *      Essentially it is asking the view to draw a subrectangle of itself into
 *      a special graphics context which is linked to the BitmapImageRep.  But
 *      our implementation of [NSView drawRect] does not allow recursive calls.
 *      If called recursively it returns immediately without doing any drawing.
 *      So the bottom line is that this function either returns a NULL pointer
 *      or a black image.  To make it useful would require a significant amount
 *      of rewriting of the drawRect method.  Perhaps the next release of OSX
 *      will include some more helpful ways of doing this.
 *
 * Results:
 *	Returns an NSBitmapRep representing the image of the given
 *      rectangle of the given drawable.  This object is retained.
 *      The caller is responsible for releasing it.
 *
 *      NOTE: The x,y coordinates should be relative to a coordinate system with
 *      origin at the top left, as used by XImage and CGImage, not bottom
 *      left as used by NSView.
 *
 * Side effects:
 *     None
 *
 *----------------------------------------------------------------------
 */

NSBitmapImageRep*
TkMacOSXBitmapRepFromDrawableRect(
        Drawable drawable,
	int x,
	int y,
	unsigned int width,
	unsigned int height)
{
    MacDrawable *mac_drawable = (MacDrawable *) drawable;
    CGContextRef cg_context = NULL;
    CGImageRef cg_image=NULL, sub_cg_image = NULL;
    NSBitmapImageRep *bitmap_rep = NULL;
    NSView *view=NULL;
    if ( mac_drawable->flags & TK_IS_PIXMAP ) {

	/*
	 * This MacDrawable is a bitmap, so its view is NULL.
	 */

	cg_context = TkMacOSXGetCGContextForDrawable(drawable);
	CGRect image_rect = CGRectMake(x, y, width, height);


	cg_image = CGBitmapContextCreateImage( (CGContextRef) cg_context);
	sub_cg_image = CGImageCreateWithImageInRect(cg_image, image_rect);
	if ( sub_cg_image ) {
	    bitmap_rep = [NSBitmapImageRep alloc];
	    [bitmap_rep initWithCGImage:sub_cg_image];
	}
	if ( cg_image ) {
	    CGImageRelease(cg_image);
	}
    } else if ( (view = TkMacOSXDrawableView(mac_drawable)) ) {

	/*
	 * Convert Tk top-left to NSView bottom-left coordinates.
	 */

	int view_height = [view bounds].size.height;
	NSRect view_rect = NSMakeRect(x + mac_drawable->xOff,
			       view_height - height - y - mac_drawable->yOff,
			       width, height);

	/*
	 * Attempt to copy from the view to a bitmapImageRep.  If the view does
	 * not have a valid CGContext, doing this will silently corrupt memory
	 * and make a big mess. So, in that case, we mark the view as needing
	 * display and return NULL.
	 */
................................................................................
 *
 *	Copies data from one drawable to another.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Data is moved from a window or bitmap to a second window or
 *	bitmap.
 *
 *----------------------------------------------------------------------
 */

void
XCopyArea(
    Display *display,		/* Display. */
    Drawable src,		/* Source drawable. */
    Drawable dst,		/* Destination drawable. */
    GC gc,				/* GC to use. */
    int src_x,			/* X & Y, width & height */
    int src_y,			/* define the source rectangle */
    unsigned int width,	/* that will be copied. */
    unsigned int height,
    int dest_x,			/* Dest X & Y on dest rect. */
    int dest_y)
{
    TkMacOSXDrawingContext dc;
    MacDrawable *srcDraw = (MacDrawable *) src;
    NSBitmapImageRep *bitmap_rep = NULL;
................................................................................

    display->request++;
    if (!width || !height) {
	return;
    }

    if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) {
	return;
	TkMacOSXDbgMsg("Failed to setup drawing context.");

    }

    if ( dc.context ) {




	if (srcDraw->flags & TK_IS_PIXMAP) {
	    img = TkMacOSXCreateCGImageWithDrawable(src);
	}else if (TkMacOSXDrawableWindow(src)) {
	    bitmap_rep =  TkMacOSXBitmapRepFromDrawableRect(src,
				   src_x, src_y, width, height);
	    if ( bitmap_rep ) {
		img = [bitmap_rep CGImage];
	    }
	} else {
	    TkMacOSXDbgMsg("Invalid source drawable - neither window nor pixmap.");
	}

	if (img) {
	    bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height);
	    srcRect = CGRectMake(src_x, src_y, width, height);
	    dstRect = CGRectMake(dest_x, dest_y, width, height);
	    TkMacOSXDrawCGImage(dst, gc, dc.context, img,
		     gc->foreground, gc->background, bounds, srcRect, dstRect);
	    CFRelease(img);
	} else {
	    TkMacOSXDbgMsg("Failed to construct CGImage.");
	}

    } else {
	TkMacOSXDbgMsg("Invalid destination drawable - no context.");
	return;
    }

    TkMacOSXRestoreDrawingContext(&dc);
}
 
/*
 *----------------------------------------------------------------------
 *
 * XCopyPlane --
 *
 *	Copies a bitmap from a source drawable to a destination
 *	drawable. The plane argument specifies which bit plane of
 *	the source contains the bitmap. Note that this implementation
 *	ignores the gc->function.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Changes the destination drawable.
 *
................................................................................
    if (plane != 1) {
	Tcl_Panic("Unexpected plane specified for XCopyPlane");
    }
    if (srcDraw->flags & TK_IS_PIXMAP) {
	if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) {
	    return;
	}

	CGContextRef context = dc.context;

	if (context) {
	    CGImageRef img = TkMacOSXCreateCGImageWithDrawable(src);

	    if (img) {
		TkpClipMask *clipPtr = (TkpClipMask *) gc->clip_mask;
		unsigned long imageBackground  = gc->background;

                if (clipPtr && clipPtr->type == TKP_CLIP_PIXMAP){
		    srcRect = CGRectMake(src_x, src_y, width, height);
		    CGImageRef mask = TkMacOSXCreateCGImageWithDrawable(clipPtr->value.pixmap);

		    CGImageRef submask = CGImageCreateWithImageInRect(img, srcRect);

		    CGRect rect = CGRectMake(dest_x, dest_y, width, height);

		    rect = CGRectOffset(rect, dstDraw->xOff, dstDraw->yOff);
		    CGContextSaveGState(context);


		    /* Move the origin of the destination to top left. */



		    CGContextTranslateCTM(context, 0, rect.origin.y + CGRectGetMaxY(rect));
		    CGContextScaleCTM(context, 1, -1);


		    /* Fill with the background color, clipping to the mask. */


		    CGContextClipToMask(context, rect, submask);
		    TkMacOSXSetColorInContext(gc, gc->background, dc.context);
		    CGContextFillRect(context, rect);


		    /* Fill with the foreground color, clipping to the
		       intersection of img and mask. */


		    CGImageRef subimage = CGImageCreateWithImageInRect(img, srcRect);

		    CGContextClipToMask(context, rect, subimage);
		    TkMacOSXSetColorInContext(gc, gc->foreground, context);
		    CGContextFillRect(context, rect);
		    CGContextRestoreGState(context);
		    CGImageRelease(img);
		    CGImageRelease(mask);
		    CGImageRelease(submask);
		    CGImageRelease(subimage);
		} else {

		    bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height);
		    srcRect = CGRectMake(src_x, src_y, width, height);
		    dstRect = CGRectMake(dest_x, dest_y, width, height);
		    TkMacOSXDrawCGImage(dst, gc, dc.context, img, gc->foreground,

					imageBackground, bounds, srcRect, dstRect);
		    CGImageRelease(img);
		}

	    } else { /* no image */
		TkMacOSXDbgMsg("Invalid source drawable");
	    }
	} else {
	    TkMacOSXDbgMsg("Invalid destination drawable - could not get a bitmap context.");

	}
	TkMacOSXRestoreDrawingContext(&dc);


    } else { /* source drawable is a window, not a Pixmap */


	XCopyArea(display, src, dst, gc, src_x, src_y, width, height, dest_x, dest_y);

    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXCreateCGImageWithDrawable --
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static NSImage*
CreateNSImageWithPixmap(
    Pixmap pixmap,
    int width,
    int height)
{
    CGImageRef cgImage;
    NSImage *nsImage;
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSImage*
TkMacOSXGetNSImageWithTkImage(
    Display *display,
    Tk_Image image,
    int width,
    int height)
{
    Pixmap pixmap = Tk_GetPixmap(display, None, width, height, 0);
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSImage*
TkMacOSXGetNSImageWithBitmap(
    Display *display,
    Pixmap bitmap,
    GC gc,
    int width,
    int height)
{
................................................................................

    if (macDraw && (macDraw->flags & TK_IS_PIXMAP) && !macDraw->context) {
	const size_t bitsPerComponent = 8;
	size_t bitsPerPixel, bytesPerRow, len;
	CGColorSpaceRef colorspace = NULL;
	CGBitmapInfo bitmapInfo =
#ifdef __LITTLE_ENDIAN__
	kCGBitmapByteOrder32Host;
#else
	kCGBitmapByteOrderDefault;
#endif
	char *data;

	CGRect bounds = CGRectMake(0, 0, macDraw->size.width, macDraw->size.height);

	if (macDraw->flags & TK_IS_BW_PIXMAP) {
	    bitsPerPixel = 8;
	    bitmapInfo = (CGBitmapInfo)kCGImageAlphaOnly;
	} else {
	    colorspace = CGColorSpaceCreateDeviceRGB();
	    bitsPerPixel = 32;
	    bitmapInfo |= kCGImageAlphaPremultipliedFirst;
	}
	bytesPerRow = ((size_t) macDraw->size.width * bitsPerPixel + 127) >> 3
		& ~15;
	len = macDraw->size.height * bytesPerRow;
	data = ckalloc(len);
	bzero(data, len);
	macDraw->context = CGBitmapContextCreate(data, macDraw->size.width,
		macDraw->size.height, bitsPerComponent, bytesPerRow,
		colorspace, bitmapInfo);
	if (macDraw->context) {
................................................................................
	    if (subImage) {
		image = subImage;
	    }
	}
	dstBounds = CGRectOffset(dstBounds, macDraw->xOff, macDraw->yOff);
	if (CGImageIsMask(image)) {
	    if (macDraw->flags & TK_IS_BW_PIXMAP) {


		/* Set fill color to black; background comes from the context,
		 * or is transparent.
		 */

		if (imageBackground != TRANSPARENT_PIXEL << 24) {
		    CGContextClearRect(context, dstBounds);
		}
		CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
................................................................................
#ifdef TK_MAC_DEBUG_IMAGE_DRAWING
	CGContextSaveGState(context);
	CGContextSetLineWidth(context, 1.0);
	CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.1);
	CGContextSetRGBFillColor(context, 0, 1, 0, 0.1);
	CGContextFillRect(context, dstBounds);
	CGContextStrokeRect(context, dstBounds);

	CGPoint p[4] = {dstBounds.origin,
	    CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMaxY(dstBounds)),
	    CGPointMake(CGRectGetMinX(dstBounds), CGRectGetMaxY(dstBounds)),
	    CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMinY(dstBounds))
	};

	CGContextStrokeLineSegments(context, p, 4);
	CGContextRestoreGState(context);
	TkMacOSXDbgMsg("Drawing CGImage at (x=%f, y=%f), (w=%f, h=%f)",
		dstBounds.origin.x, dstBounds.origin.y,
		dstBounds.size.width, dstBounds.size.height);
#else /* TK_MAC_DEBUG_IMAGE_DRAWING */
	CGContextSaveGState(context);
................................................................................
			macWin->yOff + points[i].y + o);
	    } else {
		prevx += points[i].x;
		prevy += points[i].y;
		CGContextAddLineToPoint(dc.context, prevx, prevy);
	    }
	}

        /*
         * In the case of closed polylines, the first and last points
         * are the same. We want miter or bevel join be rendered also
         * at this point, this needs telling CoreGraphics that the
         * path is closed.
         */

        if ((points[0].x == points[npoints-1].x) &&
                (points[0].y == points[npoints-1].y)) {
            CGContextClosePath(dc.context);
        }
	CGContextStrokePath(dc.context);
    }
    TkMacOSXRestoreDrawingContext(&dc);
................................................................................
 *	Draws a filled polygon on the specified drawable.
 *
 *----------------------------------------------------------------------
 */

void
XFillPolygon(
    Display* display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    XPoint* points,		/* Array of points. */
    int npoints,		/* Number of points. */
    int shape,			/* Shape to draw. */
    int mode)			/* Drawing mode. */
{
    MacDrawable *macWin = (MacDrawable *) d;
    TkMacOSXDrawingContext dc;
    int i;
................................................................................
	return;
    }
    if (dc.context) {
	CGRect rect;
	double o = (lw % 2) ? .5 : 0;

	rect = CGRectMake(
		macWin->xOff + x + o,
		macWin->yOff + y + o,
		width, height);
	CGContextStrokeRect(dc.context, rect);
    }
    TkMacOSXRestoreDrawingContext(&dc);
}
 
#ifdef TK_MACOSXDRAW_UNUSED
/*
 *----------------------------------------------------------------------
 *
 * XDrawRectangles --
 *
 *	Draws the outlines of the specified rectangles as if a
 *	five-point PolyLine protocol request were specified for each
 *	rectangle:
 *
 *	    [x,y] [x+width,y] [x+width,y+height] [x,y+height] [x,y]
 *
 *	For the specified rectangles, these functions do not draw a
 *	pixel more than once. XDrawRectangles draws the rectangles in
 *	the order listed in the array. If rectangles intersect, the
 *	intersecting pixels are drawn multiple times. Draws a
 *	rectangle.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws rectangles on the specified drawable.
 *
................................................................................
 *	Draws onto the specified drawable.
 *
 *----------------------------------------------------------------------
 */

int
XFillRectangles(
    Display* display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    XRectangle *rectangles,	/* Rectangle array. */
    int n_rectangles)		/* Number of rectangles. */
{
    MacDrawable *macWin = (MacDrawable *) d;
    TkMacOSXDrawingContext dc;
................................................................................
 *	Draws an arc on the specified drawable.
 *
 *----------------------------------------------------------------------
 */

void
XDrawArc(
    Display* display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    int x, int y,		/* Upper left of bounding rect. */
    unsigned int width,		/* Width & height. */
    unsigned int height,
    int angle1,			/* Staring angle of arc. */
    int angle2)			/* Extent of arc. */
................................................................................
 
#ifdef TK_MACOSXDRAW_UNUSED
/*
 *----------------------------------------------------------------------
 *
 * XDrawArcs --
 *
 *	Draws multiple circular or elliptical arcs. Each arc is
 *	specified by a rectangle and two angles. The center of the
 *	circle or ellipse is the center of the rect- angle, and the
 *	major and minor axes are specified by the width and height.
 *	Positive angles indicate counterclock- wise motion, and
 *	negative angles indicate clockwise motion. If the magnitude
 *	of angle2 is greater than 360 degrees, XDrawArcs truncates it
 *	to 360 degrees.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws an arc for each array element on the specified drawable.
 *
................................................................................
XDrawArcs(
    Display *display,
    Drawable d,
    GC gc,
    XArc *arcArr,
    int nArcs)
{

    MacDrawable *macWin = (MacDrawable *) d;
    TkMacOSXDrawingContext dc;
    XArc *arcPtr;
    int i, lw = gc->line_width;

    display->request++;
    if (!TkMacOSXSetupDrawingContext(d, gc, 1, &dc)) {
................................................................................
 *	Draws a filled arc on the specified drawable.
 *
 *----------------------------------------------------------------------
 */

void
XFillArc(
    Display* display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    int x, int y,		/* Upper left of bounding rect. */
    unsigned int width,		/* Width & height. */
    unsigned int height,
    int angle1,			/* Staring angle of arc. */
    int angle2)			/* Extent of arc. */
................................................................................
#endif
 
/*
 *----------------------------------------------------------------------
 *
 * TkScrollWindow --
 *
 *	Scroll a rectangle of the specified window and accumulate
 *	a damage region.
 *
 * Results:
 *	Returns 0 if the scroll generated no additional damage.
 *	Otherwise, sets the region that needs to be repainted after
 *	scrolling and returns 1.
 *
 * Side effects:
 *	Scrolls the bits in the window.
 *
 *----------------------------------------------------------------------
 */

................................................................................
    int x, int y,		/* Position rectangle to be scrolled. */
    int width, int height,
    int dx, int dy,		/* Distance rectangle should be moved. */
    TkRegion damageRgn)		/* Region to accumulate damage in. */
{
    Drawable drawable = Tk_WindowId(tkwin);
    MacDrawable *macDraw = (MacDrawable *) drawable;
    TKContentView *view = (TKContentView *)TkMacOSXDrawableView(macDraw);
    CGRect srcRect, dstRect;
    HIShapeRef dmgRgn = NULL, extraRgn = NULL;
    NSRect bounds, visRect, scrollSrc, scrollDst;
    int result = 0;

    if ( view ) {

  	/*  Get the scroll area in NSView coordinates (origin at bottom left). */


  	bounds = [view bounds];
 	scrollSrc = NSMakeRect(macDraw->xOff + x,
			       bounds.size.height - height - (macDraw->yOff + y),
			       width, height);
 	scrollDst = NSOffsetRect(scrollSrc, dx, -dy);


  	/* Limit scrolling to the window content area. */


 	visRect = [view visibleRect];
 	scrollSrc = NSIntersectionRect(scrollSrc, visRect);
 	scrollDst = NSIntersectionRect(scrollDst, visRect);
 	if ( !NSIsEmptyRect(scrollSrc) && !NSIsEmptyRect(scrollDst) ) {
  	    /*
  	     * Mark the difference between source and destination as damaged.
	     * This region is described in NSView coordinates (y=0 at the bottom)
	     * and converted to Tk coordinates later.
  	     */

	    srcRect = CGRectMake(x, y, width, height);
	    dstRect = CGRectOffset(srcRect, dx, dy);


	    /* Compute the damage. */


  	    dmgRgn = HIShapeCreateMutableWithRect(&srcRect);
 	    extraRgn = HIShapeCreateWithRect(&dstRect);
 	    ChkErr(HIShapeDifference, dmgRgn, extraRgn, (HIMutableShapeRef) dmgRgn);

	    result = HIShapeIsEmpty(dmgRgn) ? 0 : 1;


	    /* Convert to Tk coordinates, offset by the window origin. */


	    TkMacOSXSetWithNativeRegion(damageRgn, dmgRgn);
	    if (extraRgn) {
		CFRelease(extraRgn);
	    }


 	    /* Scroll the rectangle. */


 	    [view scrollRect:scrollSrc by:NSMakeSize(dx, -dy)];
  	}
    } else {
	dmgRgn = HIShapeCreateEmpty();
	TkMacOSXSetWithNativeRegion(damageRgn, dmgRgn);
    }

................................................................................
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetUpDrawingContext --
 *
 *	Set up a drawing context for the given drawable and GC.
 *
 * Results:
 *	Boolean indicating whether it is ok to draw; if false, drawing
 *	context was not setup, so do not attempt to draw and do not call
 *	TkMacOSXRestoreDrawingContext().
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Bool
TkMacOSXSetupDrawingContext(
    Drawable d,
    GC gc,
    int useCG, /* advisory only ! */
    TkMacOSXDrawingContext *dcPtr)
{
    MacDrawable *macDraw = ((MacDrawable*)d);
    Bool canDraw = true;
    NSWindow *win = NULL;
    TkMacOSXDrawingContext dc = {};
    CGRect clipBounds;

    /*
     * If the drawable is not a pixmap and it has an associated
     * NSWindow then we know we are drawing to a window.
     */

    if (!(macDraw->flags & TK_IS_PIXMAP)) {
	win = TkMacOSXDrawableWindow(d);
    }

    /*
................................................................................
    ClipToGC(d, gc, &dc.clipRgn);
    if (dc.clipRgn && HIShapeIsEmpty(dc.clipRgn)) {
	canDraw = false;
	goto end;
    }

    /*
     * If we already have a CGContext, use it.  Otherwise, if we
     * are drawing to a window then we can get one from the
     * window.
     */

    dc.context = TkMacOSXGetCGContextForDrawable(d);
    if (dc.context) {
	dc.portBounds = clipBounds = CGContextGetClipBoundingBox(dc.context);
    } else if (win) {
	NSView *view = TkMacOSXDrawableView(macDraw);

	if (view) {




	    /*
	     * We can only draw into the view when the current CGContext is
	     * valid and belongs to the view.  Validity can only be guaranteed
	     * inside of a view's drawRect or setFrame methods.  The isDrawing
	     * attribute tells us whether we are being called from one of those
	     * methods.
	     *
	     * If the CGContext is not valid, or belongs to a different View,
	     * then we mark our view as needing display and return failure.
	     * It should get drawn in a later call to drawRect.
	     */

           if (view != [NSView focusView]) {
	       [view setNeedsDisplay:YES];
	       canDraw = false;
	       goto end;
	   }
	    dc.view = view;
	    dc.context = GET_CGCONTEXT;
	    dc.portBounds = NSRectToCGRect([view bounds]);
	    if (dc.clipRgn) {
		clipBounds = CGContextGetClipBoundingBox(dc.context);
	    }
	} else {
	    Tcl_Panic("TkMacOSXSetupDrawingContext(): "
		    "no NSView to draw into !");
	}
    } else {
	Tcl_Panic("TkMacOSXSetupDrawingContext(): "
		"no context to draw into !");
    }

    /*
     * Configure the drawing context.
     */

    if (dc.context) {
	CGAffineTransform t = { .a = 1, .b = 0, .c = 0, .d = -1, .tx = 0,



		.ty = dc.portBounds.size.height};


	dc.portBounds.origin.x += macDraw->xOff;
	dc.portBounds.origin.y += macDraw->yOff;
	CGContextSaveGState(dc.context);
	CGContextSetTextDrawingMode(dc.context, kCGTextFill);
	CGContextConcatCTM(dc.context, t);
	if (dc.clipRgn) {
#ifdef TK_MAC_DEBUG_DRAWING
................................................................................
	    CGContextSaveGState(dc.context);
	    ChkErr(HIShapeReplacePathInCGContext, dc.clipRgn, dc.context);
	    CGContextSetRGBFillColor(dc.context, 1.0, 0.0, 0.0, 0.1);
	    CGContextEOFillPath(dc.context);
	    CGContextRestoreGState(dc.context);
#endif /* TK_MAC_DEBUG_DRAWING */
	    CGRect r;

	    if (!HIShapeIsRectangular(dc.clipRgn) || !CGRectContainsRect(
		    *HIShapeGetBounds(dc.clipRgn, &r),
		    CGRectApplyAffineTransform(clipBounds, t))) {
		ChkErr(HIShapeReplacePathInCGContext, dc.clipRgn, dc.context);
		CGContextEOClip(dc.context);
	    }
	}
................................................................................
	    double w = gc->line_width;

	    TkMacOSXSetColorInContext(gc, gc->foreground, dc.context);
	    if (win) {
		CGContextSetPatternPhase(dc.context, CGSizeMake(
			dc.portBounds.size.width, dc.portBounds.size.height));
	    }
	    if(gc->function != GXcopy) {
		TkMacOSXDbgMsg("Logical functions other than GXcopy are "
			"not supported for CG drawing!");
	    }


	    /* When should we antialias? */


	    shouldAntialias = !notAA(gc->line_width);
	    if (!shouldAntialias) {

		/* Make non-antialiased CG drawing look more like X11 */


		w -= (gc->line_width ? NON_AA_CG_OFFSET : 0);
	    }
	    CGContextSetShouldAntialias(dc.context, shouldAntialias);
	    CGContextSetLineWidth(dc.context, w);
	    if (gc->line_style != LineSolid) {
		int num = 0;
		char *p = &(gc->dashes);
		CGFloat dashOffset = gc->dash_offset;
		CGFloat lengths[10];

		while (p[num] != '\0' && num < 10) {
		    lengths[num] = p[num];
		    num++;
		}
		CGContextSetLineDash(dc.context, dashOffset, lengths, num);
	    }
	    if ((unsigned)gc->cap_style < sizeof(cgCap)/sizeof(CGLineCap)) {
		CGContextSetLineCap(dc.context,
			cgCap[(unsigned)gc->cap_style]);
	    }
	    if ((unsigned)gc->join_style < sizeof(cgJoin)/sizeof(CGLineJoin)) {
		CGContextSetLineJoin(dc.context,
			cgJoin[(unsigned)gc->join_style]);
	    }
	}
    }

end:
#ifdef TK_MAC_DEBUG_DRAWING
    if (!canDraw && win != NULL) {
	TkWindow *winPtr = TkMacOSXGetTkWindow(win);


	if (winPtr) fprintf(stderr, "Cannot draw in %s - postponing.\n",
			    Tk_PathName(winPtr));

    }
#endif
    if (!canDraw && dc.clipRgn) {
	CFRelease(dc.clipRgn);
	dc.clipRgn = NULL;
    }
    *dcPtr = dc;
................................................................................
    MacDrawable *macDraw = (MacDrawable *) drawable;
    HIShapeRef clipRgn = NULL;

    if (macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(macDraw->winPtr);
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s", macDraw->winPtr->pathName);

	NSView *view = TkMacOSXDrawableView(macDraw);

	CGContextSaveGState(context);
	CGContextConcatCTM(context, CGAffineTransformMake(1.0, 0.0, 0.0,
	      -1.0, 0.0, [view bounds].size.height));
	ChkErr(HIShapeReplacePathInCGContext, macDraw->visRgn, context);
	CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.1);
	CGContextEOFillPath(context);
	CGContextRestoreGState(context);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetUpClippingRgn --
 *
 *	Set up the clipping region so that drawing only occurs on the
 *	specified X subwindow.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpClipDrawableToRect --
 *
 *	Clip all drawing into the drawable d to the given rectangle.
 *	If width or height are negative, reset to no clipping.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Subsequent drawing into d is offset and clipped as specified.
 *
................................................................................
static void
ClipToGC(
    Drawable d,
    GC gc,
    HIShapeRef *clipRgnPtr) /* must point to initialized variable */
{
    if (gc && gc->clip_mask &&
	    ((TkpClipMask*)gc->clip_mask)->type == TKP_CLIP_REGION) {
	TkRegion gcClip = ((TkpClipMask*)gc->clip_mask)->value.region;
	int xOffset = ((MacDrawable *) d)->xOff + gc->clip_x_origin;
	int yOffset = ((MacDrawable *) d)->yOff + gc->clip_y_origin;
	HIShapeRef clipRgn = *clipRgnPtr, gcClipRgn;

	TkMacOSXOffsetRegion(gcClip, xOffset, yOffset);
	gcClipRgn = TkMacOSXGetNativeRegion(gcClip);
	if (clipRgn) {
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXMakeStippleMap --
 *
 *	Given a drawable and a stipple pattern this function draws the
 *	pattern repeatedly over the drawable. The drawable can then
 *	be used as a mask for bit-bliting a stipple pattern over an
 *	object.
 *
 * Results:
 *	A BitMap data structure.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDrawHighlightBorder --
 *
 *	This procedure draws a rectangular ring around the outside of
 *	a widget to indicate that it has received the input focus.
 *
 *	On the Macintosh, this puts a 1 pixel border in the bgGC color
 *	between the widget and the focus ring, except in the case where
 *	highlightWidth is 1, in which case the border is left out.
 *
 *	For proper Mac L&F, use highlightWidth of 3.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A rectangle "width" pixels wide is drawn in "drawable",
 *	corresponding to the outer area of "tkwin".
 *
 *----------------------------------------------------------------------
 */

void
TkpDrawHighlightBorder (
    Tk_Window tkwin,
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDrawFrame --
 *
 *	This procedure draws the rectangular frame area. If the user
 *	has requested themeing, it draws with the background theme.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws inside the tkwin area.
 *



|
|
<







 







|








|







 







|
|
|
|
|
|

|
|



|
|
|

|
|







>
|

|
|
|
|
|



|

|
|
<




<

>
>
|

|



|


|
<






|
|







 







|
<









|


|







 







<

>


|
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
<
<
<
<
<









|
|
|
<







 







>

>


>



>
|

|
>
|
>

>


>
>
|
>
>
>
|

>
>
|
>
>



>
>
|
|
>
>
|
>









>
|


|
>
|


>
|



|
>


>
>
|
>
>
|
>







 







|







 







|







 







|







 







|

|


>
|



|





|
|







 







<
>
|







 







>





>







 







>

|
|
|
<

>







 







|


|







 







|
<












|
|
<



|
|
|
|
<







 







|







 







|







 







|
|
|
<
|
|
|
|







 







<







 







|







 







|
|


|
|
<







 







|





|
>
|
>
>


|
|


>
|
>
>



|


|
|





>
|
>
>


|
>


>
|
>
>





>
|
>
>







 







|
|












|


|






|
|







 







|
|
<







>
|
>
>
|
>
|
|
|
|
|
<
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
<
<
<
<










|
>
>
>
|
>
>







 







>







 







|



>
>
|
>
>


>
|
>
>






|









|

|



|








>
>
|
|
>







 







>

>







 







|
|







 







|
|







 







|
|







 







|
|
|
<







 







|
|

|
|
|







|
|







 







|
|







1
2
3
4
5

6
7
8
9
10
11
12
..
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
...
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
...
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
...
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
...
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
...
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
...
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
...
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
...
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
...
653
654
655
656
657
658
659

660
661
662
663
664
665
666
667
668
...
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
...
761
762
763
764
765
766
767
768
769
770
771
772

773
774
775
776
777
778
779
780
781
...
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
...
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
....
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
....
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
....
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131

1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
....
1147
1148
1149
1150
1151
1152
1153

1154
1155
1156
1157
1158
1159
1160
....
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
....
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393

1394
1395
1396
1397
1398
1399
1400
....
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
....
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
....
1552
1553
1554
1555
1556
1557
1558
1559
1560

1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578

1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595




1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
....
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
....
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
....
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
....
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
....
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
....
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
....
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917

1918
1919
1920
1921
1922
1923
1924
....
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
....
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
/*
 * tkMacOSXDraw.c --
 *
 *	This file contains functions that perform drawing to Xlib windows. Most
 *	of the functions simple emulate Xlib functions.

 *
 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
 * Copyright 2001-2009, Apple Inc.
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2014 Marc Culler.
 *
 * See the file "license.terms" for information on usage and redistribution
................................................................................
/*
#ifdef TK_MAC_DEBUG
#define TK_MAC_DEBUG_DRAWING
#define TK_MAC_DEBUG_IMAGE_DRAWING
#endif
*/

#define radians(d)	((d) * (M_PI/180.0))

/*
 * Non-antialiased CG drawing looks better and more like X11 drawing when using
 * very fine lines, so decrease all linewidths by the following constant.
 */
#define NON_AA_CG_OFFSET .999

static int cgAntiAliasLimit = 0;
#define notAA(w)	((w) < cgAntiAliasLimit)

static int useThemedToplevel = 0;
static int useThemedFrame = 0;

/*
 * Prototypes for functions used only in this file.
 */
................................................................................
 *      implementation does not work correctly.  Originally it relied on
 *      [NSBitmapImageRep initWithFocusedViewRect:view_rect] which was
 *      deprecated by Apple in OSX 10.14 and also required the use of other
 *      deprecated functions such as [NSView lockFocus]. Apple's suggested
 *      replacement is [NSView cacheDisplayInRect: toBitmapImageRep:] and that
 *      is what is being used here.  However, that method only works when the
 *      view has a valid CGContext, and a view is only guaranteed to have a
 *      valid context during a call to [NSView drawRect]. To further complicate
 *      matters, cacheDisplayInRect calls [NSView drawRect]. Essentially it is
 *      asking the view to draw a subrectangle of itself into a special
 *      graphics context which is linked to the BitmapImageRep. But our
 *      implementation of [NSView drawRect] does not allow recursive calls. If
 *      called recursively it returns immediately without doing any drawing.
 *      So the bottom line is that this function either returns a NULL pointer
 *      or a black image. To make it useful would require a significant amount
 *      of rewriting of the drawRect method. Perhaps the next release of OSX
 *      will include some more helpful ways of doing this.
 *
 * Results:
 *	Returns an NSBitmapRep representing the image of the given rectangle of
 *      the given drawable. This object is retained. The caller is responsible
 *      for releasing it.
 *
 *      NOTE: The x,y coordinates should be relative to a coordinate system
 *      with origin at the top left, as used by XImage and CGImage, not bottom
 *      left as used by NSView.
 *
 * Side effects:
 *     None
 *
 *----------------------------------------------------------------------
 */

NSBitmapImageRep *
TkMacOSXBitmapRepFromDrawableRect(
    Drawable drawable,
    int x,
    int y,
    unsigned int width,
    unsigned int height)
{
    MacDrawable *mac_drawable = (MacDrawable *) drawable;
    CGContextRef cg_context = NULL;
    CGImageRef cg_image = NULL, sub_cg_image = NULL;
    NSBitmapImageRep *bitmap_rep = NULL;
    NSView *view = NULL;
    if (mac_drawable->flags & TK_IS_PIXMAP) {

	/*
	 * This MacDrawable is a bitmap, so its view is NULL.
	 */


	CGRect image_rect = CGRectMake(x, y, width, height);

	cg_context = TkMacOSXGetCGContextForDrawable(drawable);
	cg_image = CGBitmapContextCreateImage((CGContextRef) cg_context);
	sub_cg_image = CGImageCreateWithImageInRect(cg_image, image_rect);
	if (sub_cg_image) {
	    bitmap_rep = [NSBitmapImageRep alloc];
	    [bitmap_rep initWithCGImage:sub_cg_image];
	}
	if (cg_image) {
	    CGImageRelease(cg_image);
	}
    } else if ((view = TkMacOSXDrawableView(mac_drawable)) != NULL) {

	/*
	 * Convert Tk top-left to NSView bottom-left coordinates.
	 */

	int view_height = [view bounds].size.height;
	NSRect view_rect = NSMakeRect(x + mac_drawable->xOff,
		view_height - height - y - mac_drawable->yOff,
		width, height);

	/*
	 * Attempt to copy from the view to a bitmapImageRep.  If the view does
	 * not have a valid CGContext, doing this will silently corrupt memory
	 * and make a big mess. So, in that case, we mark the view as needing
	 * display and return NULL.
	 */
................................................................................
 *
 *	Copies data from one drawable to another.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Data is moved from a window or bitmap to a second window or bitmap.

 *
 *----------------------------------------------------------------------
 */

void
XCopyArea(
    Display *display,		/* Display. */
    Drawable src,		/* Source drawable. */
    Drawable dst,		/* Destination drawable. */
    GC gc,			/* GC to use. */
    int src_x,			/* X & Y, width & height */
    int src_y,			/* define the source rectangle */
    unsigned int width,		/* that will be copied. */
    unsigned int height,
    int dest_x,			/* Dest X & Y on dest rect. */
    int dest_y)
{
    TkMacOSXDrawingContext dc;
    MacDrawable *srcDraw = (MacDrawable *) src;
    NSBitmapImageRep *bitmap_rep = NULL;
................................................................................

    display->request++;
    if (!width || !height) {
	return;
    }

    if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) {

	TkMacOSXDbgMsg("Failed to setup drawing context.");
	return;
    }

    if (!dc.context) {
	TkMacOSXDbgMsg("Invalid destination drawable - no context.");
	return;
    }

    if (srcDraw->flags & TK_IS_PIXMAP) {
	img = TkMacOSXCreateCGImageWithDrawable(src);
    } else if (TkMacOSXDrawableWindow(src)) {
	bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(src,
		src_x, src_y, width, height);
	if (bitmap_rep) {
	    img = [bitmap_rep CGImage];
	}
    } else {
	TkMacOSXDbgMsg("Invalid source drawable - neither window nor pixmap.");
    }

    if (img) {
	bounds = CGRectMake(0, 0, srcDraw->size.width, srcDraw->size.height);
	srcRect = CGRectMake(src_x, src_y, width, height);
	dstRect = CGRectMake(dest_x, dest_y, width, height);
	TkMacOSXDrawCGImage(dst, gc, dc.context, img,
		gc->foreground, gc->background, bounds, srcRect, dstRect);
	CFRelease(img);
    } else {
	TkMacOSXDbgMsg("Failed to construct CGImage.");
    }






    TkMacOSXRestoreDrawingContext(&dc);
}
 
/*
 *----------------------------------------------------------------------
 *
 * XCopyPlane --
 *
 *	Copies a bitmap from a source drawable to a destination drawable. The
 *	plane argument specifies which bit plane of the source contains the
 *	bitmap. Note that this implementation ignores the gc->function.

 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Changes the destination drawable.
 *
................................................................................
    if (plane != 1) {
	Tcl_Panic("Unexpected plane specified for XCopyPlane");
    }
    if (srcDraw->flags & TK_IS_PIXMAP) {
	if (!TkMacOSXSetupDrawingContext(dst, gc, 1, &dc)) {
	    return;
	}

	CGContextRef context = dc.context;

	if (context) {
	    CGImageRef img = TkMacOSXCreateCGImageWithDrawable(src);

	    if (img) {
		TkpClipMask *clipPtr = (TkpClipMask *) gc->clip_mask;
		unsigned long imageBackground  = gc->background;

                if (clipPtr && clipPtr->type == TKP_CLIP_PIXMAP) {
		    srcRect = CGRectMake(src_x, src_y, width, height);
		    CGImageRef mask = TkMacOSXCreateCGImageWithDrawable(
			    clipPtr->value.pixmap);
		    CGImageRef submask = CGImageCreateWithImageInRect(
			    img, srcRect);
		    CGRect rect = CGRectMake(dest_x, dest_y, width, height);

		    rect = CGRectOffset(rect, dstDraw->xOff, dstDraw->yOff);
		    CGContextSaveGState(context);

		    /*
		     * Move the origin of the destination to top left.
		     */

		    CGContextTranslateCTM(context,
			    0, rect.origin.y + CGRectGetMaxY(rect));
		    CGContextScaleCTM(context, 1, -1);

		    /*
		     * Fill with the background color, clipping to the mask.
		     */

		    CGContextClipToMask(context, rect, submask);
		    TkMacOSXSetColorInContext(gc, gc->background, dc.context);
		    CGContextFillRect(context, rect);

		    /*
		     * Fill with the foreground color, clipping to the
		     * intersection of img and mask.
		     */

		    CGImageRef subimage = CGImageCreateWithImageInRect(
			    img, srcRect);
		    CGContextClipToMask(context, rect, subimage);
		    TkMacOSXSetColorInContext(gc, gc->foreground, context);
		    CGContextFillRect(context, rect);
		    CGContextRestoreGState(context);
		    CGImageRelease(img);
		    CGImageRelease(mask);
		    CGImageRelease(submask);
		    CGImageRelease(subimage);
		} else {
		    bounds = CGRectMake(0, 0,
			    srcDraw->size.width, srcDraw->size.height);
		    srcRect = CGRectMake(src_x, src_y, width, height);
		    dstRect = CGRectMake(dest_x, dest_y, width, height);
		    TkMacOSXDrawCGImage(dst, gc, dc.context, img,
			    gc->foreground, imageBackground, bounds,
			    srcRect, dstRect);
		    CGImageRelease(img);
		}
	    } else {
		/* no image */
		TkMacOSXDbgMsg("Invalid source drawable");
	    }
	} else {
	    TkMacOSXDbgMsg("Invalid destination drawable - "
		    "could not get a bitmap context.");
	}
	TkMacOSXRestoreDrawingContext(&dc);
    } else {
	/*
	 * Source drawable is a Window, not a Pixmap.
	 */

	XCopyArea(display, src, dst, gc, src_x, src_y, width, height,
		dest_x, dest_y);
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXCreateCGImageWithDrawable --
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static NSImage *
CreateNSImageWithPixmap(
    Pixmap pixmap,
    int width,
    int height)
{
    CGImageRef cgImage;
    NSImage *nsImage;
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSImage *
TkMacOSXGetNSImageWithTkImage(
    Display *display,
    Tk_Image image,
    int width,
    int height)
{
    Pixmap pixmap = Tk_GetPixmap(display, None, width, height, 0);
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSImage *
TkMacOSXGetNSImageWithBitmap(
    Display *display,
    Pixmap bitmap,
    GC gc,
    int width,
    int height)
{
................................................................................

    if (macDraw && (macDraw->flags & TK_IS_PIXMAP) && !macDraw->context) {
	const size_t bitsPerComponent = 8;
	size_t bitsPerPixel, bytesPerRow, len;
	CGColorSpaceRef colorspace = NULL;
	CGBitmapInfo bitmapInfo =
#ifdef __LITTLE_ENDIAN__
		kCGBitmapByteOrder32Host;
#else
		kCGBitmapByteOrderDefault;
#endif
	char *data;
	CGRect bounds = CGRectMake(0, 0,
		macDraw->size.width, macDraw->size.height);

	if (macDraw->flags & TK_IS_BW_PIXMAP) {
	    bitsPerPixel = 8;
	    bitmapInfo = (CGBitmapInfo) kCGImageAlphaOnly;
	} else {
	    colorspace = CGColorSpaceCreateDeviceRGB();
	    bitsPerPixel = 32;
	    bitmapInfo |= kCGImageAlphaPremultipliedFirst;
	}
	bytesPerRow = ((size_t)
		macDraw->size.width * bitsPerPixel + 127) >> 3 & ~15;
	len = macDraw->size.height * bytesPerRow;
	data = ckalloc(len);
	bzero(data, len);
	macDraw->context = CGBitmapContextCreate(data, macDraw->size.width,
		macDraw->size.height, bitsPerComponent, bytesPerRow,
		colorspace, bitmapInfo);
	if (macDraw->context) {
................................................................................
	    if (subImage) {
		image = subImage;
	    }
	}
	dstBounds = CGRectOffset(dstBounds, macDraw->xOff, macDraw->yOff);
	if (CGImageIsMask(image)) {
	    if (macDraw->flags & TK_IS_BW_PIXMAP) {

		/*
		 * Set fill color to black; background comes from the context,
		 * or is transparent.
		 */

		if (imageBackground != TRANSPARENT_PIXEL << 24) {
		    CGContextClearRect(context, dstBounds);
		}
		CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
................................................................................
#ifdef TK_MAC_DEBUG_IMAGE_DRAWING
	CGContextSaveGState(context);
	CGContextSetLineWidth(context, 1.0);
	CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.1);
	CGContextSetRGBFillColor(context, 0, 1, 0, 0.1);
	CGContextFillRect(context, dstBounds);
	CGContextStrokeRect(context, dstBounds);

	CGPoint p[4] = {dstBounds.origin,
	    CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMaxY(dstBounds)),
	    CGPointMake(CGRectGetMinX(dstBounds), CGRectGetMaxY(dstBounds)),
	    CGPointMake(CGRectGetMaxX(dstBounds), CGRectGetMinY(dstBounds))
	};

	CGContextStrokeLineSegments(context, p, 4);
	CGContextRestoreGState(context);
	TkMacOSXDbgMsg("Drawing CGImage at (x=%f, y=%f), (w=%f, h=%f)",
		dstBounds.origin.x, dstBounds.origin.y,
		dstBounds.size.width, dstBounds.size.height);
#else /* TK_MAC_DEBUG_IMAGE_DRAWING */
	CGContextSaveGState(context);
................................................................................
			macWin->yOff + points[i].y + o);
	    } else {
		prevx += points[i].x;
		prevy += points[i].y;
		CGContextAddLineToPoint(dc.context, prevx, prevy);
	    }
	}

        /*
         * In the case of closed polylines, the first and last points are the
         * same. We want miter or bevel join be rendered also at this point,
         * this needs telling CoreGraphics that the path is closed.

         */

        if ((points[0].x == points[npoints-1].x) &&
                (points[0].y == points[npoints-1].y)) {
            CGContextClosePath(dc.context);
        }
	CGContextStrokePath(dc.context);
    }
    TkMacOSXRestoreDrawingContext(&dc);
................................................................................
 *	Draws a filled polygon on the specified drawable.
 *
 *----------------------------------------------------------------------
 */

void
XFillPolygon(
    Display *display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    XPoint *points,		/* Array of points. */
    int npoints,		/* Number of points. */
    int shape,			/* Shape to draw. */
    int mode)			/* Drawing mode. */
{
    MacDrawable *macWin = (MacDrawable *) d;
    TkMacOSXDrawingContext dc;
    int i;
................................................................................
	return;
    }
    if (dc.context) {
	CGRect rect;
	double o = (lw % 2) ? .5 : 0;

	rect = CGRectMake(
		macWin->xOff + x + o, macWin->yOff + y + o,

		width, height);
	CGContextStrokeRect(dc.context, rect);
    }
    TkMacOSXRestoreDrawingContext(&dc);
}
 
#ifdef TK_MACOSXDRAW_UNUSED
/*
 *----------------------------------------------------------------------
 *
 * XDrawRectangles --
 *
 *	Draws the outlines of the specified rectangles as if a five-point
 *	PolyLine protocol request were specified for each rectangle:

 *
 *	    [x,y] [x+width,y] [x+width,y+height] [x,y+height] [x,y]
 *
 *	For the specified rectangles, these functions do not draw a pixel more
 *	than once. XDrawRectangles draws the rectangles in the order listed in
 *	the array. If rectangles intersect, the intersecting pixels are drawn
 *	multiple times. Draws a rectangle.

 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws rectangles on the specified drawable.
 *
................................................................................
 *	Draws onto the specified drawable.
 *
 *----------------------------------------------------------------------
 */

int
XFillRectangles(
    Display *display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    XRectangle *rectangles,	/* Rectangle array. */
    int n_rectangles)		/* Number of rectangles. */
{
    MacDrawable *macWin = (MacDrawable *) d;
    TkMacOSXDrawingContext dc;
................................................................................
 *	Draws an arc on the specified drawable.
 *
 *----------------------------------------------------------------------
 */

void
XDrawArc(
    Display *display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    int x, int y,		/* Upper left of bounding rect. */
    unsigned int width,		/* Width & height. */
    unsigned int height,
    int angle1,			/* Staring angle of arc. */
    int angle2)			/* Extent of arc. */
................................................................................
 
#ifdef TK_MACOSXDRAW_UNUSED
/*
 *----------------------------------------------------------------------
 *
 * XDrawArcs --
 *
 *	Draws multiple circular or elliptical arcs. Each arc is specified by a
 *	rectangle and two angles. The center of the circle or ellipse is the
 *	center of the rect- angle, and the major and minor axes are specified

 *	by the width and height.  Positive angles indicate counterclock- wise
 *	motion, and negative angles indicate clockwise motion. If the magnitude
 *	of angle2 is greater than 360 degrees, XDrawArcs truncates it to 360
 *	degrees.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws an arc for each array element on the specified drawable.
 *
................................................................................
XDrawArcs(
    Display *display,
    Drawable d,
    GC gc,
    XArc *arcArr,
    int nArcs)
{

    MacDrawable *macWin = (MacDrawable *) d;
    TkMacOSXDrawingContext dc;
    XArc *arcPtr;
    int i, lw = gc->line_width;

    display->request++;
    if (!TkMacOSXSetupDrawingContext(d, gc, 1, &dc)) {
................................................................................
 *	Draws a filled arc on the specified drawable.
 *
 *----------------------------------------------------------------------
 */

void
XFillArc(
    Display *display,		/* Display. */
    Drawable d,			/* Draw on this. */
    GC gc,			/* Use this GC. */
    int x, int y,		/* Upper left of bounding rect. */
    unsigned int width,		/* Width & height. */
    unsigned int height,
    int angle1,			/* Staring angle of arc. */
    int angle2)			/* Extent of arc. */
................................................................................
#endif
 
/*
 *----------------------------------------------------------------------
 *
 * TkScrollWindow --
 *
 *	Scroll a rectangle of the specified window and accumulate a damage
 *	region.
 *
 * Results:
 *	Returns 0 if the scroll generated no additional damage. Otherwise, sets
 *	the region that needs to be repainted after scrolling and returns 1.

 *
 * Side effects:
 *	Scrolls the bits in the window.
 *
 *----------------------------------------------------------------------
 */

................................................................................
    int x, int y,		/* Position rectangle to be scrolled. */
    int width, int height,
    int dx, int dy,		/* Distance rectangle should be moved. */
    TkRegion damageRgn)		/* Region to accumulate damage in. */
{
    Drawable drawable = Tk_WindowId(tkwin);
    MacDrawable *macDraw = (MacDrawable *) drawable;
    TKContentView *view = (TKContentView *) TkMacOSXDrawableView(macDraw);
    CGRect srcRect, dstRect;
    HIShapeRef dmgRgn = NULL, extraRgn = NULL;
    NSRect bounds, visRect, scrollSrc, scrollDst;
    int result = 0;

    if (view) {
  	/*
	 * Get the scroll area in NSView coordinates (origin at bottom left).
	 */

  	bounds = [view bounds];
 	scrollSrc = NSMakeRect(macDraw->xOff + x,
		bounds.size.height - height - (macDraw->yOff + y),
		width, height);
 	scrollDst = NSOffsetRect(scrollSrc, dx, -dy);

  	/*
	 * Limit scrolling to the window content area.
	 */

 	visRect = [view visibleRect];
 	scrollSrc = NSIntersectionRect(scrollSrc, visRect);
 	scrollDst = NSIntersectionRect(scrollDst, visRect);
 	if (!NSIsEmptyRect(scrollSrc) && !NSIsEmptyRect(scrollDst)) {
  	    /*
  	     * Mark the difference between source and destination as damaged.
	     * This region is described in NSView coordinates (y=0 at the
	     * bottom) and converted to Tk coordinates later.
  	     */

	    srcRect = CGRectMake(x, y, width, height);
	    dstRect = CGRectOffset(srcRect, dx, dy);

	    /*
	     * Compute the damage.
	     */

  	    dmgRgn = HIShapeCreateMutableWithRect(&srcRect);
 	    extraRgn = HIShapeCreateWithRect(&dstRect);
 	    ChkErr(HIShapeDifference, dmgRgn, extraRgn,
		    (HIMutableShapeRef) dmgRgn);
	    result = HIShapeIsEmpty(dmgRgn) ? 0 : 1;

	    /*
	     * Convert to Tk coordinates, offset by the window origin.
	     */

	    TkMacOSXSetWithNativeRegion(damageRgn, dmgRgn);
	    if (extraRgn) {
		CFRelease(extraRgn);
	    }

 	    /*
	     * Scroll the rectangle.
	     */

 	    [view scrollRect:scrollSrc by:NSMakeSize(dx, -dy)];
  	}
    } else {
	dmgRgn = HIShapeCreateEmpty();
	TkMacOSXSetWithNativeRegion(damageRgn, dmgRgn);
    }

................................................................................
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetUpDrawingContext --
 *
 *	Set up a drawing context for the given drawable and GC.
 *
 * Results:
 *	Boolean indicating whether it is ok to draw; if false, drawing context
 *	was not setup, so do not attempt to draw and do not call
 *	TkMacOSXRestoreDrawingContext().
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Bool
TkMacOSXSetupDrawingContext(
    Drawable d,
    GC gc,
    int useCG,			/* advisory only ! */
    TkMacOSXDrawingContext *dcPtr)
{
    MacDrawable *macDraw = (MacDrawable *) d;
    Bool canDraw = true;
    NSWindow *win = NULL;
    TkMacOSXDrawingContext dc = {};
    CGRect clipBounds;

    /*
     * If the drawable is not a pixmap and it has an associated NSWindow then
     * we know we are drawing to a window.
     */

    if (!(macDraw->flags & TK_IS_PIXMAP)) {
	win = TkMacOSXDrawableWindow(d);
    }

    /*
................................................................................
    ClipToGC(d, gc, &dc.clipRgn);
    if (dc.clipRgn && HIShapeIsEmpty(dc.clipRgn)) {
	canDraw = false;
	goto end;
    }

    /*
     * If we already have a CGContext, use it.  Otherwise, if we are drawing to
     * a window then we can get one from the window.

     */

    dc.context = TkMacOSXGetCGContextForDrawable(d);
    if (dc.context) {
	dc.portBounds = clipBounds = CGContextGetClipBoundingBox(dc.context);
    } else if (win) {
	NSView *view = TkMacOSXDrawableView(macDraw);

	if (!view) {
	    Tcl_Panic("TkMacOSXSetupDrawingContext(): "
		    "no NSView to draw into !");
	}

	/*
	 * We can only draw into the view when the current CGContext is valid
	 * and belongs to the view.  Validity can only be guaranteed inside of
	 * a view's drawRect or setFrame methods.  The isDrawing attribute
	 * tells us whether we are being called from one of those methods.

	 *
	 * If the CGContext is not valid, or belongs to a different View, then
	 * we mark our view as needing display and return failure. It should
	 * get drawn in a later call to drawRect.
	 */

	if (view != [NSView focusView]) {
	    [view setNeedsDisplay:YES];
	    canDraw = false;
	    goto end;
	}
	dc.view = view;
	dc.context = GET_CGCONTEXT;
	dc.portBounds = NSRectToCGRect([view bounds]);
	if (dc.clipRgn) {
	    clipBounds = CGContextGetClipBoundingBox(dc.context);
	}




    } else {
	Tcl_Panic("TkMacOSXSetupDrawingContext(): "
		"no context to draw into !");
    }

    /*
     * Configure the drawing context.
     */

    if (dc.context) {
	CGAffineTransform t = {
	    .a = 1, .b = 0,
	    .c = 0, .d = -1,
	    .tx = 0,
	    .ty = dc.portBounds.size.height
	};

	dc.portBounds.origin.x += macDraw->xOff;
	dc.portBounds.origin.y += macDraw->yOff;
	CGContextSaveGState(dc.context);
	CGContextSetTextDrawingMode(dc.context, kCGTextFill);
	CGContextConcatCTM(dc.context, t);
	if (dc.clipRgn) {
#ifdef TK_MAC_DEBUG_DRAWING
................................................................................
	    CGContextSaveGState(dc.context);
	    ChkErr(HIShapeReplacePathInCGContext, dc.clipRgn, dc.context);
	    CGContextSetRGBFillColor(dc.context, 1.0, 0.0, 0.0, 0.1);
	    CGContextEOFillPath(dc.context);
	    CGContextRestoreGState(dc.context);
#endif /* TK_MAC_DEBUG_DRAWING */
	    CGRect r;

	    if (!HIShapeIsRectangular(dc.clipRgn) || !CGRectContainsRect(
		    *HIShapeGetBounds(dc.clipRgn, &r),
		    CGRectApplyAffineTransform(clipBounds, t))) {
		ChkErr(HIShapeReplacePathInCGContext, dc.clipRgn, dc.context);
		CGContextEOClip(dc.context);
	    }
	}
................................................................................
	    double w = gc->line_width;

	    TkMacOSXSetColorInContext(gc, gc->foreground, dc.context);
	    if (win) {
		CGContextSetPatternPhase(dc.context, CGSizeMake(
			dc.portBounds.size.width, dc.portBounds.size.height));
	    }
	    if (gc->function != GXcopy) {
		TkMacOSXDbgMsg("Logical functions other than GXcopy are "
			"not supported for CG drawing!");
	    }

	    /*
	     * When should we antialias?
	     */

	    shouldAntialias = !notAA(gc->line_width);
	    if (!shouldAntialias) {
		/*
		 * Make non-antialiased CG drawing look more like X11.
		 */

		w -= (gc->line_width ? NON_AA_CG_OFFSET : 0);
	    }
	    CGContextSetShouldAntialias(dc.context, shouldAntialias);
	    CGContextSetLineWidth(dc.context, w);
	    if (gc->line_style != LineSolid) {
		int num = 0;
		char *p = &gc->dashes;
		CGFloat dashOffset = gc->dash_offset;
		CGFloat lengths[10];

		while (p[num] != '\0' && num < 10) {
		    lengths[num] = p[num];
		    num++;
		}
		CGContextSetLineDash(dc.context, dashOffset, lengths, num);
	    }
	    if ((unsigned) gc->cap_style < sizeof(cgCap)/sizeof(CGLineCap)) {
		CGContextSetLineCap(dc.context,
			cgCap[(unsigned) gc->cap_style]);
	    }
	    if ((unsigned)gc->join_style < sizeof(cgJoin)/sizeof(CGLineJoin)) {
		CGContextSetLineJoin(dc.context,
			cgJoin[(unsigned) gc->join_style]);
	    }
	}
    }

end:
#ifdef TK_MAC_DEBUG_DRAWING
    if (!canDraw && win != NULL) {
	TkWindow *winPtr = TkMacOSXGetTkWindow(win);

	if (winPtr) {
	    fprintf(stderr, "Cannot draw in %s - postponing.\n",
		    Tk_PathName(winPtr));
	}
    }
#endif
    if (!canDraw && dc.clipRgn) {
	CFRelease(dc.clipRgn);
	dc.clipRgn = NULL;
    }
    *dcPtr = dc;
................................................................................
    MacDrawable *macDraw = (MacDrawable *) drawable;
    HIShapeRef clipRgn = NULL;

    if (macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(macDraw->winPtr);
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s", macDraw->winPtr->pathName);

	NSView *view = TkMacOSXDrawableView(macDraw);

	CGContextSaveGState(context);
	CGContextConcatCTM(context, CGAffineTransformMake(1.0, 0.0, 0.0,
	      -1.0, 0.0, [view bounds].size.height));
	ChkErr(HIShapeReplacePathInCGContext, macDraw->visRgn, context);
	CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.1);
	CGContextEOFillPath(context);
	CGContextRestoreGState(context);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetUpClippingRgn --
 *
 *	Set up the clipping region so that drawing only occurs on the specified
 *	X subwindow.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpClipDrawableToRect --
 *
 *	Clip all drawing into the drawable d to the given rectangle. If width
 *	or height are negative, reset to no clipping.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Subsequent drawing into d is offset and clipped as specified.
 *
................................................................................
static void
ClipToGC(
    Drawable d,
    GC gc,
    HIShapeRef *clipRgnPtr) /* must point to initialized variable */
{
    if (gc && gc->clip_mask &&
	    ((TkpClipMask *) gc->clip_mask)->type == TKP_CLIP_REGION) {
	TkRegion gcClip = ((TkpClipMask *) gc->clip_mask)->value.region;
	int xOffset = ((MacDrawable *) d)->xOff + gc->clip_x_origin;
	int yOffset = ((MacDrawable *) d)->yOff + gc->clip_y_origin;
	HIShapeRef clipRgn = *clipRgnPtr, gcClipRgn;

	TkMacOSXOffsetRegion(gcClip, xOffset, yOffset);
	gcClipRgn = TkMacOSXGetNativeRegion(gcClip);
	if (clipRgn) {
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXMakeStippleMap --
 *
 *	Given a drawable and a stipple pattern this function draws the pattern
 *	repeatedly over the drawable. The drawable can then be used as a mask
 *	for bit-bliting a stipple pattern over an object.

 *
 * Results:
 *	A BitMap data structure.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDrawHighlightBorder --
 *
 *	This procedure draws a rectangular ring around the outside of a widget
 *	to indicate that it has received the input focus.
 *
 *	On the Macintosh, this puts a 1 pixel border in the bgGC color between
 *	the widget and the focus ring, except in the case where highlightWidth
 *	is 1, in which case the border is left out.
 *
 *	For proper Mac L&F, use highlightWidth of 3.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A rectangle "width" pixels wide is drawn in "drawable", corresponding
 *	to the outer area of "tkwin".
 *
 *----------------------------------------------------------------------
 */

void
TkpDrawHighlightBorder (
    Tk_Window tkwin,
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDrawFrame --
 *
 *	This procedure draws the rectangular frame area. If the user has
 *	requested themeing, it draws with the background theme.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws inside the tkwin area.
 *

Changes to macosx/tkMacOSXEmbed.c.

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
...
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
...
764
765
766
767
768
769
770

771
772
773
774
775
776
777
...
916
917
918
919
920
921
922

923
924
925
926
927
928
929
....
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
....
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
....
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
    /*
     * Make a copy of the TK_EMBEDDED flag, since sometimes we need this to
     * get the port after the TkWindow structure has been freed.
     */

    macWin->flags |= TK_EMBEDDED;
    macWin->xOff = parent->winPtr->privatePtr->xOff +
	parent->winPtr->changes.border_width +
	winPtr->changes.x;
    macWin->yOff = parent->winPtr->privatePtr->yOff +
	parent->winPtr->changes.border_width +
	winPtr->changes.y;

    /*
     * Finish filling up the container structure with the embedded
     * window's information.
     */

    containerPtr->embedded = (Window) macWin;
    containerPtr->embeddedPtr = macWin->winPtr;

    /*
     * Create an event handler to clean up the Container structure when
     * tkwin is eventually deleted.
     */

    Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedEventProc,
			  winPtr);

    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
	if (containerPtr->parentPtr != NULL) {
	    parentInterp = containerPtr->parentPtr->mainPtr->interp;
	}
	if (embeddedInterp != interp && parentInterp != interp) {
	    continue;
	}
	Tcl_DStringStartSublist(&dString);


	/* Parent id */


	if (containerPtr->parent == None) {
	    Tcl_DStringAppendElement(&dString, "");
	} else if (all) {
	    sprintf(buffer, "0x%" TCL_Z_MODIFIER "x", (size_t) containerPtr->parent);

	    Tcl_DStringAppendElement(&dString, buffer);
	} else {
	    Tcl_DStringAppendElement(&dString, "XXX");
	}


	/* Parent pathName */


	if (containerPtr->parentPtr == NULL ||
	    parentInterp != interp) {
	    Tcl_DStringAppendElement(&dString, "");
	} else {
	    Tcl_DStringAppendElement(&dString,
		    containerPtr->parentPtr->pathName);
	}

	/*
	 * On X11 embedded is a wrapper, which does not exist on macOS.
	 */

	Tcl_DStringAppendElement(&dString, "");


	/* Embedded window pathName */


	if (containerPtr->embeddedPtr == NULL ||
	    embeddedInterp != interp) {
	    Tcl_DStringAppendElement(&dString, "");
	} else {
	    Tcl_DStringAppendElement(&dString,
		    containerPtr->embeddedPtr->pathName);
	}
................................................................................
    Container *containerPtr;
    Tk_ErrorHandler errHandler;

    if (!firstContainerPtr) {
	/*
	 * When the interpreter is being dismantled this can be nil.
	 */

	return;
    }

    /*
     * Ignore any X protocol errors that happen in this procedure (almost any
     * operation could fail, for example, if the embedded application has
     * deleted its window).
................................................................................

static void
EmbedActivateProc(
    ClientData clientData,	/* Token for container window. */
    XEvent *eventPtr)		/* ResizeRequest event. */
{
    Container *containerPtr = clientData;

    if (containerPtr->embeddedPtr != NULL) {
	if (eventPtr->type == ActivateNotify) {
	    TkGenerateActivateEvents(containerPtr->embeddedPtr,1);
	} else if (eventPtr->type == DeactivateNotify) {
	    TkGenerateActivateEvents(containerPtr->embeddedPtr,0);
	}
    }
................................................................................
    int width, int height)	/* Size that the child has requested. */
{
    TkWindow *winPtr = containerPtr->parentPtr;

    /*
     * Forward the requested size into our geometry management hierarchy via
     * the container window. We need to send a Configure event back to the
     * embedded application if we decide not to honor its request; to make
     * this happen, process all idle event handlers synchronously here (so
     * that the geometry managers have had a chance to do whatever they want
     * to do), and if the window's size didn't change then generate a
     * configure event.
     */

    Tk_GeometryRequest((Tk_Window) winPtr, width, height);
    while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) {
	/* Empty loop body. */
    }
    if ((winPtr->changes.width != width)
................................................................................
 *
 * EmbedSendConfigure --
 *
 *	This is currently a stub. It is called to notify an embedded
 *	application of its current size and location. This procedure is called
 *	when the embedded application made a geometry request that we did not
 *	grant, so that the embedded application knows that its geometry didn't
 *	change after all. It is a response to ConfigureRequest events, which
 *	we do not currently synthesize on the Mac
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
	     * Fabricate an event to do this.
	     */

	    if (containerPtr->parentPtr != NULL &&
		    containerPtr->parentPtr->flags & TK_BOTH_HALVES) {
		XEvent event;

		event.xany.serial =
			LastKnownRequestProcessed(Tk_Display(containerPtr->parentPtr));
		event.xany.send_event = False;
		event.xany.display = Tk_Display(containerPtr->parentPtr);

		event.xany.type = DestroyNotify;
		event.xany.window = containerPtr->parent;
		event.xdestroywindow.event = containerPtr->parent;
		Tk_QueueWindowEvent(&event, TCL_QUEUE_HEAD);







|
|

|
|


|
|










|
|







 







>
>
|
>
>



|
>




>
>
|
>
>







>



>

>
>
|
>
>







 







>







 







>







 







|
|
|
|
<







 







|
|







 







|
|







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
...
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
...
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
...
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
....
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047

1048
1049
1050
1051
1052
1053
1054
....
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
....
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
    /*
     * Make a copy of the TK_EMBEDDED flag, since sometimes we need this to
     * get the port after the TkWindow structure has been freed.
     */

    macWin->flags |= TK_EMBEDDED;
    macWin->xOff = parent->winPtr->privatePtr->xOff +
	    parent->winPtr->changes.border_width +
	    winPtr->changes.x;
    macWin->yOff = parent->winPtr->privatePtr->yOff +
	    parent->winPtr->changes.border_width +
	    winPtr->changes.y;

    /*
     * Finish filling up the container structure with the embedded window's
     * information.
     */

    containerPtr->embedded = (Window) macWin;
    containerPtr->embeddedPtr = macWin->winPtr;

    /*
     * Create an event handler to clean up the Container structure when
     * tkwin is eventually deleted.
     */

    Tk_CreateEventHandler(tkwin, StructureNotifyMask,
	    EmbeddedEventProc, winPtr);

    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
	if (containerPtr->parentPtr != NULL) {
	    parentInterp = containerPtr->parentPtr->mainPtr->interp;
	}
	if (embeddedInterp != interp && parentInterp != interp) {
	    continue;
	}
	Tcl_DStringStartSublist(&dString);

	/*
	 * Parent id
	 */

	if (containerPtr->parent == None) {
	    Tcl_DStringAppendElement(&dString, "");
	} else if (all) {
	    sprintf(buffer, "0x%" TCL_Z_MODIFIER "x",
		    (size_t) containerPtr->parent);
	    Tcl_DStringAppendElement(&dString, buffer);
	} else {
	    Tcl_DStringAppendElement(&dString, "XXX");
	}

	/*
	 * Parent pathName
	 */

	if (containerPtr->parentPtr == NULL ||
	    parentInterp != interp) {
	    Tcl_DStringAppendElement(&dString, "");
	} else {
	    Tcl_DStringAppendElement(&dString,
		    containerPtr->parentPtr->pathName);
	}

	/*
	 * On X11 embedded is a wrapper, which does not exist on macOS.
	 */

	Tcl_DStringAppendElement(&dString, "");

	/*
	 * Embedded window pathName
	 */

	if (containerPtr->embeddedPtr == NULL ||
	    embeddedInterp != interp) {
	    Tcl_DStringAppendElement(&dString, "");
	} else {
	    Tcl_DStringAppendElement(&dString,
		    containerPtr->embeddedPtr->pathName);
	}
................................................................................
    Container *containerPtr;
    Tk_ErrorHandler errHandler;

    if (!firstContainerPtr) {
	/*
	 * When the interpreter is being dismantled this can be nil.
	 */

	return;
    }

    /*
     * Ignore any X protocol errors that happen in this procedure (almost any
     * operation could fail, for example, if the embedded application has
     * deleted its window).
................................................................................

static void
EmbedActivateProc(
    ClientData clientData,	/* Token for container window. */
    XEvent *eventPtr)		/* ResizeRequest event. */
{
    Container *containerPtr = clientData;

    if (containerPtr->embeddedPtr != NULL) {
	if (eventPtr->type == ActivateNotify) {
	    TkGenerateActivateEvents(containerPtr->embeddedPtr,1);
	} else if (eventPtr->type == DeactivateNotify) {
	    TkGenerateActivateEvents(containerPtr->embeddedPtr,0);
	}
    }
................................................................................
    int width, int height)	/* Size that the child has requested. */
{
    TkWindow *winPtr = containerPtr->parentPtr;

    /*
     * Forward the requested size into our geometry management hierarchy via
     * the container window. We need to send a Configure event back to the
     * embedded application if we decide not to honor its request; to make this
     * happen, process all idle event handlers synchronously here (so that the
     * geometry managers have had a chance to do whatever they want to do), and
     * if the window's size didn't change then generate a configure event.

     */

    Tk_GeometryRequest((Tk_Window) winPtr, width, height);
    while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) {
	/* Empty loop body. */
    }
    if ((winPtr->changes.width != width)
................................................................................
 *
 * EmbedSendConfigure --
 *
 *	This is currently a stub. It is called to notify an embedded
 *	application of its current size and location. This procedure is called
 *	when the embedded application made a geometry request that we did not
 *	grant, so that the embedded application knows that its geometry didn't
 *	change after all. It is a response to ConfigureRequest events, which we
 *	do not currently synthesize on the Mac
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
	     * Fabricate an event to do this.
	     */

	    if (containerPtr->parentPtr != NULL &&
		    containerPtr->parentPtr->flags & TK_BOTH_HALVES) {
		XEvent event;

		event.xany.serial = LastKnownRequestProcessed(
			Tk_Display(containerPtr->parentPtr));
		event.xany.send_event = False;
		event.xany.display = Tk_Display(containerPtr->parentPtr);

		event.xany.type = DestroyNotify;
		event.xany.window = containerPtr->parent;
		event.xdestroywindow.event = containerPtr->parent;
		Tk_QueueWindowEvent(&event, TCL_QUEUE_HEAD);

Changes to macosx/tkMacOSXFont.c.

1
2
3
4
5
6
7
8
9
10
11
12
..
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
..
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
...
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
...
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
...
354
355
356
357
358
359
360

361

362
363

364

365
366
367
368
369
370
371
...
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
...
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
...
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
...
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
...
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
...
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
...
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
...
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
...
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
...
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
...
899
900
901
902
903
904
905

906
907
908


909
910
911
912
913
914
915
...
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
...
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
...
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
....
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
....
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
....
1087
1088
1089
1090
1091
1092
1093

1094
1095
1096
1097
1098
1099
1100
....
1115
1116
1117
1118
1119
1120
1121

1122
1123
1124
1125
1126
1127
1128
....
1237
1238
1239
1240
1241
1242
1243

1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
....
1263
1264
1265
1266
1267
1268
1269
1270
1271

1272
1273
1274
1275
1276
1277
1278
/*
 * tkMacOSXFont.c --
 *
 *	Contains the Macintosh implementation of the platform-independant
 *	font package interface.
 *
 * Copyright 2002-2004 Benjamin Riefenstahl, Benjamin.Riefenstahl@epost.de
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2008-2009, Apple Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
................................................................................

/*
 * The following structure represents our Macintosh-specific implementation
 * of a font object.
 */

typedef struct {
    TkFont font;		/* Stuff used by generic font package. Must
				 * be first in structure. */

    NSFont *nsFont;
    NSDictionary *nsAttributes;
} MacFont;

/*
 * The names for our "native" fonts.
 */
................................................................................
};
#undef ThemeFont

static int antialiasedTextEnabled = -1;
static NSCharacterSet *whitespaceCharacterSet = nil;
static NSCharacterSet *lineendingCharacterSet = nil;

static void GetTkFontAttributesForNSFont(NSFont *nsFont,
	TkFontAttributes *faPtr);
static NSFont *FindNSFont(const char *familyName, NSFontTraitMask traits,

	NSInteger weight, CGFloat size, int fallbackToDefault);

static void InitFont(NSFont *nsFont, const TkFontAttributes *reqFaPtr,
	MacFont * fontPtr);
static int CreateNamedSystemFont(Tcl_Interp *interp, Tk_Window tkwin,

	const char* name, TkFontAttributes *faPtr);
static void DrawCharsInContext(Display *display, Drawable drawable, GC gc,
	Tk_Font tkfont, const char *source, int numBytes, int rangeStart,

	int rangeLength, int x, int y, double angle);

#pragma mark -
#pragma mark Font Helpers:

#define GetNSFontTraitsFromTkFontAttributes(faPtr) \
	((faPtr)->weight == TK_FW_BOLD ? NSBoldFontMask : NSUnboldFontMask) | \
	((faPtr)->slant == TK_FS_ITALIC ? NSItalicFontMask : NSUnitalicFontMask)
................................................................................
    NSDictionary *nsAttributes;
    NSRect bounds;
    CGFloat kern = 0.0;
    NSFontRenderingMode renderingMode = NSFontDefaultRenderingMode;
    int ascent, descent/*, dontAA*/;
    static const UniChar ch[] = {'.', 'W', ' ', 0xc4, 0xc1, 0xc2, 0xc3, 0xc7};
			/* ., W, Space, Auml, Aacute, Acirc, Atilde, Ccedilla */
    #define nCh (sizeof(ch) / sizeof(UniChar))
    CGGlyph glyphs[nCh];
    CGRect boundingRects[nCh];

    fontPtr->font.fid = (Font) fontPtr;
    faPtr = &fontPtr->font.fa;
    if (reqFaPtr) {
	*faPtr = *reqFaPtr;
    } else {
	TkInitFontAttributes(faPtr);
    }
    fontPtr->nsFont = nsFont;


    // some don't like antialiasing on fixed-width even if bigger than limit


    // dontAA = [nsFont isFixedPitch] && fontPtr->font.fa.size <= 10;
    if (antialiasedTextEnabled >= 0/* || dontAA*/) {
	renderingMode = (antialiasedTextEnabled == 0/* || dontAA*/) ?
		NSFontIntegerAdvancementsRenderingMode :
		NSFontAntialiasedRenderingMode;
    }
    nsFont = [nsFont screenFontWithRenderingMode:renderingMode];
................................................................................
	    [NSNumber numberWithInt:faPtr->overstrike ?
		NSUnderlineStyleSingle|NSUnderlinePatternSolid :
		NSUnderlineStyleNone], NSStrikethroughStyleAttributeName,
	    [NSNumber numberWithInt:fmPtr->fixed ? 0 : 1],
		NSLigatureAttributeName,
	    [NSNumber numberWithDouble:kern], NSKernAttributeName, nil];
    fontPtr->nsAttributes = [nsAttributes retain];
    #undef nCh
}
 
/*
 *-------------------------------------------------------------------------
 *
 * CreateNamedSystemFont --
 *
................................................................................
{
    Tcl_Interp *interp = mainPtr->interp;
    Tk_Window tkwin = (Tk_Window) mainPtr->winPtr;
    const struct SystemFontMapEntry *systemFont = systemFontMap;
    NSFont *nsFont;
    TkFontAttributes fa;
    NSMutableCharacterSet *cs;

    /* Since we called before TkpInit, we need our own autorelease pool. */

    NSAutoreleasePool *pool = [NSAutoreleasePool new];


    /* force this for now */

    if (!mainPtr->winPtr->mainPtr) {
	mainPtr->winPtr->mainPtr = mainPtr;
    }
    while (systemFont->systemName) {
	nsFont = (NSFont*) CTFontCreateUIFontForLanguage(
		HIThemeGetUIFontType(systemFont->id), 0, NULL);
	if (nsFont) {
................................................................................
 *---------------------------------------------------------------------------
 *
 * TkpGetNativeFont --
 *
 *	Map a platform-specific native font name to a TkFont.
 *
 * Results:
 *	The return value is a pointer to a TkFont that represents the
 *	native font. If a native font by the given name could not be
 *	found, the return value is NULL.
 *
 *	Every call to this procedure returns a new TkFont structure, even
 *	if the name has already been seen before. The caller should call
 *	TkpDeleteFont() when the font is no longer needed.
 *
 *	The caller is responsible for initializing the memory associated
 *	with the generic TkFont when this function returns and releasing
 *	the contents of the generics TkFont before calling TkpDeleteFont().
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

................................................................................
    } else if (strcmp(name, APPLFONT_NAME) == 0) {
	themeFontId = kThemeApplicationFont;
    } else if (strcmp(name, MENUITEMFONT_NAME) == 0) {
	themeFontId = kThemeMenuItemFont;
    } else {
	return NULL;
    }
    ctFont = CTFontCreateUIFontForLanguage(HIThemeGetUIFontType(
	    themeFontId), 0, NULL);
    if (ctFont) {
	fontPtr = ckalloc(sizeof(MacFont));
	InitFont((NSFont*) ctFont, NULL, fontPtr);
    }

    return (TkFont *) fontPtr;
}
................................................................................
 *
 * TkpGetFontFromAttributes --
 *
 *	Given a desired set of attributes for a font, find a font with the
 *	closest matching attributes.
 *
 * Results:
 *	The return value is a pointer to a TkFont that represents the font
 *	with the desired attributes. If a font with the desired attributes
 *	could not be constructed, some other font will be substituted
 *	automatically.
 *
 *	Every call to this procedure returns a new TkFont structure, even
 *	if the specified attributes have already been seen before. The
 *	caller should call TkpDeleteFont() to free the platform- specific
 *	data when the font is no longer needed.
 *
 *	The caller is responsible for initializing the memory associated
 *	with the generic TkFont when this function returns and releasing
 *	the contents of the generic TkFont before calling TkpDeleteFont().
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

TkFont *
TkpGetFontFromAttributes(
    TkFont *tkFontPtr,		/* If non-NULL, store the information in this
				 * existing TkFont structure, rather than
				 * allocating a new structure to hold the
				 * font; the existing contents of the font
				 * will be released. If NULL, a new TkFont
				 * structure is allocated. */
    Tk_Window tkwin,		/* For display where font will be used. */
    const TkFontAttributes *faPtr)
				/* Set of attributes to match. */
{
    MacFont *fontPtr;
    int points = (int)(TkFontGetPoints(tkwin, faPtr->size) + 0.5);
    NSFontTraitMask traits = GetNSFontTraitsFromTkFontAttributes(faPtr);
    NSInteger weight = (faPtr->weight == TK_FW_BOLD ? 9 : 5);
    NSFont *nsFont;

    nsFont = FindNSFont(faPtr->family, traits, weight, points, 0);
    if (!nsFont) {
	const char *const *aliases = TkFontGetAliasList(faPtr->family);
................................................................................
 
/*
 *---------------------------------------------------------------------------
 *
 * TkpDeleteFont --
 *
 *	Called to release a font allocated by TkpGetNativeFont() or
 *	TkpGetFontFromAttributes(). The caller should have already
 *	released the fields of the TkFont that are used exclusively by the
 *	generic TkFont code.
 *
 * Results:
 *	TkFont is deallocated.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 *---------------------------------------------------------------------------
 *
 * TkpGetFontFamilies --
 *
 *	Return information about the font families that are available on
 *	the display of the given window.
 *
 * Results:
 *	Modifies interp's result object to hold a list of all the available
 *	font families.
 *
 * Side effects:
 *	None.
................................................................................
}
 
/*
 *-------------------------------------------------------------------------
 *
 * TkpGetSubFonts --
 *
 *	A function used by the testing package for querying the actual
 *	screen fonts that make up a font object.
 *
 * Results:
 *	Modifies interp's result object to hold a list containing the names
 *	of the screen fonts that make up the given font object.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpGetFontAttrsForChar --
 *
 *	Retrieve the font attributes of the actual font used to render a
 *	given character.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The font attributes are stored in *faPtr.
 *
................................................................................
 *	that TkpDrawCharsInContext() will be used to actually display the
 *	characters.
 *
 *	This one is almost the same as Tk_MeasureChars(), but with access to
 *	all the characters on the line for context.
 *
 * Results:
 *	The return value is the number of bytes from source that
 *	fit into the span that extends from 0 to maxLength. *lengthPtr is
 *	filled with the x-coordinate of the right edge of the last
 *	character that did fit.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

................................................................................
				 * character that would cross this x-position.
				 * If < 0, then line length is unbounded and
				 * the flags argument is ignored. */
    int flags,			/* Various flag bits OR-ed together:
				 * TK_PARTIAL_OK means include the last char
				 * which only partially fits on this line.
				 * TK_WHOLE_WORDS means stop on a word
				 * boundary, if possible. TK_AT_LEAST_ONE
				 * means return at least one character even
				 * if no characters fit.  If TK_WHOLE_WORDS
				 * and TK_AT_LEAST_ONE are set and the first
				 * word doesn't fit, we return at least one
				 * character or whatever characters fit into
				 * maxLength.  TK_ISOLATE_END means that the
				 * last character should not be considered in
				 * context with the rest of the string (used
				 * for breaking lines). */
    int *lengthPtr)		/* Filled with x-location just after the
				 * terminating character. */
................................................................................
		whitespaceCharacterSet : lineendingCharacterSet;
	while (index > start &&
		[cs characterIsMember:[string characterAtIndex:(index - 1)]]) {
	    index--;
	}

        /*
         * If there is no line breakpoint in the source string between
         * its start and the index position that fits in maxWidth, then
         * CTTypesetterSuggestLineBreak() returns that very last index.
         * However if the TK_WHOLE_WORDS flag is set, we want to break
         * at a word boundary. In this situation, unless TK_AT_LEAST_ONE
         * is set, we must report that zero chars actually fit (in other
         * words the smallest word of the source string is still larger
         * than maxWidth).
         */

        if ((index >= start) && (index < len) &&
                (flags & TK_WHOLE_WORDS) && !(flags & TK_AT_LEAST_ONE) &&
                ![cs characterIsMember:[string characterAtIndex:index]]) {
            index = start;
        }
................................................................................
	if (width < maxWidth && (flags & TK_PARTIAL_OK) && index < len) {
	    range.length = ++index;
	    line = CTTypesetterCreateLine(typesetter, range);
	    width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
	    CFRelease(line);
	}


        /* The call to CTTypesetterSuggestClusterBreak above will always
           return at least one character regardless of whether it exceeded
           it or not.  Clean that up now. */


	while (width > maxWidth && !(flags & TK_PARTIAL_OK)
		&& index > start+(flags & TK_AT_LEAST_ONE)) {
	    range.length = --index;
	    line = CTTypesetterCreateLine(typesetter, range);
	    width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
	    CFRelease(line);
	}
................................................................................
 *
 *	Draw a string of characters on the screen.
 *
 *	With ATSUI we need the line context to do this right, so we have the
 *	actual implementation in TkpDrawCharsInContext().
 *
 * Results:
  *	None.
 *
 * Side effects:
 *	Information gets drawn on the screen.
 *
 *---------------------------------------------------------------------------
 */

................................................................................
    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 x, int y)		/* Coordinates at which to place origin of the
				 * string when drawing. */
{
    DrawCharsInContext(display, drawable, gc, tkfont, source, numBytes,
................................................................................
    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. */
    double x, double y,		/* Coordinates at which to place origin of
				 * string when drawing. */
    double angle)		/* What angle to put text at, in degrees. */
{
................................................................................
    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
................................................................................
    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
................................................................................
	return;
    }
    string = [[NSString alloc] initWithBytesNoCopy:(void*)source
		length:numBytes encoding:NSUTF8StringEncoding freeWhenDone:NO];
    if (!string) {
	return;
    }

    context = drawingContext.context;
    fg = TkMacOSXCreateCGColor(gc, gc->foreground);
    attributes = [fontPtr->nsAttributes mutableCopy];
    [attributes setObject:(id)fg forKey:(id)kCTForegroundColorAttributeName];
    CFRelease(fg);
    nsFont = [attributes objectForKey:NSFontAttributeName];
    [nsFont setInContext:[NSGraphicsContext graphicsContextWithGraphicsPort:
................................................................................
    }
    CGContextConcatCTM(context, t);
    CGContextSetTextPosition(context, x, y);
    start = Tcl_NumUtfChars(source, rangeStart);
    len = Tcl_NumUtfChars(source, rangeStart + rangeLength);
    if (start > 0) {
	CGRect clipRect = CGRectInfinite, startBounds;

	line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, start));
	startBounds = CTLineGetImageBounds(line, context);
	CFRelease(line);
	clipRect.origin.x = startBounds.origin.x + startBounds.size.width;
	CGContextClipToRect(context, clipRect);
    }
    line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, len));
................................................................................
    if (nsFont && familyName) {
	NSFontTraitMask traits = [[NSFontManager sharedFontManager]
		traitsOfFont:nsFont];
	id underline = [nsAttributes objectForKey:
		NSUnderlineStyleAttributeName];
	id strikethrough = [nsAttributes objectForKey:
		NSStrikethroughStyleAttributeName];

	objv[i++] = Tcl_NewStringObj(familyName, -1);
	objv[i++] = Tcl_NewWideIntObj([nsFont pointSize]);
#define S(s) Tcl_NewStringObj(STRINGIFY(s),(int)(sizeof(STRINGIFY(s))-1))
	objv[i++] = (traits & NSBoldFontMask)	? S(bold)   : S(normal);
	objv[i++] = (traits & NSItalicFontMask)	? S(italic) : S(roman);
	if ([underline respondsToSelector:@selector(intValue)] &&
		([underline intValue] & (NSUnderlineStyleSingle |
		NSUnderlineStyleThick | NSUnderlineStyleDouble))) {
	    objv[i++] = S(underline);
	}
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXUseAntialiasedText --
 *
 *	Enables or disables application-wide use of antialiased text (where
 *	available). Sets up a linked Tcl global variable to allow
 *	disabling of antialiased text from tcl.

 *	The possible values for this variable are:
 *
 *	-1 - Use system default as configurable in "System Prefs" -> "General".
 *	 0 - Unconditionally disable antialiasing.
 *	 1 - Unconditionally enable antialiasing.
 *
 * Results:



|
|







 







|
|
<







 







|
|
|
>
|
>
|
|
|
>
|
|
|
>
|







 







|











>
>
|
>
>







 







|







 







>
|
>


>
|
>







 







|
|
|

|
|


|
|
|







 







|
|







 







|
|
|
<

|
|
|
|

|
|
|











|
|
|
|





|







 







|
|
|







 







|
|







 







|
|


|
|







 







|
|







 







|
|
|
<







 







|
|
|
|
|







 







|
|

|
|
|
|
<







 







>
|
|
|
>
>







 







|







 







|
|







 







|
|







 







|
|







 







|
|







 







>







 







>







 







>


|







 







|
|
>







1
2
3
4
5
6
7
8
9
10
11
12
..
28
29
30
31
32
33
34
35
36

37
38
39
40
41
42
43
..
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
...
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
...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
...
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
...
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
...
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
...
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
...
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
...
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
...
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
...
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
...
751
752
753
754
755
756
757
758
759
760

761
762
763
764
765
766
767
...
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
...
869
870
871
872
873
874
875
876
877
878
879
880
881
882

883
884
885
886
887
888
889
...
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
...
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
...
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
...
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
....
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
....
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
....
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
....
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
....
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
....
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
/*
 * tkMacOSXFont.c --
 *
 *	Contains the Macintosh implementation of the platform-independant font
 *	package interface.
 *
 * Copyright 2002-2004 Benjamin Riefenstahl, Benjamin.Riefenstahl@epost.de
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2008-2009, Apple Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
................................................................................

/*
 * The following structure represents our Macintosh-specific implementation
 * of a font object.
 */

typedef struct {
    TkFont font;		/* Stuff used by generic font package. Must be
				 * first in structure. */

    NSFont *nsFont;
    NSDictionary *nsAttributes;
} MacFont;

/*
 * The names for our "native" fonts.
 */
................................................................................
};
#undef ThemeFont

static int antialiasedTextEnabled = -1;
static NSCharacterSet *whitespaceCharacterSet = nil;
static NSCharacterSet *lineendingCharacterSet = nil;

static void		GetTkFontAttributesForNSFont(NSFont *nsFont,
			    TkFontAttributes *faPtr);
static NSFont *		FindNSFont(const char *familyName,
			    NSFontTraitMask traits, NSInteger weight,
			    CGFloat size, int fallbackToDefault);
static void		InitFont(NSFont *nsFont,
			    const TkFontAttributes *reqFaPtr,
			    MacFont *fontPtr);
static int		CreateNamedSystemFont(Tcl_Interp *interp,
			    Tk_Window tkwin, const char *name,
			    TkFontAttributes *faPtr);
static void		DrawCharsInContext(Display *display, Drawable drawable,
			    GC gc, Tk_Font tkfont, const char *source,
			    int numBytes, int rangeStart, int rangeLength,
			    int x, int y, double angle);

#pragma mark -
#pragma mark Font Helpers:

#define GetNSFontTraitsFromTkFontAttributes(faPtr) \
	((faPtr)->weight == TK_FW_BOLD ? NSBoldFontMask : NSUnboldFontMask) | \
	((faPtr)->slant == TK_FS_ITALIC ? NSItalicFontMask : NSUnitalicFontMask)
................................................................................
    NSDictionary *nsAttributes;
    NSRect bounds;
    CGFloat kern = 0.0;
    NSFontRenderingMode renderingMode = NSFontDefaultRenderingMode;
    int ascent, descent/*, dontAA*/;
    static const UniChar ch[] = {'.', 'W', ' ', 0xc4, 0xc1, 0xc2, 0xc3, 0xc7};
			/* ., W, Space, Auml, Aacute, Acirc, Atilde, Ccedilla */
#define nCh	(sizeof(ch) / sizeof(UniChar))
    CGGlyph glyphs[nCh];
    CGRect boundingRects[nCh];

    fontPtr->font.fid = (Font) fontPtr;
    faPtr = &fontPtr->font.fa;
    if (reqFaPtr) {
	*faPtr = *reqFaPtr;
    } else {
	TkInitFontAttributes(faPtr);
    }
    fontPtr->nsFont = nsFont;

    /*
     * Some don't like antialiasing on fixed-width even if bigger than limit
     */

    // dontAA = [nsFont isFixedPitch] && fontPtr->font.fa.size <= 10;
    if (antialiasedTextEnabled >= 0/* || dontAA*/) {
	renderingMode = (antialiasedTextEnabled == 0/* || dontAA*/) ?
		NSFontIntegerAdvancementsRenderingMode :
		NSFontAntialiasedRenderingMode;
    }
    nsFont = [nsFont screenFontWithRenderingMode:renderingMode];
................................................................................
	    [NSNumber numberWithInt:faPtr->overstrike ?
		NSUnderlineStyleSingle|NSUnderlinePatternSolid :
		NSUnderlineStyleNone], NSStrikethroughStyleAttributeName,
	    [NSNumber numberWithInt:fmPtr->fixed ? 0 : 1],
		NSLigatureAttributeName,
	    [NSNumber numberWithDouble:kern], NSKernAttributeName, nil];
    fontPtr->nsAttributes = [nsAttributes retain];
#undef nCh
}
 
/*
 *-------------------------------------------------------------------------
 *
 * CreateNamedSystemFont --
 *
................................................................................
{
    Tcl_Interp *interp = mainPtr->interp;
    Tk_Window tkwin = (Tk_Window) mainPtr->winPtr;
    const struct SystemFontMapEntry *systemFont = systemFontMap;
    NSFont *nsFont;
    TkFontAttributes fa;
    NSMutableCharacterSet *cs;
    /*
     * Since we called before TkpInit, we need our own autorelease pool.
     */
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    /*
     * Force this for now.
     */
    if (!mainPtr->winPtr->mainPtr) {
	mainPtr->winPtr->mainPtr = mainPtr;
    }
    while (systemFont->systemName) {
	nsFont = (NSFont*) CTFontCreateUIFontForLanguage(
		HIThemeGetUIFontType(systemFont->id), 0, NULL);
	if (nsFont) {
................................................................................
 *---------------------------------------------------------------------------
 *
 * TkpGetNativeFont --
 *
 *	Map a platform-specific native font name to a TkFont.
 *
 * Results:
 *	The return value is a pointer to a TkFont that represents the native
 *	font. If a native font by the given name could not be found, the return
 *	value is NULL.
 *
 *	Every call to this procedure returns a new TkFont structure, even if
 *	the name has already been seen before. The caller should call
 *	TkpDeleteFont() when the font is no longer needed.
 *
 *	The caller is responsible for initializing the memory associated with
 *	the generic TkFont when this function returns and releasing the
 *	contents of the generics TkFont before calling TkpDeleteFont().
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

................................................................................
    } else if (strcmp(name, APPLFONT_NAME) == 0) {
	themeFontId = kThemeApplicationFont;
    } else if (strcmp(name, MENUITEMFONT_NAME) == 0) {
	themeFontId = kThemeMenuItemFont;
    } else {
	return NULL;
    }
    ctFont = CTFontCreateUIFontForLanguage(
	    HIThemeGetUIFontType(themeFontId), 0, NULL);
    if (ctFont) {
	fontPtr = ckalloc(sizeof(MacFont));
	InitFont((NSFont*) ctFont, NULL, fontPtr);
    }

    return (TkFont *) fontPtr;
}
................................................................................
 *
 * TkpGetFontFromAttributes --
 *
 *	Given a desired set of attributes for a font, find a font with the
 *	closest matching attributes.
 *
 * Results:
 *	The return value is a pointer to a TkFont that represents the font with
 *	the desired attributes. If a font with the desired attributes could not
 *	be constructed, some other font will be substituted automatically.

 *
 *	Every call to this procedure returns a new TkFont structure, even if
 *	the specified attributes have already been seen before. The caller
 *	should call TkpDeleteFont() to free the platform- specific data when
 *	the font is no longer needed.
 *
 *	The caller is responsible for initializing the memory associated with
 *	the generic TkFont when this function returns and releasing the
 *	contents of the generic TkFont before calling TkpDeleteFont().
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

TkFont *
TkpGetFontFromAttributes(
    TkFont *tkFontPtr,		/* If non-NULL, store the information in this
				 * existing TkFont structure, rather than
				 * allocating a new structure to hold the font;
				 * the existing contents of the font will be
				 * released. If NULL, a new TkFont structure is
				 * allocated. */
    Tk_Window tkwin,		/* For display where font will be used. */
    const TkFontAttributes *faPtr)
				/* Set of attributes to match. */
{
    MacFont *fontPtr;
    int points = (int) (TkFontGetPoints(tkwin, faPtr->size) + 0.5);
    NSFontTraitMask traits = GetNSFontTraitsFromTkFontAttributes(faPtr);
    NSInteger weight = (faPtr->weight == TK_FW_BOLD ? 9 : 5);
    NSFont *nsFont;

    nsFont = FindNSFont(faPtr->family, traits, weight, points, 0);
    if (!nsFont) {
	const char *const *aliases = TkFontGetAliasList(faPtr->family);
................................................................................
 
/*
 *---------------------------------------------------------------------------
 *
 * TkpDeleteFont --
 *
 *	Called to release a font allocated by TkpGetNativeFont() or
 *	TkpGetFontFromAttributes(). The caller should have already released the
 *	fields of the TkFont that are used exclusively by the generic TkFont
 *	code.
 *
 * Results:
 *	TkFont is deallocated.
 *
 * Side effects:
 *	None.
 *
................................................................................
}
 
/*
 *---------------------------------------------------------------------------
 *
 * TkpGetFontFamilies --
 *
 *	Return information about the font families that are available on the
 *	display of the given window.
 *
 * Results:
 *	Modifies interp's result object to hold a list of all the available
 *	font families.
 *
 * Side effects:
 *	None.
................................................................................
}
 
/*
 *-------------------------------------------------------------------------
 *
 * TkpGetSubFonts --
 *
 *	A function used by the testing package for querying the actual screen
 *	fonts that make up a font object.
 *
 * Results:
 *	Modifies interp's result object to hold a list containing the names of
 *	the screen fonts that make up the given font object.
 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------------
 */

................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpGetFontAttrsForChar --
 *
 *	Retrieve the font attributes of the actual font used to render a given
 *	character.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The font attributes are stored in *faPtr.
 *
................................................................................
 *	that TkpDrawCharsInContext() will be used to actually display the
 *	characters.
 *
 *	This one is almost the same as Tk_MeasureChars(), but with access to
 *	all the characters on the line for context.
 *
 * Results:
 *	The return value is the number of bytes from source that fit into the
 *	span that extends from 0 to maxLength. *lengthPtr is filled with the
 *	x-coordinate of the right edge of the last character that did fit.

 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

................................................................................
				 * character that would cross this x-position.
				 * If < 0, then line length is unbounded and
				 * the flags argument is ignored. */
    int flags,			/* Various flag bits OR-ed together:
				 * TK_PARTIAL_OK means include the last char
				 * which only partially fits on this line.
				 * TK_WHOLE_WORDS means stop on a word
				 * boundary, if possible. TK_AT_LEAST_ONE means
				 * return at least one character even if no
				 * characters fit.  If TK_WHOLE_WORDS and
				 * TK_AT_LEAST_ONE are set and the first word
				 * doesn't fit, we return at least one
				 * character or whatever characters fit into
				 * maxLength.  TK_ISOLATE_END means that the
				 * last character should not be considered in
				 * context with the rest of the string (used
				 * for breaking lines). */
    int *lengthPtr)		/* Filled with x-location just after the
				 * terminating character. */
................................................................................
		whitespaceCharacterSet : lineendingCharacterSet;
	while (index > start &&
		[cs characterIsMember:[string characterAtIndex:(index - 1)]]) {
	    index--;
	}

        /*
         * If there is no line breakpoint in the source string between its
         * start and the index position that fits in maxWidth, then
         * CTTypesetterSuggestLineBreak() returns that very last index.
         * However if the TK_WHOLE_WORDS flag is set, we want to break at a
         * word boundary. In this situation, unless TK_AT_LEAST_ONE is set, we
         * must report that zero chars actually fit (in other words the
         * smallest word of the source string is still larger than maxWidth).

         */

        if ((index >= start) && (index < len) &&
                (flags & TK_WHOLE_WORDS) && !(flags & TK_AT_LEAST_ONE) &&
                ![cs characterIsMember:[string characterAtIndex:index]]) {
            index = start;
        }
................................................................................
	if (width < maxWidth && (flags & TK_PARTIAL_OK) && index < len) {
	    range.length = ++index;
	    line = CTTypesetterCreateLine(typesetter, range);
	    width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
	    CFRelease(line);
	}

        /*
	 * The call to CTTypesetterSuggestClusterBreak above will always return
	 * at least one character regardless of whether it exceeded it or not.
	 * Clean that up now.
	 */

	while (width > maxWidth && !(flags & TK_PARTIAL_OK)
		&& index > start+(flags & TK_AT_LEAST_ONE)) {
	    range.length = --index;
	    line = CTTypesetterCreateLine(typesetter, range);
	    width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
	    CFRelease(line);
	}
................................................................................
 *
 *	Draw a string of characters on the screen.
 *
 *	With ATSUI we need the line context to do this right, so we have the
 *	actual implementation in TkpDrawCharsInContext().
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information gets drawn on the screen.
 *
 *---------------------------------------------------------------------------
 */

................................................................................
    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 x, int y)		/* Coordinates at which to place origin of the
				 * string when drawing. */
{
    DrawCharsInContext(display, drawable, gc, tkfont, source, numBytes,
................................................................................
    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. */
    double x, double y,		/* Coordinates at which to place origin of
				 * string when drawing. */
    double angle)		/* What angle to put text at, in degrees. */
{
................................................................................
    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
................................................................................
    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
................................................................................
	return;
    }
    string = [[NSString alloc] initWithBytesNoCopy:(void*)source
		length:numBytes encoding:NSUTF8StringEncoding freeWhenDone:NO];
    if (!string) {
	return;
    }

    context = drawingContext.context;
    fg = TkMacOSXCreateCGColor(gc, gc->foreground);
    attributes = [fontPtr->nsAttributes mutableCopy];
    [attributes setObject:(id)fg forKey:(id)kCTForegroundColorAttributeName];
    CFRelease(fg);
    nsFont = [attributes objectForKey:NSFontAttributeName];
    [nsFont setInContext:[NSGraphicsContext graphicsContextWithGraphicsPort:
................................................................................
    }
    CGContextConcatCTM(context, t);
    CGContextSetTextPosition(context, x, y);
    start = Tcl_NumUtfChars(source, rangeStart);
    len = Tcl_NumUtfChars(source, rangeStart + rangeLength);
    if (start > 0) {
	CGRect clipRect = CGRectInfinite, startBounds;

	line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, start));
	startBounds = CTLineGetImageBounds(line, context);
	CFRelease(line);
	clipRect.origin.x = startBounds.origin.x + startBounds.size.width;
	CGContextClipToRect(context, clipRect);
    }
    line = CTTypesetterCreateLine(typesetter, CFRangeMake(0, len));
................................................................................
    if (nsFont && familyName) {
	NSFontTraitMask traits = [[NSFontManager sharedFontManager]
		traitsOfFont:nsFont];
	id underline = [nsAttributes objectForKey:
		NSUnderlineStyleAttributeName];
	id strikethrough = [nsAttributes objectForKey:
		NSStrikethroughStyleAttributeName];

	objv[i++] = Tcl_NewStringObj(familyName, -1);
	objv[i++] = Tcl_NewWideIntObj([nsFont pointSize]);
#define S(s)    Tcl_NewStringObj(STRINGIFY(s), (int)(sizeof(STRINGIFY(s))-1))
	objv[i++] = (traits & NSBoldFontMask)	? S(bold)   : S(normal);
	objv[i++] = (traits & NSItalicFontMask)	? S(italic) : S(roman);
	if ([underline respondsToSelector:@selector(intValue)] &&
		([underline intValue] & (NSUnderlineStyleSingle |
		NSUnderlineStyleThick | NSUnderlineStyleDouble))) {
	    objv[i++] = S(underline);
	}
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXUseAntialiasedText --
 *
 *	Enables or disables application-wide use of antialiased text (where
 *	available). Sets up a linked Tcl global variable to allow disabling of
 *	antialiased text from Tcl.
 *
 *	The possible values for this variable are:
 *
 *	-1 - Use system default as configurable in "System Prefs" -> "General".
 *	 0 - Unconditionally disable antialiasing.
 *	 1 - Unconditionally enable antialiasing.
 *
 * Results:

Changes to macosx/tkMacOSXImage.c.

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
..
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
...
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
...
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
...
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
...
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
...
385
386
387
388
389
390
391

392
393
394
395
396
397
398
...
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
...
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
...
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
...
555
556
557
558
559
560
561

562
563
564
565
566
567
568

569
570
571
572
573
574
575

int
_XInitImageFuncPtrs(
    XImage *image)
{
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXCreateCGImageWithXImage --
 *
 *	Create CGImage from XImage, copying the image data.  Called
 *      in Tk_PutImage and (currently) nowhere else.
................................................................................
	    while (srcPtr < endPtr) {
		*destPtr++ = xBitReverseTable[(unsigned char)(*(srcPtr++))];
	    }
	} else {
	    data = memcpy(ckalloc(len), image->data + image->xoffset, len);
	}
	if (data) {
	    provider = CGDataProviderCreateWithData(data, data, len, releaseData);

	}
	if (provider) {
	    img = CGImageMaskCreate(image->width, image->height, bitsPerComponent,
				    bitsPerPixel, image->bytes_per_line, provider, decode, 0);
	}
    } else if (image->format == ZPixmap && image->bits_per_pixel == 32) {


	/*
	 * Color image
	 */

	CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

	if (image->width == 0 && image->height == 0) {

	    /*
	     * CGCreateImage complains on early macOS releases.
	     */

	    return NULL;
	}
	bitsPerComponent = 8;
	bitsPerPixel = 32;
	bitmapInfo = (image->byte_order == MSBFirst ?
		      kCGBitmapByteOrder32Little : kCGBitmapByteOrder32Big);
	bitmapInfo |= kCGImageAlphaLast;
	data = memcpy(ckalloc(len), image->data + image->xoffset, len);
	if (data) {
	    provider = CGDataProviderCreateWithData(data, data, len, releaseData);

	}
	if (provider) {
	    img = CGImageCreate(image->width, image->height, bitsPerComponent,
		    bitsPerPixel, image->bytes_per_line, colorspace, bitmapInfo,
		    provider, decode, 0, kCGRenderingIntentDefault);
	    CFRelease(provider);
	}
................................................................................
	}
    } else {
	TkMacOSXDbgMsg("Unsupported image type");
    }
    return img;
}
 

/*
 *----------------------------------------------------------------------
 *
 * XGetImage --
 *
 *	This function copies data from a pixmap or window into an XImage.  It
 *      is essentially never used. At one time it was called by
................................................................................
    unsigned int bytes_per_row, size, row, n, m;
    unsigned int scalefactor=1, scaled_height=height, scaled_width=width;
    NSWindow *win = TkMacOSXDrawableWindow(drawable);
    static enum {unknown, no, yes} has_retina = unknown;

    if (win && has_retina == unknown) {
#ifdef __clang__
	has_retina = [win respondsToSelector:@selector(backingScaleFactor)]?
	    yes : no;
#else
	has_retina = no;
#endif
    }

    if (has_retina == yes) {

	/*
	 * We only allow scale factors 1 or 2, as Apple currently does.
	 */

#ifdef __clang__
	scalefactor = [win backingScaleFactor] == 2.0 ? 2 : 1;
#endif
................................................................................

    if (format == ZPixmap) {
	if (width == 0 || height == 0) {
	    return NULL;
	}

	bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(drawable,
			  x, y, width, height);
	if (!bitmap_rep) {
	    TkMacOSXDbgMsg("XGetImage: Failed to construct NSBitmapRep");
	    return NULL;
	}
	bitmap_fmt = [bitmap_rep bitmapFormat];
	size = [bitmap_rep bytesPerPlane];
	bytes_per_row = [bitmap_rep bytesPerRow];
	bitmap = ckalloc(size);
	if (!bitmap                              ||
	    (bitmap_fmt != 0 && bitmap_fmt != 1) ||
	    [bitmap_rep samplesPerPixel] != 4    ||
	    [bitmap_rep isPlanar] != 0           ||
	    bytes_per_row < 4 * scaled_width    ||
	    size != bytes_per_row*scaled_height  ) {
	    TkMacOSXDbgMsg("XGetImage: Unrecognized bitmap format");
	    CFRelease(bitmap_rep);
	    return NULL;
	}
	memcpy(bitmap, (char *)[bitmap_rep bitmapData], size);
	CFRelease(bitmap_rep);

	/*
	 * When Apple extracts a bitmap from an NSView, it may be in
	 * either BGRA or ABGR format.  For an XImage we need RGBA.
	 */

	struct pixel_fmt pixel = bitmap_fmt == 0 ? bgra : abgr;

	for (row = 0, n = 0; row < scaled_height; row++, n += bytes_per_row) {
	    for (m = n; m < n + 4*scaled_width; m += 4) {
		R = *(bitmap + m + pixel.r);
................................................................................
		*(bitmap + m)     = R;
		*(bitmap + m + 1) = G;
		*(bitmap + m + 2) = B;
		*(bitmap + m + 3) = A;
	    }
	}
	imagePtr = XCreateImage(display, NULL, depth, format, offset,
				(char*)bitmap, scaled_width, scaled_height,
				bitmap_pad, bytes_per_row);
	if (scalefactor == 2) {
	    imagePtr->pixelpower = 1;
	}
    } else {
	/*
	 * There are some calls to XGetImage in the generic Tk
	 * code which pass an XYPixmap rather than a ZPixmap.
	 * XYPixmaps should be handled here.
	 */
	TkMacOSXDbgMsg("XGetImage does not handle XYPixmaps at the moment.");
    }
    return imagePtr;
}
 
/*
................................................................................

    if (image && image->data) {
	unsigned char *srcPtr = ((unsigned char*) image->data)
		+ (y * image->bytes_per_line)
		+ (((image->xoffset + x) * image->bits_per_pixel) / NBBY);

	switch (image->bits_per_pixel) {
	    case 32: {
		r = (*((unsigned int*) srcPtr) >> 16) & 0xff;
		g = (*((unsigned int*) srcPtr) >>  8) & 0xff;
		b = (*((unsigned int*) srcPtr)      ) & 0xff;
		/*if (image->byte_order == LSBFirst) {
		    r = srcPtr[2]; g = srcPtr[1]; b = srcPtr[0];
		} else {
		    r = srcPtr[1]; g = srcPtr[2]; b = srcPtr[3];
		}*/
		break;
	    }
	    case 16:
		r = (*((unsigned short*) srcPtr) >> 7) & 0xf8;
		g = (*((unsigned short*) srcPtr) >> 2) & 0xf8;
		b = (*((unsigned short*) srcPtr) << 3) & 0xf8;
		break;
	    case 8:
		r = (*srcPtr << 2) & 0xc0;
		g = (*srcPtr << 4) & 0xc0;
		b = (*srcPtr << 6) & 0xc0;
		r |= r >> 2 | r >> 4 | r >> 6;
		g |= g >> 2 | g >> 4 | g >> 6;
		b |= b >> 2 | b >> 4 | b >> 6;
		break;
	    case 4: {
		unsigned char c = (x % 2) ? *srcPtr : (*srcPtr >> 4);

		r = (c & 0x04) ? 0xff : 0;
		g = (c & 0x02) ? 0xff : 0;
		b = (c & 0x01) ? 0xff : 0;
		break;
		}
	    case 1:
		r = g = b = ((*srcPtr) & (0x80 >> (x % 8))) ? 0xff : 0;
		break;
	}
    }
    return (PIXEL_MAGIC << 24) | (r << 16) | (g << 8) | b;
}
 
/*
 *----------------------------------------------------------------------
................................................................................
    int y,
    unsigned long pixel)
{
    if (image && image->data) {
	unsigned char *dstPtr = ((unsigned char*) image->data)
		+ (y * image->bytes_per_line)
		+ (((image->xoffset + x) * image->bits_per_pixel) / NBBY);

	if (image->bits_per_pixel == 32) {
	    *((unsigned int*) dstPtr) = pixel;
	} else {
	    unsigned char r = ((pixel & image->red_mask)   >> 16) & 0xff;
	    unsigned char g = ((pixel & image->green_mask) >>  8) & 0xff;
	    unsigned char b = ((pixel & image->blue_mask)       ) & 0xff;
	    switch (image->bits_per_pixel) {
................................................................................
			(*dstPtr & ~(0x80 >> (x % 8)));
		break;
	    }
	}
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * XCreateImage --
 *
 *	Allocates storage for a new XImage.
 *
................................................................................
    char* data,
    unsigned int width,
    unsigned int height,
    int bitmap_pad,
    int bytes_per_line)
{
    XImage *ximage;

    display->request++;
    ximage = ckalloc(sizeof(XImage));

    ximage->height = height;
    ximage->width = width;
    ximage->depth = depth;
    ximage->xoffset = offset;
    ximage->format = format;
    ximage->data = data;
    ximage->obdata = NULL;


    /* The default pixelpower is 0.  This must be explicitly set to 1 in the
     * case of an XImage extracted from a Retina display.
     */

    ximage->pixelpower = 0;

    if (format == ZPixmap) {
	ximage->bits_per_pixel = 32;
	ximage->bitmap_unit = 32;
    } else {
	ximage->bits_per_pixel = 1;
	ximage->bitmap_unit = 8;
    }
    if (bitmap_pad) {
	ximage->bitmap_pad = bitmap_pad;
    } else {

	/* Use 16 byte alignment for best Quartz perfomance */


	ximage->bitmap_pad = 128;
    }
    if (bytes_per_line) {
	ximage->bytes_per_line = bytes_per_line;
    } else {
	ximage->bytes_per_line = ((width * ximage->bits_per_pixel +
		(ximage->bitmap_pad - 1)) >> 3) &
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkPutImage --
 *
 *	Copies a rectangular subimage of an XImage into a drawable.
 *      Currently this is only called by TkImgPhotoDisplay, using
 *      a Window as the drawable.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws the image on the specified drawable.
 *
................................................................................
	 */

	if (!(macDraw->flags & TK_IS_PIXMAP)) {
	    CGContextSetBlendMode(dc.context, kCGBlendModeSourceAtop);
	}
	if (img) {


	    /* If the XImage has big pixels, the source is rescaled to reflect
	     * the actual pixel dimensions.  This is not currently used, but
	     * could arise if the image were copied from a retina monitor and
	     * redrawn on an ordinary monitor.
	     */

	    int pp = image->pixelpower;

	    bounds = CGRectMake(0, 0, image->width, image->height);
	    srcRect = CGRectMake(src_x<<pp, src_y<<pp, width<<pp, height<<pp);
	    dstRect = CGRectMake(dest_x, dest_y, width, height);
	    TkMacOSXDrawCGImage(drawable, gc, dc.context,
				img, gc->foreground, gc->background,
				bounds, srcRect, dstRect);
	    CFRelease(img);







|







 







|
>


|
|
<
|
|
>







<









|



|
>







 







<







 







|
|






<







 







|








|
|
|
|
|
|








|
|







 







|
|





|
|
|







 







|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|







 







>







 







|







 







>










>
>
|


>












>
|
>
>







 







|
|
|







 







>
|






>







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
..
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
...
124
125
126
127
128
129
130

131
132
133
134
135
136
137
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189

190
191
192
193
194
195
196
...
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
...
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
...
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
...
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
...
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
...
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
...
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
...
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

int
_XInitImageFuncPtrs(
    XImage *image)
{
    return 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXCreateCGImageWithXImage --
 *
 *	Create CGImage from XImage, copying the image data.  Called
 *      in Tk_PutImage and (currently) nowhere else.
................................................................................
	    while (srcPtr < endPtr) {
		*destPtr++ = xBitReverseTable[(unsigned char)(*(srcPtr++))];
	    }
	} else {
	    data = memcpy(ckalloc(len), image->data + image->xoffset, len);
	}
	if (data) {
	    provider = CGDataProviderCreateWithData(data, data, len,
		    releaseData);
	}
	if (provider) {
	    img = CGImageMaskCreate(image->width, image->height,
		    bitsPerComponent, bitsPerPixel, image->bytes_per_line,

		    provider, decode, 0);
	}
    } else if ((image->format == ZPixmap) && (image->bits_per_pixel == 32)) {
	/*
	 * Color image
	 */

	CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

	if (image->width == 0 && image->height == 0) {

	    /*
	     * CGCreateImage complains on early macOS releases.
	     */

	    return NULL;
	}
	bitsPerComponent = 8;
	bitsPerPixel = 32;
	bitmapInfo = (image->byte_order == MSBFirst ?
		kCGBitmapByteOrder32Little : kCGBitmapByteOrder32Big);
	bitmapInfo |= kCGImageAlphaLast;
	data = memcpy(ckalloc(len), image->data + image->xoffset, len);
	if (data) {
	    provider = CGDataProviderCreateWithData(data, data, len,
		    releaseData);
	}
	if (provider) {
	    img = CGImageCreate(image->width, image->height, bitsPerComponent,
		    bitsPerPixel, image->bytes_per_line, colorspace, bitmapInfo,
		    provider, decode, 0, kCGRenderingIntentDefault);
	    CFRelease(provider);
	}
................................................................................
	}
    } else {
	TkMacOSXDbgMsg("Unsupported image type");
    }
    return img;
}
 

/*
 *----------------------------------------------------------------------
 *
 * XGetImage --
 *
 *	This function copies data from a pixmap or window into an XImage.  It
 *      is essentially never used. At one time it was called by
................................................................................
    unsigned int bytes_per_row, size, row, n, m;
    unsigned int scalefactor=1, scaled_height=height, scaled_width=width;
    NSWindow *win = TkMacOSXDrawableWindow(drawable);
    static enum {unknown, no, yes} has_retina = unknown;

    if (win && has_retina == unknown) {
#ifdef __clang__
	has_retina = [win respondsToSelector:@selector(backingScaleFactor)] ?
		yes : no;
#else
	has_retina = no;
#endif
    }

    if (has_retina == yes) {

	/*
	 * We only allow scale factors 1 or 2, as Apple currently does.
	 */

#ifdef __clang__
	scalefactor = [win backingScaleFactor] == 2.0 ? 2 : 1;
#endif
................................................................................

    if (format == ZPixmap) {
	if (width == 0 || height == 0) {
	    return NULL;
	}

	bitmap_rep = TkMacOSXBitmapRepFromDrawableRect(drawable,
		x, y, width, height);
	if (!bitmap_rep) {
	    TkMacOSXDbgMsg("XGetImage: Failed to construct NSBitmapRep");
	    return NULL;
	}
	bitmap_fmt = [bitmap_rep bitmapFormat];
	size = [bitmap_rep bytesPerPlane];
	bytes_per_row = [bitmap_rep bytesPerRow];
	bitmap = ckalloc(size);
	if (!bitmap
		|| (bitmap_fmt != 0 && bitmap_fmt != 1)
		|| [bitmap_rep samplesPerPixel] != 4
		|| [bitmap_rep isPlanar] != 0
		|| bytes_per_row < 4 * scaled_width
		|| size != bytes_per_row * scaled_height) {
	    TkMacOSXDbgMsg("XGetImage: Unrecognized bitmap format");
	    CFRelease(bitmap_rep);
	    return NULL;
	}
	memcpy(bitmap, (char *)[bitmap_rep bitmapData], size);
	CFRelease(bitmap_rep);

	/*
	 * When Apple extracts a bitmap from an NSView, it may be in either
	 * BGRA or ABGR format.  For an XImage we need RGBA.
	 */

	struct pixel_fmt pixel = bitmap_fmt == 0 ? bgra : abgr;

	for (row = 0, n = 0; row < scaled_height; row++, n += bytes_per_row) {
	    for (m = n; m < n + 4*scaled_width; m += 4) {
		R = *(bitmap + m + pixel.r);
................................................................................
		*(bitmap + m)     = R;
		*(bitmap + m + 1) = G;
		*(bitmap + m + 2) = B;
		*(bitmap + m + 3) = A;
	    }
	}
	imagePtr = XCreateImage(display, NULL, depth, format, offset,
		(char*) bitmap, scaled_width, scaled_height,
		bitmap_pad, bytes_per_row);
	if (scalefactor == 2) {
	    imagePtr->pixelpower = 1;
	}
    } else {
	/*
	 * There are some calls to XGetImage in the generic Tk code which pass
	 * an XYPixmap rather than a ZPixmap.  XYPixmaps should be handled
	 * here.
	 */
	TkMacOSXDbgMsg("XGetImage does not handle XYPixmaps at the moment.");
    }
    return imagePtr;
}
 
/*
................................................................................

    if (image && image->data) {
	unsigned char *srcPtr = ((unsigned char*) image->data)
		+ (y * image->bytes_per_line)
		+ (((image->xoffset + x) * image->bits_per_pixel) / NBBY);

	switch (image->bits_per_pixel) {
	case 32:
	    r = (*((unsigned int*) srcPtr) >> 16) & 0xff;
	    g = (*((unsigned int*) srcPtr) >>  8) & 0xff;
	    b = (*((unsigned int*) srcPtr)      ) & 0xff;
	    /*if (image->byte_order == LSBFirst) {
		r = srcPtr[2]; g = srcPtr[1]; b = srcPtr[0];
	    } else {
		r = srcPtr[1]; g = srcPtr[2]; b = srcPtr[3];
	    }*/
	    break;

	case 16:
	    r = (*((unsigned short*) srcPtr) >> 7) & 0xf8;
	    g = (*((unsigned short*) srcPtr) >> 2) & 0xf8;
	    b = (*((unsigned short*) srcPtr) << 3) & 0xf8;
	    break;
	case 8:
	    r = (*srcPtr << 2) & 0xc0;
	    g = (*srcPtr << 4) & 0xc0;
	    b = (*srcPtr << 6) & 0xc0;
	    r |= r >> 2 | r >> 4 | r >> 6;
	    g |= g >> 2 | g >> 4 | g >> 6;
	    b |= b >> 2 | b >> 4 | b >> 6;
	    break;
	case 4: {
	    unsigned char c = (x % 2) ? *srcPtr : (*srcPtr >> 4);

	    r = (c & 0x04) ? 0xff : 0;
	    g = (c & 0x02) ? 0xff : 0;
	    b = (c & 0x01) ? 0xff : 0;
	    break;
	}
	case 1:
	    r = g = b = ((*srcPtr) & (0x80 >> (x % 8))) ? 0xff : 0;
	    break;
	}
    }
    return (PIXEL_MAGIC << 24) | (r << 16) | (g << 8) | b;
}
 
/*
 *----------------------------------------------------------------------
................................................................................
    int y,
    unsigned long pixel)
{
    if (image && image->data) {
	unsigned char *dstPtr = ((unsigned char*) image->data)
		+ (y * image->bytes_per_line)
		+ (((image->xoffset + x) * image->bits_per_pixel) / NBBY);

	if (image->bits_per_pixel == 32) {
	    *((unsigned int*) dstPtr) = pixel;
	} else {
	    unsigned char r = ((pixel & image->red_mask)   >> 16) & 0xff;
	    unsigned char g = ((pixel & image->green_mask) >>  8) & 0xff;
	    unsigned char b = ((pixel & image->blue_mask)       ) & 0xff;
	    switch (image->bits_per_pixel) {
................................................................................
			(*dstPtr & ~(0x80 >> (x % 8)));
		break;
	    }
	}
    }
    return 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * XCreateImage --
 *
 *	Allocates storage for a new XImage.
 *
................................................................................
    char* data,
    unsigned int width,
    unsigned int height,
    int bitmap_pad,
    int bytes_per_line)
{
    XImage *ximage;

    display->request++;
    ximage = ckalloc(sizeof(XImage));

    ximage->height = height;
    ximage->width = width;
    ximage->depth = depth;
    ximage->xoffset = offset;
    ximage->format = format;
    ximage->data = data;
    ximage->obdata = NULL;

    /*
     * The default pixelpower is 0.  This must be explicitly set to 1 in the
     * case of an XImage extracted from a Retina display.
     */

    ximage->pixelpower = 0;

    if (format == ZPixmap) {
	ximage->bits_per_pixel = 32;
	ximage->bitmap_unit = 32;
    } else {
	ximage->bits_per_pixel = 1;
	ximage->bitmap_unit = 8;
    }
    if (bitmap_pad) {
	ximage->bitmap_pad = bitmap_pad;
    } else {
	/*
	 * Use 16 byte alignment for best Quartz perfomance.
	 */

	ximage->bitmap_pad = 128;
    }
    if (bytes_per_line) {
	ximage->bytes_per_line = bytes_per_line;
    } else {
	ximage->bytes_per_line = ((width * ximage->bits_per_pixel +
		(ximage->bitmap_pad - 1)) >> 3) &
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkPutImage --
 *
 *	Copies a rectangular subimage of an XImage into a drawable.  Currently
 *      this is only called by TkImgPhotoDisplay, using a Window as the
 *      drawable.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws the image on the specified drawable.
 *
................................................................................
	 */

	if (!(macDraw->flags & TK_IS_PIXMAP)) {
	    CGContextSetBlendMode(dc.context, kCGBlendModeSourceAtop);
	}
	if (img) {

	    /*
	     * If the XImage has big pixels, the source is rescaled to reflect
	     * the actual pixel dimensions.  This is not currently used, but
	     * could arise if the image were copied from a retina monitor and
	     * redrawn on an ordinary monitor.
	     */

	    int pp = image->pixelpower;

	    bounds = CGRectMake(0, 0, image->width, image->height);
	    srcRect = CGRectMake(src_x<<pp, src_y<<pp, width<<pp, height<<pp);
	    dstRect = CGRectMake(dest_x, dest_y, width, height);
	    TkMacOSXDrawCGImage(drawable, gc, dc.context,
				img, gc->foreground, gc->background,
				bounds, srcRect, dstRect);
	    CFRelease(img);

Changes to macosx/tkMacOSXInit.c.

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
...
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
...
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
...
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
 * called while the pool is locked.
 */
#undef DEBUG_LOCK

@implementation TKApplication(TKInit)
- (void) _resetAutoreleasePool
{
    if([self poolLock] == 0) {
	[_mainPool drain];
	_mainPool = [NSAutoreleasePool new];
    } else {
#ifdef DEBUG_LOCK
	fprintf(stderr, "Pool is locked with count %d!!!!\n", [self poolLock]);
#endif
    }
................................................................................
    TkMacOSXUseAntialiasedText(_eventInterp, -1);
    TkMacOSXInitCGDrawing(_eventInterp, TRUE, 0);
}

-(void)applicationDidFinishLaunching:(NSNotification *)notification
{
    /*
     * It is not safe to force activation of the NSApp until this
     * method is called.  Activating too early can cause the menu
     * bar to be unresponsive.
     */

    [NSApp activateIgnoringOtherApps: YES];

    /*
     * Process events to ensure that the root window is fully
     * initialized. See ticket 56a1823c73.
     */
    
    [NSApp _lockAutoreleasePool];
    while (Tcl_DoOneEvent(TCL_WINDOW_EVENTS| TCL_DONT_WAIT)) {}
    [NSApp _unlockAutoreleasePool];
}

................................................................................

	if (getenv("XCNOSTDIN") != NULL) {
	    close(0);
	    close(1);
	}

	/*
	 * Instantiate our NSApplication object. This needs to be
	 * done before we check whether to open a console window.
	 */

	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	[[NSUserDefaults standardUserDefaults] registerDefaults:
		[NSDictionary dictionaryWithObjectsAndKeys:
				  [NSNumber numberWithBool:YES],
			      @"_NSCanWrapButtonTitles",
................................................................................
		(S_ISCHR(st.st_mode) && st.st_blocks == 0)))) {
	    Tk_InitConsoleChannels(interp);
	    Tcl_RegisterChannel(interp, Tcl_GetStdChannel(TCL_STDIN));
	    Tcl_RegisterChannel(interp, Tcl_GetStdChannel(TCL_STDOUT));
	    Tcl_RegisterChannel(interp, Tcl_GetStdChannel(TCL_STDERR));

	    /*
	     * Only show the console if we don't have a startup script
	     * and tcl_interactive hasn't been set already.
	     */

	    if (Tcl_GetStartupScript(NULL) == NULL) {
		const char *intvar = Tcl_GetVar2(interp,
			"tcl_interactive", NULL, TCL_GLOBAL_ONLY);

		if (intvar == NULL) {







|







 







|
|
<





|
|







 







|
|







 







|
|







41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
...
113
114
115
116
117
118
119
120
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
...
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
...
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
 * called while the pool is locked.
 */
#undef DEBUG_LOCK

@implementation TKApplication(TKInit)
- (void) _resetAutoreleasePool
{
    if ([self poolLock] == 0) {
	[_mainPool drain];
	_mainPool = [NSAutoreleasePool new];
    } else {
#ifdef DEBUG_LOCK
	fprintf(stderr, "Pool is locked with count %d!!!!\n", [self poolLock]);
#endif
    }
................................................................................
    TkMacOSXUseAntialiasedText(_eventInterp, -1);
    TkMacOSXInitCGDrawing(_eventInterp, TRUE, 0);
}

-(void)applicationDidFinishLaunching:(NSNotification *)notification
{
    /*
     * It is not safe to force activation of the NSApp until this method is
     * called. Activating too early can cause the menu bar to be unresponsive.

     */

    [NSApp activateIgnoringOtherApps: YES];

    /*
     * Process events to ensure that the root window is fully initialized. See
     * ticket 56a1823c73.
     */
    
    [NSApp _lockAutoreleasePool];
    while (Tcl_DoOneEvent(TCL_WINDOW_EVENTS| TCL_DONT_WAIT)) {}
    [NSApp _unlockAutoreleasePool];
}

................................................................................

	if (getenv("XCNOSTDIN") != NULL) {
	    close(0);
	    close(1);
	}

	/*
	 * Instantiate our NSApplication object. This needs to be done before
	 * we check whether to open a console window.
	 */

	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	[[NSUserDefaults standardUserDefaults] registerDefaults:
		[NSDictionary dictionaryWithObjectsAndKeys:
				  [NSNumber numberWithBool:YES],
			      @"_NSCanWrapButtonTitles",
................................................................................
		(S_ISCHR(st.st_mode) && st.st_blocks == 0)))) {
	    Tk_InitConsoleChannels(interp);
	    Tcl_RegisterChannel(interp, Tcl_GetStdChannel(TCL_STDIN));
	    Tcl_RegisterChannel(interp, Tcl_GetStdChannel(TCL_STDOUT));
	    Tcl_RegisterChannel(interp, Tcl_GetStdChannel(TCL_STDERR));

	    /*
	     * Only show the console if we don't have a startup script and
	     * tcl_interactive hasn't been set already.
	     */

	    if (Tcl_GetStartupScript(NULL) == NULL) {
		const char *intvar = Tcl_GetVar2(interp,
			"tcl_interactive", NULL, TCL_GLOBAL_ONLY);

		if (intvar == NULL) {

Changes to macosx/tkMacOSXKeyEvent.c.

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
...
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
...
493
494
495
496
497
498
499
500

501
502
503
504
505
506
507
508
509
510
511
512
...
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
#endif
*/
#define NS_KEYLOG 0

static Tk_Window keyboardGrabWinPtr = NULL;
				/* Current keyboard grab window. */
static NSWindow *keyboardGrabNSWindow = nil;
                               /* NSWindow for the current keyboard grab window. */

static NSModalSession modalSession = nil;

static BOOL processingCompose = NO;
static BOOL finishedCompose = NO;

static int caret_x = 0, caret_y = 0, caret_height = 0;

static void setupXEvent(XEvent *xEvent, NSWindow *w, unsigned int state);

static unsigned isFunctionKey(unsigned int code);

unsigned short releaseCode;


#pragma mark TKApplication(TKKeyEvent)

@implementation TKApplication(TKKeyEvent)

- (NSEvent *) tkProcessKeyEvent: (NSEvent *) theEvent
{
#ifdef TK_MAC_DEBUG_EVENTS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, theEvent);
#endif
    NSWindow*	    w;
    NSEventType	    type = [theEvent type];
    NSUInteger modifiers = ([theEvent modifierFlags] &
			    NSDeviceIndependentModifierFlagsMask);
    NSUInteger	    len = 0;
    BOOL	    repeat = NO;
    unsigned short  keyCode = [theEvent keyCode];
    NSString	    *characters = nil, *charactersIgnoringModifiers = nil;
    static NSUInteger savedModifiers = 0;
    static NSMutableArray *nsEvArray;

    if (nsEvArray == nil)
      {
        nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
        processingCompose = NO;
      }

    w = [theEvent window];
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);
    Tk_Window tkwin = (Tk_Window) winPtr;
    XEvent xEvent;

    if (!winPtr) {
................................................................................
#endif
	break;

    default:
	return theEvent; /* Unrecognized key event. */
    }


    /* Create an Xevent to add to the Tk queue. */


    if (!processingCompose) {
        unsigned int state = 0;

        if (modifiers & NSAlphaShiftKeyMask) {
          state |= LockMask;
        }
        if (modifiers & NSShiftKeyMask) {
          state |= ShiftMask;
        }
        if (modifiers & NSControlKeyMask) {
          state |= ControlMask;
        }
        if (modifiers & NSCommandKeyMask) {
          state |= Mod1Mask;		/* command key */
        }
        if (modifiers & NSAlternateKeyMask) {
          state |= Mod2Mask;		/* option key */
        }
        if (modifiers & NSNumericPadKeyMask) {
          state |= Mod3Mask;
        }
        if (modifiers & NSFunctionKeyMask) {
          state |= Mod4Mask;
        }

        /*
         * Events are only received for the front Window on the Macintosh.
	 * So to build an XEvent we look up the Tk window associated to the
	 * Front window. If a different window has a local grab we ignore
	 * the event.
         */

        TkWindow *winPtr = TkMacOSXGetTkWindow(w);
        Tk_Window tkwin = (Tk_Window) winPtr;

	if (tkwin) {
	    TkWindow *grabWinPtr = winPtr->dispPtr->grabWinPtr;

	    if (grabWinPtr &&
		grabWinPtr != winPtr &&
		!winPtr->dispPtr->grabFlags && /* this means the grab is local. */
		grabWinPtr->mainPtr == winPtr->mainPtr) {
		return theEvent;
	    }
	} else {
	    tkwin = (Tk_Window) winPtr->dispPtr->focusPtr;
	}
        if (!tkwin) {
          TkMacOSXDbgMsg("tkwin == NULL");
          return theEvent;  /* Give up. No window for this event. */
        }

        /*
         * If it's a function key, or we have modifiers other than Shift or Alt,
         * pass it straight to Tk.  Otherwise we'll send for input processing.

         */

        int code = (len == 0) ?
          0 : [charactersIgnoringModifiers characterAtIndex: 0];
        if (type != NSKeyDown || isFunctionKey(code)
            || (len > 0 && state & (ControlMask | Mod1Mask | Mod3Mask | Mod4Mask))) {

            XEvent xEvent;
            setupXEvent(&xEvent, w, state);


            if (type == NSFlagsChanged) {
              if (savedModifiers > modifiers) {
                xEvent.xany.type = KeyRelease;
              } else {
                xEvent.xany.type = KeyPress;
              }

              /*
               * Use special '-1' to signify a special keycode to our platform
               * specific code in tkMacOSXKeyboard.c. This is rather like what
               * happens on Windows.
               */

              xEvent.xany.send_event = -1;

              /*
               * Set keycode (which was zero) to the changed modifier
               */

              xEvent.xkey.keycode = (modifiers ^ savedModifiers);
            } else {
              if (type == NSKeyUp || repeat) {
		  xEvent.xany.type = KeyRelease;
              } else {
                xEvent.xany.type = KeyPress;
              }


              /* For command key, take input manager's word so things
                 like dvorak / qwerty layout work. */


              if ((modifiers & NSCommandKeyMask) == NSCommandKeyMask
                  && (modifiers & NSAlternateKeyMask) != NSAlternateKeyMask
                  && len > 0 && !isFunctionKey(code)) {
                // head off keycode-based translation in tkMacOSXKeyboard.c
                xEvent.xkey.nbytes = [characters length]; //len
              }

              if ([characters length] > 0) {
                xEvent.xkey.keycode =
                  (keyCode << 16) | (UInt16) [characters characterAtIndex:0];
                if (![characters getCString:xEvent.xkey.trans_chars
                                  maxLength:XMaxTransChars encoding:NSUTF8StringEncoding]) {
                  /* prevent SF bug 2907388 (crash on some composite chars) */
                  //PENDING: we might not need this anymore
                  TkMacOSXDbgMsg("characters too long");
                  return theEvent;
                }
              }

              if (repeat) {
                Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
                xEvent.xany.type = KeyPress;
                xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
              }
            }
            Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
            savedModifiers = modifiers;
            return theEvent;
          }  /* if send straight to TK */

      }  /* if not processing compose */

    if (type == NSKeyDown) {
        if (NS_KEYLOG)
          fprintf (stderr, "keyDown: %s compose sequence.\n",
                   processingCompose == YES ? "Continue" : "Begin");

        processingCompose = YES;
        [nsEvArray addObject: theEvent];
        [[w contentView] interpretKeyEvents: nsEvArray];
        [nsEvArray removeObject: theEvent];
      }

    savedModifiers = modifiers;

    return theEvent;
}
@end

 

@implementation TKContentView
/* <NSTextInput> implementation (called through interpretKeyEvents:]). */

/* <NSTextInput>: called when done composing;
   NOTE: also called when we delete over working text, followed immed.
         by doCommandBySelector: deleteBackward: */
- (void)insertText: (id)aString
{
  int i, len = [(NSString *)aString length];
  XEvent xEvent;

  if (NS_KEYLOG)
    TKLog (@"insertText '%@'\tlen = %d", aString, len);

  processingCompose = NO;
  finishedCompose = YES;


  /* first, clear any working text */


  if (privateWorkingText != nil)
    [self deleteWorkingText];



  /* now insert the string as keystrokes */


  setupXEvent(&xEvent, [self window], 0);
  xEvent.xany.type = KeyPress;

  for (i =0; i<len; i++)
      {
	  xEvent.xkey.keycode = (UInt16) [aString characterAtIndex: i];
	  [[aString substringWithRange: NSMakeRange(i,1)]
	      getCString: xEvent.xkey.trans_chars
	       maxLength: XMaxTransChars encoding: NSUTF8StringEncoding];
	  xEvent.xkey.nbytes = strlen(xEvent.xkey.trans_chars);
	  xEvent.xany.type = KeyPress;
	  releaseCode =  (UInt16) [aString characterAtIndex: 0];
	  Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
      }
  releaseCode =  (UInt16) [aString characterAtIndex: 0];
}


/* <NSTextInput>: inserts display of composing characters */
- (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
{
  NSString *str = [aString respondsToSelector: @selector (string)] ?
    [aString string] : aString;
  if (NS_KEYLOG)
    TKLog (@"setMarkedText '%@' len =%lu range %lu from %lu", str,
	   (unsigned long) [str length], (unsigned long) selRange.length,
	   (unsigned long) selRange.location);


  if (privateWorkingText != nil)
    [self deleteWorkingText];

  if ([str length] == 0)
    return;


  processingCompose = YES;
  privateWorkingText = [str copy];

  //PENDING: insert workingText underlined
}


- (BOOL)hasMarkedText
{
  return privateWorkingText != nil;
}


- (NSRange)markedRange
{
  NSRange rng = privateWorkingText != nil
    ? NSMakeRange (0, [privateWorkingText length]) : NSMakeRange (NSNotFound, 0);


  if (NS_KEYLOG)
    TKLog (@"markedRange request");

  return rng;
}


- (void)unmarkText
{
  if (NS_KEYLOG)
    TKLog (@"unmark (accept) text");

  [self deleteWorkingText];
  processingCompose = NO;
}


/* used to position char selection windows, etc. */
- (NSRect)firstRectForCharacterRange: (NSRange)theRange
{
  NSRect rect;
  NSPoint pt;

  pt.x = caret_x;
  pt.y = caret_y;

  pt = [self convertPoint: pt toView: nil];
  pt = [[self window] tkConvertPointToScreen: pt];
  pt.y -= caret_height;

  rect.origin = pt;
  rect.size.width = caret_height;
  rect.size.height = caret_height;
  return rect;
}


- (NSInteger)conversationIdentifier
{
  return (NSInteger)self;
}


- (void)doCommandBySelector: (SEL)aSelector
{
  if (NS_KEYLOG)
    TKLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));

  processingCompose = NO;
  if (aSelector == @selector (deleteBackward:))
    {

      /* happens when user backspaces over an ongoing composition:
         throw a 'delete' into the event queue */


      XEvent xEvent;

      setupXEvent(&xEvent, [self window], 0);
      xEvent.xany.type = KeyPress;
      xEvent.xkey.nbytes = 1;
      xEvent.xkey.keycode = (0x33 << 16) | 0x7F;
      xEvent.xkey.trans_chars[0] = 0x7F;
      xEvent.xkey.trans_chars[1] = 0x0;
      Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
    }
}


- (NSArray *)validAttributesForMarkedText
{
  static NSArray *arr = nil;


  if (arr == nil) arr = [NSArray new];

 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
  return arr;
}


- (NSRange)selectedRange
{
  if (NS_KEYLOG)
    TKLog (@"selectedRange request");

  return NSMakeRange (NSNotFound, 0);
}


- (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
{
  if (NS_KEYLOG)
    TKLog (@"characterIndexForPoint request");

  return 0;
}


- (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
{
  static NSAttributedString *str = nil;

  if (str == nil) str = [NSAttributedString new];

  if (NS_KEYLOG)
    TKLog (@"attributedSubstringFromRange request");

  return str;
}
/* End <NSTextInput> impl. */
@end
 

@implementation TKContentView(TKKeyEvent)
/* delete display of composing characters [not in <NSTextInput>] */
- (void)deleteWorkingText
{
  if (privateWorkingText == nil)
    return;

  if (NS_KEYLOG)
    TKLog(@"deleteWorkingText len = %lu\n",
	    (unsigned long)[privateWorkingText length]);

  [privateWorkingText release];
  privateWorkingText = nil;
  processingCompose = NO;

  //PENDING: delete working text
}
@end



/*
 *  Set up basic fields in xevent for keyboard input.
 */
static void
setupXEvent(XEvent *xEvent, NSWindow *w, unsigned int state)
{
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);
    Tk_Window tkwin = (Tk_Window) winPtr;

    if (!winPtr) {
	return;
    }

    memset(xEvent, 0, sizeof(XEvent));
    xEvent->xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
    xEvent->xany.send_event = false;
................................................................................
    Window grab_window,
    Bool owner_events,
    int pointer_mode,
    int keyboard_mode,
    Time time)
{
    keyboardGrabWinPtr = Tk_IdToWindow(display, grab_window);
    TkWindow *captureWinPtr = (TkWindow *)TkMacOSXGetCapture(); 

    if (keyboardGrabWinPtr && captureWinPtr) {
	NSWindow *w = TkMacOSXDrawableWindow(grab_window);
	MacDrawable *macWin = (MacDrawable *) grab_window;

	if (w && macWin->toplevel->winPtr == (TkWindow*) captureWinPtr) {
	    if (modalSession) {
		Tcl_Panic("XGrabKeyboard: already grabbed");
	    }
	    keyboardGrabNSWindow = w;
	    [w retain];
	    modalSession = [NSApp beginModalSessionForWindow:w];
	}
................................................................................
	y += Tk_Y(tkwin);
	tkwin = Tk_Parent(tkwin);
	if (tkwin == NULL) {
	    return;
	}
    }


    /* But adjust for fact that NS uses flipped view. */


    y = Tk_Height(tkwin) - y;

    caret_x = x;
    caret_y = y;
    caret_height = height;
}
 

static unsigned convert_ns_to_X_keysym[] =
{
  NSHomeFunctionKey,            0x50,
  NSLeftArrowFunctionKey,       0x51,
  NSUpArrowFunctionKey,         0x52,
  NSRightArrowFunctionKey,      0x53,
  NSDownArrowFunctionKey,       0x54,
  NSPageUpFunctionKey,          0x55,
  NSPageDownFunctionKey,        0x56,
  NSEndFunctionKey,             0x57,
  NSBeginFunctionKey,           0x58,
  NSSelectFunctionKey,          0x60,
  NSPrintFunctionKey,           0x61,
  NSExecuteFunctionKey,         0x62,
  NSInsertFunctionKey,          0x63,
  NSUndoFunctionKey,            0x65,
  NSRedoFunctionKey,            0x66,
  NSMenuFunctionKey,            0x67,
  NSFindFunctionKey,            0x68,
  NSHelpFunctionKey,            0x6A,
  NSBreakFunctionKey,           0x6B,

  NSF1FunctionKey,              0xBE,
  NSF2FunctionKey,              0xBF,
  NSF3FunctionKey,              0xC0,
  NSF4FunctionKey,              0xC1,
  NSF5FunctionKey,              0xC2,
  NSF6FunctionKey,              0xC3,
  NSF7FunctionKey,              0xC4,
  NSF8FunctionKey,              0xC5,
  NSF9FunctionKey,              0xC6,
  NSF10FunctionKey,             0xC7,
  NSF11FunctionKey,             0xC8,
  NSF12FunctionKey,             0xC9,
  NSF13FunctionKey,             0xCA,
  NSF14FunctionKey,             0xCB,
  NSF15FunctionKey,             0xCC,
  NSF16FunctionKey,             0xCD,
  NSF17FunctionKey,             0xCE,
  NSF18FunctionKey,             0xCF,
  NSF19FunctionKey,             0xD0,
  NSF20FunctionKey,             0xD1,
  NSF21FunctionKey,             0xD2,
  NSF22FunctionKey,             0xD3,
  NSF23FunctionKey,             0xD4,
  NSF24FunctionKey,             0xD5,

  NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
  NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
  NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */

  NSTabCharacter,		0x09,
  0x19,				0x09,  /* left tab->regular since pass shift */
  NSCarriageReturnCharacter,	0x0D,
  NSNewlineCharacter,		0x0D,
  NSEnterCharacter,		0x8D,

  0x1B,				0x1B   /* escape */
};


static unsigned isFunctionKey(unsigned code)


{
    const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
                                / sizeof (convert_ns_to_X_keysym[0]));
  unsigned keysym;

  for (keysym = 0; keysym < last_keysym; keysym += 2)
    if (code == convert_ns_to_X_keysym[keysym])
      return 0xFF00 | convert_ns_to_X_keysym[keysym+1];


  return 0;
 }
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */







|
>

<


<


|
>
|













|
|


|
|
|
|



|
<


|







 







>
|
>
>




|


|


|


|


|


|


|



|
|
|
<







>
|
|
|
|






|
|



|
|
>


|
|

|
<

<

>

|
|
|
|
|

|
|
|
|
|

|

|
|
|

|

|
|
|
|
|

>
|
|
>
>
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|




|
<
|


|
|
|
>




|


<



<










|
|

|
|
>
|
|

>
|
>
>
|
|
|
>
>
|
>
>
|
|

|
<
|
|


|
|
|
|
|
|






|
|
|
|
|
|
|
>
|
|
>
|
|
|
>
|
|

|





|





|
|
>
>
|
|
>
|





|
|
>
|
|






|
|

|
|

|
|
|

|
|
|
|





|





|
|
>
|
|
<
>
|
|
>
>
|
>
|
|
|
|
|
|
|






|
>
>
|
>
|
|





|
|
>
|





|
|
>
|





|
>
|
>
|
|
>
|









|
|
>
|
|
|
>
|
|
|

|



<
<

|






>







 







|
>




|







 







>
|
>
>










|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|

|
|
|
|
|

|



|
>
>

|
|
|
>
|
|
|
>
>
|
|









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
...
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
...
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
...
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
#endif
*/
#define NS_KEYLOG 0

static Tk_Window keyboardGrabWinPtr = NULL;
				/* Current keyboard grab window. */
static NSWindow *keyboardGrabNSWindow = nil;
				/* NSWindow for the current keyboard grab
				 * window. */
static NSModalSession modalSession = nil;

static BOOL processingCompose = NO;
static BOOL finishedCompose = NO;

static int caret_x = 0, caret_y = 0, caret_height = 0;

static void		setupXEvent(XEvent *xEvent, NSWindow *w,
			    unsigned int state);
static unsigned		isFunctionKey(unsigned int code);

unsigned short releaseCode;


#pragma mark TKApplication(TKKeyEvent)

@implementation TKApplication(TKKeyEvent)

- (NSEvent *) tkProcessKeyEvent: (NSEvent *) theEvent
{
#ifdef TK_MAC_DEBUG_EVENTS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, theEvent);
#endif
    NSWindow *w;
    NSEventType type = [theEvent type];
    NSUInteger modifiers = ([theEvent modifierFlags] &
			    NSDeviceIndependentModifierFlagsMask);
    NSUInteger len = 0;
    BOOL repeat = NO;
    unsigned short keyCode = [theEvent keyCode];
    NSString *characters = nil, *charactersIgnoringModifiers = nil;
    static NSUInteger savedModifiers = 0;
    static NSMutableArray *nsEvArray;

    if (nsEvArray == nil) {

        nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
        processingCompose = NO;
    }

    w = [theEvent window];
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);
    Tk_Window tkwin = (Tk_Window) winPtr;
    XEvent xEvent;

    if (!winPtr) {
................................................................................
#endif
	break;

    default:
	return theEvent; /* Unrecognized key event. */
    }

    /*
     * Create an Xevent to add to the Tk queue.
     */

    if (!processingCompose) {
        unsigned int state = 0;

        if (modifiers & NSAlphaShiftKeyMask) {
	    state |= LockMask;
        }
        if (modifiers & NSShiftKeyMask) {
	    state |= ShiftMask;
        }
        if (modifiers & NSControlKeyMask) {
	    state |= ControlMask;
        }
        if (modifiers & NSCommandKeyMask) {
	    state |= Mod1Mask;		/* command key */
        }
        if (modifiers & NSAlternateKeyMask) {
	    state |= Mod2Mask;		/* option key */
        }
        if (modifiers & NSNumericPadKeyMask) {
	    state |= Mod3Mask;
        }
        if (modifiers & NSFunctionKeyMask) {
	    state |= Mod4Mask;
        }

        /*
         * Events are only received for the front Window on the Macintosh. So
	 * to build an XEvent we look up the Tk window associated to the Front
	 * window. If a different window has a local grab we ignore the event.

         */

        TkWindow *winPtr = TkMacOSXGetTkWindow(w);
        Tk_Window tkwin = (Tk_Window) winPtr;

	if (tkwin) {
	    TkWindow *grabWinPtr = winPtr->dispPtr->grabWinPtr;

	    if (grabWinPtr
		    && grabWinPtr != winPtr
		    && !winPtr->dispPtr->grabFlags /* this means the grab is local. */
		    && grabWinPtr->mainPtr == winPtr->mainPtr) {
		return theEvent;
	    }
	} else {
	    tkwin = (Tk_Window) winPtr->dispPtr->focusPtr;
	}
        if (!tkwin) {
	    TkMacOSXDbgMsg("tkwin == NULL");
	    return theEvent;  /* Give up. No window for this event. */
        }

        /*
         * If it's a function key, or we have modifiers other than Shift or
         * Alt, pass it straight to Tk.  Otherwise we'll send for input
         * processing.
         */

        int code = (len == 0) ? 0 :
		[charactersIgnoringModifiers characterAtIndex: 0];
        if (type != NSKeyDown || isFunctionKey(code)
		|| (len > 0 && state & (ControlMask | Mod1Mask | Mod3Mask | Mod4Mask))) {

            XEvent xEvent;


            setupXEvent(&xEvent, w, state);
            if (type == NSFlagsChanged) {
		if (savedModifiers > modifiers) {
		    xEvent.xany.type = KeyRelease;
		} else {
		    xEvent.xany.type = KeyPress;
		}

		/*
		 * Use special '-1' to signify a special keycode to our
		 * platform specific code in tkMacOSXKeyboard.c. This is rather
		 * like what happens on Windows.
		 */

		xEvent.xany.send_event = -1;

		/*
		 * Set keycode (which was zero) to the changed modifier
		 */

		xEvent.xkey.keycode = (modifiers ^ savedModifiers);
            } else {
		if (type == NSKeyUp || repeat) {
		    xEvent.xany.type = KeyRelease;
		} else {
		    xEvent.xany.type = KeyPress;
		}

		/*
		 * For command key, take input manager's word so things like
		 * dvorak / qwerty layout work.
		 */

		if ((modifiers & NSCommandKeyMask) == NSCommandKeyMask
			&& (modifiers & NSAlternateKeyMask) != NSAlternateKeyMask
			&& len > 0 && !isFunctionKey(code)) {
		    // head off keycode-based translation in tkMacOSXKeyboard.c
		    xEvent.xkey.nbytes = [characters length]; //len
		}

		if ([characters length] > 0) {
		    xEvent.xkey.keycode = (keyCode << 16) |
			    (UInt16) [characters characterAtIndex:0];
		    if (![characters getCString:xEvent.xkey.trans_chars
			    maxLength:XMaxTransChars encoding:NSUTF8StringEncoding]) {
			/* prevent SF bug 2907388 (crash on some composite chars) */
			//PENDING: we might not need this anymore
			TkMacOSXDbgMsg("characters too long");
			return theEvent;
		    }
		}

		if (repeat) {
		    Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
		    xEvent.xany.type = KeyPress;
		    xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
		}
            }
            Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
            savedModifiers = modifiers;
            return theEvent;
	}  /* if send straight to TK */

    }  /* if not processing compose */

    if (type == NSKeyDown) {
        if (NS_KEYLOG) {
	    TKLog(@"keyDown: %s compose sequence.\n",
		    processingCompose == YES ? "Continue" : "Begin");
	}
        processingCompose = YES;
        [nsEvArray addObject: theEvent];
        [[w contentView] interpretKeyEvents: nsEvArray];
        [nsEvArray removeObject: theEvent];
    }

    savedModifiers = modifiers;

    return theEvent;
}
@end

 

@implementation TKContentView
/* <NSTextInput> implementation (called through interpretKeyEvents:]). */

/* <NSTextInput>: called when done composing;
   NOTE: also called when we delete over working text, followed immed.
         by doCommandBySelector: deleteBackward: */
- (void)insertText: (id)aString
{
    int i, len = [(NSString *) aString length];
    XEvent xEvent;

    if (NS_KEYLOG) {
	TKLog(@"insertText '%@'\tlen = %d", aString, len);
    }
    processingCompose = NO;
    finishedCompose = YES;

    /*
     * First, clear any working text.
     */

    if (privateWorkingText != nil) {
	[self deleteWorkingText];
    }

    /*
     * Now insert the string as keystrokes.
     */

    setupXEvent(&xEvent, [self window], 0);
    xEvent.xany.type = KeyPress;

    for (i =0; i<len; i++) {

	xEvent.xkey.keycode = (UInt16) [aString characterAtIndex: i];
	[[aString substringWithRange: NSMakeRange(i,1)]
	      getCString: xEvent.xkey.trans_chars
	       maxLength: XMaxTransChars encoding: NSUTF8StringEncoding];
	xEvent.xkey.nbytes = strlen(xEvent.xkey.trans_chars);
	xEvent.xany.type = KeyPress;
	releaseCode = (UInt16) [aString characterAtIndex: 0];
	Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
    }
    releaseCode = (UInt16) [aString characterAtIndex: 0];
}


/* <NSTextInput>: inserts display of composing characters */
- (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
{
    NSString *str = [aString respondsToSelector: @selector (string)] ?
	[aString string] : aString;
    if (NS_KEYLOG) {
	TKLog(@"setMarkedText '%@' len =%lu range %lu from %lu", str,
	      (unsigned long) [str length], (unsigned long) selRange.length,
	      (unsigned long) selRange.location);
    }

    if (privateWorkingText != nil) {
	[self deleteWorkingText];
    }
    if ([str length] == 0) {
	return;
    }

    processingCompose = YES;
    privateWorkingText = [str copy];

    //PENDING: insert workingText underlined
}


- (BOOL)hasMarkedText
{
    return privateWorkingText != nil;
}


- (NSRange)markedRange
{
    NSRange rng = privateWorkingText != nil
	? NSMakeRange(0, [privateWorkingText length])
	: NSMakeRange(NSNotFound, 0);

    if (NS_KEYLOG) {
	TKLog(@"markedRange request");
    }
    return rng;
}


- (void)unmarkText
{
    if (NS_KEYLOG) {
	TKLog(@"unmark (accept) text");
    }
    [self deleteWorkingText];
    processingCompose = NO;
}


/* used to position char selection windows, etc. */
- (NSRect)firstRectForCharacterRange: (NSRange)theRange
{
    NSRect rect;
    NSPoint pt;

    pt.x = caret_x;
    pt.y = caret_y;

    pt = [self convertPoint: pt toView: nil];
    pt = [[self window] tkConvertPointToScreen: pt];
    pt.y -= caret_height;

    rect.origin = pt;
    rect.size.width = caret_height;
    rect.size.height = caret_height;
    return rect;
}


- (NSInteger)conversationIdentifier
{
    return (NSInteger) self;
}


- (void)doCommandBySelector: (SEL)aSelector
{
    if (NS_KEYLOG) {
	TKLog(@"doCommandBySelector: %@", NSStringFromSelector(aSelector));
    }
    processingCompose = NO;
    if (aSelector == @selector (deleteBackward:)) {

	/*
	 * Happens when user backspaces over an ongoing composition:
	 * throw a 'delete' into the event queue.
	 */

	XEvent xEvent;

	setupXEvent(&xEvent, [self window], 0);
	xEvent.xany.type = KeyPress;
	xEvent.xkey.nbytes = 1;
	xEvent.xkey.keycode = (0x33 << 16) | 0x7F;
	xEvent.xkey.trans_chars[0] = 0x7F;
	xEvent.xkey.trans_chars[1] = 0x0;
	Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
    }
}


- (NSArray *)validAttributesForMarkedText
{
    static NSArray *arr = nil;

    if (arr == nil) {
	arr = [NSArray new];
    }
    /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
    return arr;
}


- (NSRange)selectedRange
{
    if (NS_KEYLOG) {
	TKLog(@"selectedRange request");
    }
    return NSMakeRange(NSNotFound, 0);
}


- (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
{
    if (NS_KEYLOG) {
	TKLog(@"characterIndexForPoint request");
    }
    return 0;
}


- (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
{
    static NSAttributedString *str = nil;
    if (str == nil) {
	str = [NSAttributedString new];
    }
    if (NS_KEYLOG) {
	TKLog(@"attributedSubstringFromRange request");
    }
    return str;
}
/* End <NSTextInput> impl. */
@end
 

@implementation TKContentView(TKKeyEvent)
/* delete display of composing characters [not in <NSTextInput>] */
- (void)deleteWorkingText
{
    if (privateWorkingText == nil) {
	return;
    }
    if (NS_KEYLOG) {
	TKLog(@"deleteWorkingText len = %lu\n",
	      (unsigned long)[privateWorkingText length]);
    }
    [privateWorkingText release];
    privateWorkingText = nil;
    processingCompose = NO;

    //PENDING: delete working text
}
@end



/*
 * Set up basic fields in xevent for keyboard input.
 */
static void
setupXEvent(XEvent *xEvent, NSWindow *w, unsigned int state)
{
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);
    Tk_Window tkwin = (Tk_Window) winPtr;

    if (!winPtr) {
	return;
    }

    memset(xEvent, 0, sizeof(XEvent));
    xEvent->xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
    xEvent->xany.send_event = false;
................................................................................
    Window grab_window,
    Bool owner_events,
    int pointer_mode,
    int keyboard_mode,
    Time time)
{
    keyboardGrabWinPtr = Tk_IdToWindow(display, grab_window);
    TkWindow *captureWinPtr = (TkWindow *) TkMacOSXGetCapture(); 

    if (keyboardGrabWinPtr && captureWinPtr) {
	NSWindow *w = TkMacOSXDrawableWindow(grab_window);
	MacDrawable *macWin = (MacDrawable *) grab_window;

	if (w && macWin->toplevel->winPtr == (TkWindow *) captureWinPtr) {
	    if (modalSession) {
		Tcl_Panic("XGrabKeyboard: already grabbed");
	    }
	    keyboardGrabNSWindow = w;
	    [w retain];
	    modalSession = [NSApp beginModalSessionForWindow:w];
	}
................................................................................
	y += Tk_Y(tkwin);
	tkwin = Tk_Parent(tkwin);
	if (tkwin == NULL) {
	    return;
	}
    }

    /*
     * But adjust for fact that NS uses flipped view.
     */

    y = Tk_Height(tkwin) - y;

    caret_x = x;
    caret_y = y;
    caret_height = height;
}
 

static unsigned convert_ns_to_X_keysym[] =
{
    NSHomeFunctionKey,		0x50,
    NSLeftArrowFunctionKey,	0x51,
    NSUpArrowFunctionKey,	0x52,
    NSRightArrowFunctionKey,	0x53,
    NSDownArrowFunctionKey,	0x54,
    NSPageUpFunctionKey,	0x55,
    NSPageDownFunctionKey,	0x56,
    NSEndFunctionKey,		0x57,
    NSBeginFunctionKey,		0x58,
    NSSelectFunctionKey,	0x60,
    NSPrintFunctionKey,		0x61,
    NSExecuteFunctionKey,	0x62,
    NSInsertFunctionKey,	0x63,
    NSUndoFunctionKey,		0x65,
    NSRedoFunctionKey,		0x66,
    NSMenuFunctionKey,		0x67,
    NSFindFunctionKey,		0x68,
    NSHelpFunctionKey,		0x6A,
    NSBreakFunctionKey,		0x6B,

    NSF1FunctionKey,		0xBE,
    NSF2FunctionKey,		0xBF,
    NSF3FunctionKey,		0xC0,
    NSF4FunctionKey,		0xC1,
    NSF5FunctionKey,		0xC2,
    NSF6FunctionKey,		0xC3,
    NSF7FunctionKey,		0xC4,
    NSF8FunctionKey,		0xC5,
    NSF9FunctionKey,		0xC6,
    NSF10FunctionKey,		0xC7,
    NSF11FunctionKey,		0xC8,
    NSF12FunctionKey,		0xC9,
    NSF13FunctionKey,		0xCA,
    NSF14FunctionKey,		0xCB,
    NSF15FunctionKey,		0xCC,
    NSF16FunctionKey,		0xCD,
    NSF17FunctionKey,		0xCE,
    NSF18FunctionKey,		0xCF,
    NSF19FunctionKey,		0xD0,
    NSF20FunctionKey,		0xD1,
    NSF21FunctionKey,		0xD2,
    NSF22FunctionKey,		0xD3,
    NSF23FunctionKey,		0xD4,
    NSF24FunctionKey,		0xD5,

    NSBackspaceCharacter,	0x08,  /* 8: Not on some KBs. */
    NSDeleteCharacter,		0xFF,  /* 127: Big 'delete' key upper right. */
    NSDeleteFunctionKey,	0x9F,  /* 63272: Del forw key off main array. */

    NSTabCharacter,		0x09,
    0x19,			0x09,  /* left tab->regular since pass shift */
    NSCarriageReturnCharacter,	0x0D,
    NSNewlineCharacter,		0x0D,
    NSEnterCharacter,		0x8D,

    0x1B,			0x1B   /* escape */
};


static unsigned
isFunctionKey(
    unsigned code)
{
    const unsigned last_keysym = (sizeof(convert_ns_to_X_keysym)
                                / sizeof(convert_ns_to_X_keysym[0]));
    unsigned keysym;

    for (keysym = 0; keysym < last_keysym; keysym += 2) {
	if (code == convert_ns_to_X_keysym[keysym]) {
	    return 0xFF00 | convert_ns_to_X_keysym[keysym + 1];
	}
    }
    return 0;
}
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */

Changes to macosx/tkMacOSXMenu.c.

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
...
248
249
250
251
252
253
254
255
256
257
258
259
260
261

262
263
264
265
266
267
268
269
270
...
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
...
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
...
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
...
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
...
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
...
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
...
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
...
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
....
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
....
1291
1292
1293
1294
1295
1296
1297

1298
1299
1300
1301
1302
1303
1304

1305
1306
1307
1308
1309
1310
1311
....
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
....
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
....
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
....
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
....
1853
1854
1855
1856
1857
1858
1859
1860
1861

1862
1863
1864
1865
1866
1867
1868
1869
    [super insertItem:newItem atIndex:index + _tkOffset];
    _tkItemCount++;
}

- (void) insertItem: (NSMenuItem *) newItem atIndex: (NSInteger) index
{
    if (_tkMenu && index >= 0) {
	if ((NSUInteger)index <= _tkOffset) {
	    _tkOffset++;
	} else {
	    NSAssert((NSUInteger)index >= _tkItemCount + _tkOffset,
		    @"Cannot insert in the middle of Tk menu");
	}
    }
    [super insertItem:newItem atIndex:index];
}

- (void) removeItemAtIndex: (NSInteger) index
{
    if (_tkMenu && index >= 0) {
	if ((NSUInteger)index < _tkOffset) {
	    _tkOffset--;
	} else if ((NSUInteger)index < _tkItemCount + _tkOffset) {
	    _tkItemCount--;
	}
    }
    [super removeItemAtIndex:index];
}

- (NSMenuItem *) newTkMenuItem: (TkMenuEntry *) mePtr
{
    NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@""
	    action:@selector(tkMenuItemInvoke:) keyEquivalent:@""];

    [menuItem setTarget:self];
    [menuItem setTag:(NSInteger)mePtr];
    return menuItem;
}
@end

@implementation TKMenu(TKMenuActions)

- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
................................................................................
     * With the delegate matching key equivalents, when a menu action is sent
     * in response to a key equivalent, the sender is the whole menu and not the
     * specific menu item.  We use this to ignore key equivalents for Tk
     * menus (as Tk handles them directly via bindings).
     */

    if ([sender isKindOfClass:[NSMenuItem class]]) {
	NSMenuItem *menuItem = (NSMenuItem *)sender;
	TkMenu *menuPtr = (TkMenu *)_tkMenu;
	TkMenuEntry *mePtr = (TkMenuEntry *)[menuItem tag];

	if (menuPtr && mePtr) {
	    Tcl_Interp *interp = menuPtr->interp;


	    /*Add time for errors to fire if necessary. This is sub-optimal
	     *but avoids issues with Tcl/Cocoa event loop integration.
	     */

	    //Tcl_Sleep(100);
	    Tcl_Preserve(interp);
	    Tcl_Preserve(menuPtr);

	    int result = TkInvokeMenu(interp, menuPtr, mePtr->index);
................................................................................
	 * Command-Shift-? has not been allowed as a keyboard equivalent since
	 * the first aqua port, for some mysterious reason.
	 */

	return NO;
    } else if (modifiers == (NSControlKeyMask | NSShiftKeyMask) &&
	    [event keyCode] == 48) {


	/* Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used
	 * to select window tabs.  But for some even more mysterious reason the
	 * Control-Shift-Tab event has character 0x19 = NSBackTabCharacter
	 * rather than 0x09 = NSTabCharacter.  At the same time, the
	 * keyEquivalent must be \0x09 in order for it to be displayed
	 * correctly in the menu. This makes it impossible for the standard
	 * "Select Previous Tab" to work correctly, unless we intervene.
	 */

	key = @"\t";
    } else if (([event modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask) {

	/*
	 * If the command modifier is set, use the full character string so
	 * things like the dvorak / qwerty layout will work.
	 */

	key = [event characters];
    }
................................................................................
	attributes = TkMacOSXNSFontAttributesForFont(Tk_GetFontFromObj(
		mePtr->menuPtr->tkwin, fontPtr));
	if (gc->foreground != defaultFg || gc->background != defaultBg) {
	    NSColor *color = TkMacOSXGetNSColor(gc,
		    gc->foreground!=defaultFg? gc->foreground:gc->background);

	    attributes = [[attributes mutableCopy] autorelease];
	    [(NSMutableDictionary *)attributes setObject:color
		    forKey:NSForegroundColorAttributeName];
	}
	if (attributes) {
	    attributedTitle = [[[NSAttributedString alloc]
		    initWithString:title attributes:attributes] autorelease];
	}
    }
................................................................................
		 */

		submenu = nil;
	    } else {
		[submenu setTitle:title];

    		if ([menuItem isEnabled]) {

		  /* This menuItem might have been previously disabled (XXX:
		     track this), which would have disabled entries; we must
		     re-enable the entries here. */


		  int i = 0;
		  NSArray *itemArray = [submenu itemArray];

		  for (NSMenuItem *item in itemArray) {
		    TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i];


		    /* Work around an apparent bug where itemArray can have
                      more items than the menu's entries[] array. */


                    if (i >= (int)menuRefPtr->menuPtr->numEntries) break;


		    [item setEnabled: !(submePtr->state == ENTRY_DISABLED)];
		    i++;
		  }
		}

	    }
	}
    }
    [menuItem setSubmenu:submenu];

    return TCL_OK;
}
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpPostMenu --
 *
 *	Posts a menu on the screen. If entry is < 0 then the menu is
 *      drawn so its top left corner is located at the point with
 *      screen coordinates (x, y).  Otherwise the top left corner of
 *      the specified entry is located at that point.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	The menu is posted and handled.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpPostTearoffMenu --
 *
 *	Tearoff menus are not supported on the Mac.  This placeholder
 *      function, which is simply a copy of the unix function, posts a
 *      completely useless window with a black background on the screen. If
 *      entry is < 0 then the window is positioned so that its top left corner
 *      is located at the point with screen coordinates (x, y).  Otherwise the
 *      window position is offset so that top left corner of the specified
 *      entry would be located at that point, if there actually were a menu.
 *
 *      Mac menus steal all mouse or keyboard input from the application until
 *      the menu is dismissed, with or without a selection, by a mouse or key
 *      event.  Posting a Mac menu in a regression test will cause the test to
 *      halt waiting for user input.  This is why the TkpPostMenu function is
 *      not being used as the placeholder.
 *
................................................................................
    int x, int y, int index)	/* The screen coordinates where the top left
				 * corner of the menu, or of the specified
				 * entry, will be located. */
{
    int vRootX, vRootY, vRootWidth, vRootHeight;
    int result;

    if (index >= (int)menuPtr->numEntries) {
	index = menuPtr->numEntries - 1;
    }
    if (index >= 0) {
	y -= menuPtr->entries[index]->y;
    }

    TkActivateMenuEntry(menuPtr, -1);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpSetMainMenubar --
 *
 *	Puts the menu associated with a window into the menubar. Should only
 *	be called when the window is in front.
 *
 *      This is a no-op on all other platforms.  On OS X it is a no-op when
 *      passed a NULL menuName or a nonexistent menuName, with an exception
 *      for the first call in a new interpreter.  In that special case, passing a
 *      NULL menuName installs the default menu.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menubar may be changed.
................................................................................

    /*
     * We will be called when an embedded window receives an ActivationNotify
     * event, but we should not change the menubar in that case.
     */

    if (Tk_IsEmbedded(winPtr)) {
	    return;
	}

    if (menuName) {
	Tk_Window menubar = NULL;

	if (winPtr->wmInfoPtr &&
	    winPtr->wmInfoPtr->menuPtr &&
	    winPtr->wmInfoPtr->menuPtr->masterMenuPtr) {
	    menubar = winPtr->wmInfoPtr->menuPtr->masterMenuPtr->tkwin;
	}

	/*
	 * Attempt to find the NSMenu directly.  If that fails, ask Tk to find it.

	 */

	if (menubar != NULL && strcmp(menuName, Tk_PathName(menubar)) == 0) {
	    menu = (TKMenu *) winPtr->wmInfoPtr->menuPtr->platformData;
	} else {
	    TkMenuReferences *menuRefPtr = TkFindMenuReferences(interp,
		    menuName);

	    if (menuRefPtr && menuRefPtr->menuPtr &&
		    menuRefPtr->menuPtr->platformData) {
		menu = (TKMenu *) menuRefPtr->menuPtr->platformData;
	    }
	}
    }

    /*
     * If we couldn't find a menu, do nothing unless the window belongs
     * to a different application.  In that case, install the default
     * menubar.
     */

    if (menu || interp != currentInterp) {
	[NSApp tkSetMainMenu:menu];
    }
    currentInterp = interp;
}
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * CheckForSpecialMenu --
 *
 *	Given a menu, check to see whether or not it is a cascade in a menubar
 *	with one of the special names ".apple", ".help" or ".window".  If it
 *	is, the entry that points to this menu will be marked.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Will set entryFlags appropriately.
 *
................................................................................
    int entryWidth, maxIndicatorSpace, borderWidth, activeBorderWidth;
    TkMenuEntry *mePtr;
    int haveAccel = 0;

    /*
     * Do nothing if this menu is a clone.
     */

    if (menuPtr->tkwin == NULL || menuPtr->masterMenuPtr != menuPtr) {
	return;
    }

    menuSize = [(NSMenu *)menuPtr->platformData size];
    Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr,
	    &borderWidth);
    Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->activeBorderWidthPtr,
	    &activeBorderWidth);
    x = y = borderWidth;
    windowHeight = maxWidth = 0;
    maxIndicatorSpace = 0;

    /*
     * On the Mac especially, getting font metrics can be quite slow, so we
     * want to do it intelligently. We are going to precalculate them and pass
     * them down to all of the measuring and drawing routines. We will measure
     * the font metrics of the menu once. If an entry does not have its own
     * font set, then we give the geometry/drawing routines the menu's font
     * and metrics. If an entry has its own font, we will measure that font
     * and give all of the geometry/drawing the entry's font and metrics.
     */

    menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
    Tk_GetFontMetrics(menuFont, &menuMetrics);
    menuModifierCharWidth = ModifierCharWidth(menuFont);

    for (i = 0; i < (int)menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->type == CASCADE_ENTRY || mePtr->accelLength > 0) {
	    haveAccel = 1;
	    break;
	}
    }

    for (i = 0; i < (int)menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->type == TEAROFF_ENTRY) {
	    continue;
	}
	if (mePtr->fontPtr == NULL) {
	    tkfont = menuFont;
	    fmPtr = &menuMetrics;
................................................................................
	     * (if any), and the width of the accelerator to be displayed to
	     * the right of the label (if any). These sizes depend, of course,
	     * on the type of the entry.
	     */

	    NSMenuItem *menuItem = (NSMenuItem *) mePtr->platformEntryData;
	    int haveImage = 0, width = 0, height = 0;

	    if (mePtr->image) {
		Tk_SizeOfImage(mePtr->image, &width, &height);
		haveImage = 1;
		height += 2; /* tweak */
	    } else if (mePtr->bitmapPtr) {
		Pixmap bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin,
			mePtr->bitmapPtr);

		Tk_SizeOfBitmap(menuPtr->display, bitmap, &width, &height);
		haveImage = 1;
		height += 2; /* tweak */
	    }
	    if (!haveImage || (mePtr->compound != COMPOUND_NONE)) {
		NSAttributedString *attrTitle = [menuItem attributedTitle];
		NSSize size;
................................................................................
    NSMenuItem *menuItem)
{
    TkMenu *menuPtr = [menu tkMenu];

    if (menuPtr) {
	int index = [menu tkIndexOfItem:menuItem];

	if (index < 0 || index >= (int)menuPtr->numEntries ||
		(menuPtr->entries[index])->state == ENTRY_DISABLED) {
	    TkActivateMenuEntry(menuPtr, -1);
	} else {
	    TkActivateMenuEntry(menuPtr, index);
	    MenuSelectEvent(menuPtr);
	    return true;
	}
................................................................................
void
RecursivelyClearActiveMenu(
    TkMenu *menuPtr)		/* The menu to reset. */
{
    int i;

    TkActivateMenuEntry(menuPtr, -1);
    for (i = 0; i < (int)menuPtr->numEntries; i++) {
	TkMenuEntry *mePtr = menuPtr->entries[i];

	if (mePtr->type == CASCADE_ENTRY
		&& (mePtr->childMenuRefPtr != NULL)
		&& (mePtr->childMenuRefPtr->menuPtr != NULL)) {
	    RecursivelyClearActiveMenu(mePtr->childMenuRefPtr->menuPtr);
	}
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXUseID --
 *
 *	Take the ID out of the available list for new menus. Used by the
 *	default menu bar's menus so that they do not get created at the tk
 *	level. See TkMacOSXGetNewMenuID for more information.
 *
 * Results:
 *	Returns TCL_OK if the id was not in use. Returns TCL_ERROR if the id
 *	was in use.
 *
 * Side effects:
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDispatchMenuEvent --
 *
 *	Given a menu id and an item, dispatches the command associated with
 *	it.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands for the event are scheduled for execution at idle time.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetHelpMenuItemCount --
 *
 *	Has to be called after the first call to InsertMenu. Sets up the
 *	global variable for the number of items in the unmodified help menu.

 *	NB. Nobody uses this any more, since you can get the number of system
 *	help items from HMGetHelpMenu trivially. But it is in the stubs
 *	table...
 *
 * Results:
 *	None.
 *
 * Side effects:







|


|









|

|












|







 







|
|
|




>
|
|







 







<
>
|










<







 







|







 







>
|
|
|
>
>
|
|
>
|
|
>
>
|
|
>
>
|
>
>
|
|
|

<







 







|
|
|
|







 







|
|
|
|
|
|
|







 







|







 







|
|


|
|







 







|
|



>

|
|




|
>







>








|
|
<







 







|
|







 







>




|













|
|
|






|







|







 







>







>







 







|







 







|







 







|







 







|
<







 







|
|
>
|







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
...
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
...
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
...
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
...
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
...
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
...
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
...
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
...
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
...
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
....
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
....
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
....
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
....
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
....
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
....
1816
1817
1818
1819
1820
1821
1822
1823

1824
1825
1826
1827
1828
1829
1830
....
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
    [super insertItem:newItem atIndex:index + _tkOffset];
    _tkItemCount++;
}

- (void) insertItem: (NSMenuItem *) newItem atIndex: (NSInteger) index
{
    if (_tkMenu && index >= 0) {
	if ((NSUInteger) index <= _tkOffset) {
	    _tkOffset++;
	} else {
	    NSAssert((NSUInteger) index >= _tkItemCount + _tkOffset,
		    @"Cannot insert in the middle of Tk menu");
	}
    }
    [super insertItem:newItem atIndex:index];
}

- (void) removeItemAtIndex: (NSInteger) index
{
    if (_tkMenu && index >= 0) {
	if ((NSUInteger) index < _tkOffset) {
	    _tkOffset--;
	} else if ((NSUInteger) index < _tkItemCount + _tkOffset) {
	    _tkItemCount--;
	}
    }
    [super removeItemAtIndex:index];
}

- (NSMenuItem *) newTkMenuItem: (TkMenuEntry *) mePtr
{
    NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@""
	    action:@selector(tkMenuItemInvoke:) keyEquivalent:@""];

    [menuItem setTarget:self];
    [menuItem setTag:(NSInteger) mePtr];
    return menuItem;
}
@end

@implementation TKMenu(TKMenuActions)

- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
................................................................................
     * With the delegate matching key equivalents, when a menu action is sent
     * in response to a key equivalent, the sender is the whole menu and not the
     * specific menu item.  We use this to ignore key equivalents for Tk
     * menus (as Tk handles them directly via bindings).
     */

    if ([sender isKindOfClass:[NSMenuItem class]]) {
	NSMenuItem *menuItem = (NSMenuItem *) sender;
	TkMenu *menuPtr = (TkMenu *) _tkMenu;
	TkMenuEntry *mePtr = (TkMenuEntry *) [menuItem tag];

	if (menuPtr && mePtr) {
	    Tcl_Interp *interp = menuPtr->interp;

	    /*
	     * Add time for errors to fire if necessary. This is sub-optimal
	     * but avoids issues with Tcl/Cocoa event loop integration.
	     */

	    //Tcl_Sleep(100);
	    Tcl_Preserve(interp);
	    Tcl_Preserve(menuPtr);

	    int result = TkInvokeMenu(interp, menuPtr, mePtr->index);
................................................................................
	 * Command-Shift-? has not been allowed as a keyboard equivalent since
	 * the first aqua port, for some mysterious reason.
	 */

	return NO;
    } else if (modifiers == (NSControlKeyMask | NSShiftKeyMask) &&
	    [event keyCode] == 48) {

	/*
	 * Starting with OSX 10.12 Control-Tab and Control-Shift-Tab are used
	 * to select window tabs.  But for some even more mysterious reason the
	 * Control-Shift-Tab event has character 0x19 = NSBackTabCharacter
	 * rather than 0x09 = NSTabCharacter.  At the same time, the
	 * keyEquivalent must be \0x09 in order for it to be displayed
	 * correctly in the menu. This makes it impossible for the standard
	 * "Select Previous Tab" to work correctly, unless we intervene.
	 */

	key = @"\t";
    } else if (([event modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask) {

	/*
	 * If the command modifier is set, use the full character string so
	 * things like the dvorak / qwerty layout will work.
	 */

	key = [event characters];
    }
................................................................................
	attributes = TkMacOSXNSFontAttributesForFont(Tk_GetFontFromObj(
		mePtr->menuPtr->tkwin, fontPtr));
	if (gc->foreground != defaultFg || gc->background != defaultBg) {
	    NSColor *color = TkMacOSXGetNSColor(gc,
		    gc->foreground!=defaultFg? gc->foreground:gc->background);

	    attributes = [[attributes mutableCopy] autorelease];
	    [(NSMutableDictionary *) attributes setObject:color
		    forKey:NSForegroundColorAttributeName];
	}
	if (attributes) {
	    attributedTitle = [[[NSAttributedString alloc]
		    initWithString:title attributes:attributes] autorelease];
	}
    }
................................................................................
		 */

		submenu = nil;
	    } else {
		[submenu setTitle:title];

    		if ([menuItem isEnabled]) {
		    /*
		     * This menuItem might have been previously disabled (XXX:
		     * track this), which would have disabled entries; we must
		     * re-enable the entries here.
		     */

		    int i = 0;
		    NSArray *itemArray = [submenu itemArray];

		    for (NSMenuItem *item in itemArray) {
			TkMenuEntry *submePtr = menuRefPtr->menuPtr->entries[i];

			/*
			 * Work around an apparent bug where itemArray can have
			 * more items than the menu's entries[] array.
			 */

			if (i >= (int) menuRefPtr->menuPtr->numEntries) {
			    break;
			}
			[item setEnabled: !(submePtr->state == ENTRY_DISABLED)];
			i++;
		    }
		}

	    }
	}
    }
    [menuItem setSubmenu:submenu];

    return TCL_OK;
}
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpPostMenu --
 *
 *	Posts a menu on the screen. If entry is < 0 then the menu is drawn so
 *      its top left corner is located at the point with screen coordinates
 *      (x,y).  Otherwise the top left corner of the specified entry is located
 *      at that point.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * Side effects:
 *	The menu is posted and handled.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpPostTearoffMenu --
 *
 *	Tearoff menus are not supported on the Mac.  This placeholder function,
 *      which is simply a copy of the unix function, posts a completely useless
 *      window with a black background on the screen. If entry is < 0 then the
 *      window is positioned so that its top left corner is located at the
 *      point with screen coordinates (x, y).  Otherwise the window position is
 *      offset so that top left corner of the specified entry would be located
 *      at that point, if there actually were a menu.
 *
 *      Mac menus steal all mouse or keyboard input from the application until
 *      the menu is dismissed, with or without a selection, by a mouse or key
 *      event.  Posting a Mac menu in a regression test will cause the test to
 *      halt waiting for user input.  This is why the TkpPostMenu function is
 *      not being used as the placeholder.
 *
................................................................................
    int x, int y, int index)	/* The screen coordinates where the top left
				 * corner of the menu, or of the specified
				 * entry, will be located. */
{
    int vRootX, vRootY, vRootWidth, vRootHeight;
    int result;

    if (index >= (int) menuPtr->numEntries) {
	index = menuPtr->numEntries - 1;
    }
    if (index >= 0) {
	y -= menuPtr->entries[index]->y;
    }

    TkActivateMenuEntry(menuPtr, -1);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpSetMainMenubar --
 *
 *	Puts the menu associated with a window into the menubar. Should only be
 *	called when the window is in front.
 *
 *      This is a no-op on all other platforms.  On OS X it is a no-op when
 *      passed a NULL menuName or a nonexistent menuName, with an exception for
 *      the first call in a new interpreter.  In that special case, passing a
 *      NULL menuName installs the default menu.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The menubar may be changed.
................................................................................

    /*
     * We will be called when an embedded window receives an ActivationNotify
     * event, but we should not change the menubar in that case.
     */

    if (Tk_IsEmbedded(winPtr)) {
	return;
    }

    if (menuName) {
	Tk_Window menubar = NULL;

	if (winPtr->wmInfoPtr &&
		winPtr->wmInfoPtr->menuPtr &&
		winPtr->wmInfoPtr->menuPtr->masterMenuPtr) {
	    menubar = winPtr->wmInfoPtr->menuPtr->masterMenuPtr->tkwin;
	}

	/*
	 * Attempt to find the NSMenu directly. If that fails, ask Tk to find
	 * it.
	 */

	if (menubar != NULL && strcmp(menuName, Tk_PathName(menubar)) == 0) {
	    menu = (TKMenu *) winPtr->wmInfoPtr->menuPtr->platformData;
	} else {
	    TkMenuReferences *menuRefPtr = TkFindMenuReferences(interp,
		    menuName);

	    if (menuRefPtr && menuRefPtr->menuPtr &&
		    menuRefPtr->menuPtr->platformData) {
		menu = (TKMenu *) menuRefPtr->menuPtr->platformData;
	    }
	}
    }

    /*
     * If we couldn't find a menu, do nothing unless the window belongs to a
     * different application.  In that case, install the default menubar.

     */

    if (menu || interp != currentInterp) {
	[NSApp tkSetMainMenu:menu];
    }
    currentInterp = interp;
}
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * CheckForSpecialMenu --
 *
 *	Given a menu, check to see whether or not it is a cascade in a menubar
 *	with one of the special names ".apple", ".help" or ".window". If it is,
 *	the entry that points to this menu will be marked.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Will set entryFlags appropriately.
 *
................................................................................
    int entryWidth, maxIndicatorSpace, borderWidth, activeBorderWidth;
    TkMenuEntry *mePtr;
    int haveAccel = 0;

    /*
     * Do nothing if this menu is a clone.
     */

    if (menuPtr->tkwin == NULL || menuPtr->masterMenuPtr != menuPtr) {
	return;
    }

    menuSize = [(NSMenu *) menuPtr->platformData size];
    Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->borderWidthPtr,
	    &borderWidth);
    Tk_GetPixelsFromObj(NULL, menuPtr->tkwin, menuPtr->activeBorderWidthPtr,
	    &activeBorderWidth);
    x = y = borderWidth;
    windowHeight = maxWidth = 0;
    maxIndicatorSpace = 0;

    /*
     * On the Mac especially, getting font metrics can be quite slow, so we
     * want to do it intelligently. We are going to precalculate them and pass
     * them down to all of the measuring and drawing routines. We will measure
     * the font metrics of the menu once. If an entry does not have its own
     * font set, then we give the geometry/drawing routines the menu's font and
     * metrics. If an entry has its own font, we will measure that font and
     * give all of the geometry/drawing the entry's font and metrics.
     */

    menuFont = Tk_GetFontFromObj(menuPtr->tkwin, menuPtr->fontPtr);
    Tk_GetFontMetrics(menuFont, &menuMetrics);
    menuModifierCharWidth = ModifierCharWidth(menuFont);

    for (i = 0; i < (int) menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->type == CASCADE_ENTRY || mePtr->accelLength > 0) {
	    haveAccel = 1;
	    break;
	}
    }

    for (i = 0; i < (int) menuPtr->numEntries; i++) {
	mePtr = menuPtr->entries[i];
	if (mePtr->type == TEAROFF_ENTRY) {
	    continue;
	}
	if (mePtr->fontPtr == NULL) {
	    tkfont = menuFont;
	    fmPtr = &menuMetrics;
................................................................................
	     * (if any), and the width of the accelerator to be displayed to
	     * the right of the label (if any). These sizes depend, of course,
	     * on the type of the entry.
	     */

	    NSMenuItem *menuItem = (NSMenuItem *) mePtr->platformEntryData;
	    int haveImage = 0, width = 0, height = 0;

	    if (mePtr->image) {
		Tk_SizeOfImage(mePtr->image, &width, &height);
		haveImage = 1;
		height += 2; /* tweak */
	    } else if (mePtr->bitmapPtr) {
		Pixmap bitmap = Tk_GetBitmapFromObj(menuPtr->tkwin,
			mePtr->bitmapPtr);

		Tk_SizeOfBitmap(menuPtr->display, bitmap, &width, &height);
		haveImage = 1;
		height += 2; /* tweak */
	    }
	    if (!haveImage || (mePtr->compound != COMPOUND_NONE)) {
		NSAttributedString *attrTitle = [menuItem attributedTitle];
		NSSize size;
................................................................................
    NSMenuItem *menuItem)
{
    TkMenu *menuPtr = [menu tkMenu];

    if (menuPtr) {
	int index = [menu tkIndexOfItem:menuItem];

	if (index < 0 || index >= (int) menuPtr->numEntries ||
		(menuPtr->entries[index])->state == ENTRY_DISABLED) {
	    TkActivateMenuEntry(menuPtr, -1);
	} else {
	    TkActivateMenuEntry(menuPtr, index);
	    MenuSelectEvent(menuPtr);
	    return true;
	}
................................................................................
void
RecursivelyClearActiveMenu(
    TkMenu *menuPtr)		/* The menu to reset. */
{
    int i;

    TkActivateMenuEntry(menuPtr, -1);
    for (i = 0; i < (int) menuPtr->numEntries; i++) {
	TkMenuEntry *mePtr = menuPtr->entries[i];

	if (mePtr->type == CASCADE_ENTRY
		&& (mePtr->childMenuRefPtr != NULL)
		&& (mePtr->childMenuRefPtr->menuPtr != NULL)) {
	    RecursivelyClearActiveMenu(mePtr->childMenuRefPtr->menuPtr);
	}
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXUseID --
 *
 *	Take the ID out of the available list for new menus. Used by the
 *	default menu bar's menus so that they do not get created at the Tk
 *	level. See TkMacOSXGetNewMenuID for more information.
 *
 * Results:
 *	Returns TCL_OK if the id was not in use. Returns TCL_ERROR if the id
 *	was in use.
 *
 * Side effects:
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDispatchMenuEvent --
 *
 *	Given a menu id and an item, dispatches the command associated with it.

 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands for the event are scheduled for execution at idle time.
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetHelpMenuItemCount --
 *
 *	Has to be called after the first call to InsertMenu. Sets up the global
 *	variable for the number of items in the unmodified help menu.
 *
 *	NB: Nobody uses this any more, since you can get the number of system
 *	help items from HMGetHelpMenu trivially. But it is in the stubs
 *	table...
 *
 * Results:
 *	None.
 *
 * Side effects:

Changes to macosx/tkMacOSXMenubutton.c.

1
2
3
4
5
6
7
8
9
10
11
12
..
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
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
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
...
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
...
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
...
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
...
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
...
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
...
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
...
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
/*
 * tkMacOSXMenubutton.c --
 *
 *	This file implements the Macintosh specific portion of the
 *	menubutton widget.
 *
 * Copyright (c) 1996 by Sun Microsystems, Inc.
 * Copyright 2001, Apple Computer, Inc.
 * Copyright (c) 2006-2007 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2007 Revar Desmera.
 * Copyright 2015 Kevin Walzer/WordTech Communications LLC.
 *
................................................................................
typedef struct {
    Tk_3DBorder border;
    int relief;
    GC gc;
    int hasImageOrBitmap;
} DrawParams;


/*
 * Declaration of Mac specific button structure.
 */

typedef struct MacMenuButton {
    TkMenuButton info;		/* Generic button info. */
    int flags;
................................................................................
    DrawParams drawParams;
} MacMenuButton;

/*
 * Forward declarations for static functions defined later in this file:
 */

static void MenuButtonEventProc(ClientData clientData, XEvent *eventPtr);

static void MenuButtonBackgroundDrawCB (MacMenuButton *ptr, SInt16 depth,
					Boolean isColorDev);
static void MenuButtonContentDrawCB (ThemeButtonKind kind,
				     const HIThemeButtonDrawInfo * info,
				     MacMenuButton *ptr, SInt16 depth,
				     Boolean isColorDev);

static void MenuButtonEventProc ( ClientData clientData, XEvent *eventPtr);
static void TkMacOSXComputeMenuButtonParams (TkMenuButton * butPtr,
					     ThemeButtonKind* btnkind,
					     HIThemeButtonDrawInfo* drawinfo);
static void TkMacOSXComputeMenuButtonDrawParams (TkMenuButton * butPtr,
						 DrawParams * dpPtr);
static void TkMacOSXDrawMenuButton (MacMenuButton *butPtr, GC gc, Pixmap pixmap);

static void DrawMenuButtonImageAndText(TkMenuButton* butPtr);

/*
 * The structure below defines menubutton class behavior by means of
 * procedures that can be invoked from generic window code.
 */

Tk_ClassProcs tkpMenubuttonClass = {
................................................................................

TkMenuButton *
TkpCreateMenuButton(
    Tk_Window tkwin)
{
    MacMenuButton *mbPtr = (MacMenuButton *) ckalloc(sizeof(MacMenuButton));

    Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc,
			  (ClientData) mbPtr);
    mbPtr->flags = FIRST_DRAW;
    mbPtr->btnkind = kThemePopupButton;
    bzero(&mbPtr->drawinfo, sizeof(mbPtr->drawinfo));
    bzero(&mbPtr->lastdrawinfo, sizeof(mbPtr->lastdrawinfo));
    return (TkMenuButton *) mbPtr;
}
 
................................................................................
 *
 *	This procedure is invoked to display a menubutton widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menubutton in its
 *	current mode.
 *
 *----------------------------------------------------------------------
 */

void
TkpDisplayMenuButton(
    ClientData clientData)	/* Information about widget. */
{
    MacMenuButton *mbPtr    = (MacMenuButton *)clientData;
    TkMenuButton  *butPtr   = (TkMenuButton *) clientData;
    Tk_Window tkwin         = butPtr->tkwin;
    Pixmap pixmap;
    DrawParams* dpPtr = &mbPtr->drawParams;

    butPtr->flags &= ~REDRAW_PENDING;
    if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
        return;
    }

    pixmap = (Pixmap) Tk_WindowId(tkwin);

    TkMacOSXComputeMenuButtonDrawParams(butPtr, dpPtr);

    /*
     * set up clipping region.  Make sure the we are using the port
     * for this button, or we will set the wrong window's clip.
     */

    TkMacOSXSetUpClippingRgn(pixmap);


    /* Draw the native portion of the buttons. */


    TkMacOSXDrawMenuButton(mbPtr,  dpPtr->gc, pixmap);


    /* Draw highlight border, if needed. */


    if (butPtr->highlightWidth < 3) {
        if ((butPtr->flags & GOT_FOCUS)) {
            Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
                Tk_Width(tkwin), Tk_Height(tkwin),
                butPtr->highlightWidth, TK_RELIEF_SOLID);
        }
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyMenuButton --
 *
 *	Free data structures associated with the menubutton control.
 *      This is a no-op on the Mac.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
        txtWidth = butPtr->textWidth;
        txtHeight = butPtr->textHeight;
        avgWidth = Tk_TextWidth(butPtr->tkfont, "0", 1);
        Tk_GetFontMetrics(butPtr->tkfont, &fm);
    }

    /*
     * If the button is compound (ie, it shows both an image and text),
     * the new geometry is a combination of the image and text geometry.
     * We only honor the compound bit if the button has both text and an
     * image, because otherwise it is not really a compound button.
     */

    if (haveImage && haveText) {
        switch ((enum compound) butPtr->compound) {
            case COMPOUND_TOP:
            case COMPOUND_BOTTOM: {
                /*
                 * Image is above or below text
                 */

                height += txtHeight + butPtr->padY;
                width = (width > txtWidth ? width : txtWidth);
                break;
            }
            case COMPOUND_LEFT:
            case COMPOUND_RIGHT: {
                /*
                 * Image is left or right of text
                 */

                width += txtWidth + butPtr->padX;
                height = (height > txtHeight ? height : txtHeight);
                break;
            }
            case COMPOUND_CENTER: {
                /*
                 * Image and text are superimposed
                 */

                width = (width > txtWidth ? width : txtWidth);
                height = (height > txtHeight ? height : txtHeight);
                break;
            }
            case COMPOUND_NONE: {break;}

        }

        if (butPtr->width > 0) {
            width = butPtr->width;
        }
        if (butPtr->height > 0) {
            height = butPtr->height;
................................................................................
 * Side effects:
 *        The image and text are drawn.
 *
 *----------------------------------------------------------------------
 */
void
DrawMenuButtonImageAndText(
    TkMenuButton* butPtr)
{
    MacMenuButton *mbPtr = (MacMenuButton*)butPtr;
    Tk_Window  tkwin  = butPtr->tkwin;
    Pixmap     pixmap;
    int        haveImage = 0;
    int        haveText = 0;
    int        imageWidth = 0;
    int        imageHeight = 0;
    int        imageXOffset = 0;
    int        imageYOffset = 0;
    int        textXOffset = 0;
    int        textYOffset = 0;
    int        width = 0;
    int        height = 0;
    int        fullWidth = 0;
    int        fullHeight = 0;
    int        pressed;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }

    DrawParams* dpPtr = &mbPtr->drawParams;
    pixmap = (Pixmap)Tk_WindowId(tkwin);


    if (butPtr->image != None) {
        Tk_SizeOfImage(butPtr->image, &width, &height);
        haveImage = 1;
    } else if (butPtr->bitmap != None) {
        Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
        haveImage = 1;
    }

    imageWidth  = width;
    imageHeight = height;

    if (mbPtr->drawinfo.state == kThemeStatePressed) {
        /* Offset bitmaps by a bit when the button is pressed. */
        pressed = 1;
    }

    haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0);
    if (butPtr->compound != COMPOUND_NONE && haveImage && haveText) {
        int x = 0;
        int y = 0;

        textXOffset = 0;
        textYOffset = 0;
        fullWidth = 0;
        fullHeight = 0;

        switch ((enum compound) butPtr->compound) {
            case COMPOUND_TOP:
            case COMPOUND_BOTTOM: {

                /* Image is above or below text */


                if (butPtr->compound == COMPOUND_TOP) {
                    textYOffset = height + butPtr->padY;
                } else {
                    imageYOffset = butPtr->textHeight + butPtr->padY;
                }
                fullHeight = height + butPtr->textHeight + butPtr->padY;
                fullWidth = (width > butPtr->textWidth ?
			     width : butPtr->textWidth);
                textXOffset = (fullWidth - butPtr->textWidth)/2;
                imageXOffset = (fullWidth - width)/2;
                break;
            }
            case COMPOUND_LEFT:
            case COMPOUND_RIGHT: {
                /*
                 * Image is left or right of text
                 */

                if (butPtr->compound == COMPOUND_LEFT) {
                    textXOffset = width + butPtr->padX - 2;
                } else {
                    imageXOffset = butPtr->textWidth + butPtr->padX;
                }
                fullWidth = butPtr->textWidth + butPtr->padX + width;
                fullHeight = (height > butPtr->textHeight ? height :
                        butPtr->textHeight);
                textYOffset = (fullHeight - butPtr->textHeight)/2;
                imageYOffset = (fullHeight - height)/2;
                break;
            }
            case COMPOUND_CENTER: {
                /*
                 * Image and text are superimposed
                 */

                fullWidth = (width > butPtr->textWidth ? width :
                        butPtr->textWidth);
                fullHeight = (height > butPtr->textHeight ? height :
                        butPtr->textHeight);
                textXOffset = (fullWidth - butPtr->textWidth)/2;
                imageXOffset = (fullWidth - width)/2;
                textYOffset = (fullHeight - butPtr->textHeight)/2;
                imageYOffset = (fullHeight - height)/2;
                break;
            }
            case COMPOUND_NONE: {break;}

	}

        TkComputeAnchor(butPtr->anchor, tkwin,
                butPtr->padX + butPtr->inset,
                butPtr->padY + butPtr->inset,
                fullWidth, fullHeight, &x, &y);
        imageXOffset = LEFT_INSET;
        imageYOffset += y;
        textYOffset -= 1;

        if (butPtr->image != NULL) {
                Tk_RedrawImage(butPtr->image, 0, 0, width,
                        height, pixmap, imageXOffset, imageYOffset);
        } else {
            XSetClipOrigin(butPtr->display, dpPtr->gc,
                    imageXOffset, imageYOffset);
            XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc,
                    0, 0, (unsigned int) width, (unsigned int) height,
                    imageXOffset, imageYOffset, 1);
            XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
        }

        Tk_DrawTextLayout(butPtr->display, pixmap,
                dpPtr->gc, butPtr->textLayout,
                x + textXOffset, y + textYOffset, 0, -1);
        Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc,
                butPtr->textLayout,
                x + textXOffset, y + textYOffset,
                butPtr->underline);
    } else {
        if (haveImage) {
            int x, y;


            TkComputeAnchor(butPtr->anchor, tkwin,
                    butPtr->padX + butPtr->borderWidth,
                    butPtr->padY + butPtr->borderWidth,
                    width, height, &x, &y);
	    imageXOffset = LEFT_INSET;
	    imageYOffset += y;
	    if (butPtr->image != NULL) {
................................................................................
			   pixmap, dpPtr->gc,
			   0, 0, (unsigned int) width,
			   (unsigned int) height,
			   imageXOffset, imageYOffset, 1);
                XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
            }
        } else {
	    int x, y;
	    textXOffset = LEFT_INSET;
	    TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY,
			    butPtr->textWidth, butPtr->textHeight, &x, &y);
	    Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc,
			      butPtr->textLayout, textXOffset, y, 0, -1);
	    y += butPtr->textHeight/2;
	  }
   }
}



/*
 *--------------------------------------------------------------
 *
 * TkMacOSXDrawMenuButton --
 *
 *        This function draws the tk menubutton using Mac controls
 *        In addition, this code may apply custom colors passed
 *        in the TkMenubutton.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        None.
 *
 *--------------------------------------------------------------
 */

static void
TkMacOSXDrawMenuButton(
    MacMenuButton *mbPtr, /* Mac menubutton. */
    GC gc,                /* The GC we are drawing into - needed for
                           * the bevel button */
    Pixmap pixmap)        /* The pixmap we are drawing into - needed
                           * for the bevel button */
{
    TkMenuButton * butPtr = ( TkMenuButton *)mbPtr;
    TkWindow * winPtr;
    HIRect       cntrRect;
    TkMacOSXDrawingContext dc;
    DrawParams* dpPtr = &mbPtr->drawParams;
    int useNewerHITools = 1;

    winPtr = (TkWindow *)butPtr->tkwin;

    TkMacOSXComputeMenuButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);

    cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff,
			  Tk_Width(butPtr->tkwin),
			  Tk_Height(butPtr->tkwin));

    if (useNewerHITools == 1) {
        HIRect contHIRec;
        static HIThemeButtonDrawInfo hiinfo;

        MenuButtonBackgroundDrawCB((MacMenuButton*) mbPtr, 32, true);

	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}


        hiinfo.version = 0;
        hiinfo.state = mbPtr->drawinfo.state;
        hiinfo.kind  = mbPtr->btnkind;
        hiinfo.value = mbPtr->drawinfo.value;
        hiinfo.adornment = mbPtr->drawinfo.adornment;
        hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent();
        if (hiinfo.animation.time.start == 0) {
            hiinfo.animation.time.start = hiinfo.animation.time.current;
        }

        HIThemeDrawButton(&cntrRect, &hiinfo, dc.context,
			  kHIThemeOrientationNormal, &contHIRec);
	TkMacOSXRestoreDrawingContext(&dc);
        MenuButtonContentDrawCB( mbPtr->btnkind, &mbPtr->drawinfo,
				 (MacMenuButton *)mbPtr, 32, true);
    } else {
	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}
	TkMacOSXRestoreDrawingContext(&dc);
    }
    mbPtr->lastdrawinfo = mbPtr->drawinfo;
................................................................................
}
 
/*
 *--------------------------------------------------------------
 *
 * MenuButtonBackgroundDrawCB --
 *
 *        This function draws the background that
 *        lies under checkboxes and radiobuttons.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        The background gets updated to the current color.
 *
 *--------------------------------------------------------------
 */

static void
MenuButtonBackgroundDrawCB (
    MacMenuButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    TkMenuButton* butPtr = (TkMenuButton*)ptr;
    Tk_Window tkwin  = butPtr->tkwin;
    Pixmap pixmap;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }
    pixmap = (Pixmap)Tk_WindowId(tkwin);

    Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
        Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
}
 
/*
 *--------------------------------------------------------------
 *
 * MenuButtonContentDrawCB --
 *
 *        This function draws the label and image for the button.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        The content of the button gets updated.
 *
 *--------------------------------------------------------------
 */

static void
MenuButtonContentDrawCB (
    ThemeButtonKind kind,
    const HIThemeButtonDrawInfo *drawinfo,
    MacMenuButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    TkMenuButton  *butPtr = (TkMenuButton *)ptr;
    Tk_Window  tkwin  = butPtr->tkwin;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }
    DrawMenuButtonImageAndText(butPtr);
}
 
/*
 *--------------------------------------------------------------
 *
 * MenuButtonEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various
 *	events on buttons.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When it gets exposed, it is redisplayed.
 *
................................................................................
 */

static void
MenuButtonEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkMenuButton *buttonPtr = (TkMenuButton *) clientData;
    MacMenuButton *mbPtr = (MacMenuButton *) clientData;

    if (eventPtr->type == ActivateNotify
	    || eventPtr->type == DeactivateNotify) {
	if ((buttonPtr->tkwin == NULL) || (!Tk_IsMapped(buttonPtr->tkwin))) {
	    return;
	}
	if (eventPtr->type == ActivateNotify) {
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeMenuButtonParams --
 *
 *      This procedure computes the various parameters used
 *        when creating a Carbon Appearance control.
 *      These are determined by the various tk button parameters
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        Sets the btnkind and drawinfo parameters
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXComputeMenuButtonParams(
    TkMenuButton * butPtr,
    ThemeButtonKind* btnkind,
    HIThemeButtonDrawInfo *drawinfo)
{
    MacMenuButton *mbPtr = (MacMenuButton *)butPtr;

    if (butPtr->image || butPtr->bitmap || butPtr->text) {
	/* TODO: allow for Small and Mini menubuttons. */
	*btnkind = kThemePopupButton;
    } else { /* This should never happen. */
	*btnkind = kThemeArrowButton;
    }
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeMenuButtonDrawParams --
 *
 *        This procedure selects an appropriate drawing context for
 *        drawing a menubutton.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        Sets the button draw parameters.
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXComputeMenuButtonDrawParams(
    TkMenuButton * butPtr,
    DrawParams * dpPtr)
{
    dpPtr->hasImageOrBitmap = ((butPtr->image != NULL) ||
			       (butPtr->bitmap != None));
    dpPtr->border = butPtr->normalBorder;
    if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) {
        dpPtr->gc = butPtr->disabledGC;
    } else if (butPtr->state == STATE_ACTIVE) {
        dpPtr->gc = butPtr->activeTextGC;
        dpPtr->border = butPtr->activeBorder;
    } else {
        dpPtr->gc = butPtr->normalTextGC;
    }
}

/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */



|
|







 







<







 







|
>
|
|
|
|
|
|
>
|
|
|
|
|
|
|
>
|







 







|
<







 







|
<








|
|
|

|











|
|




>
|
>
>


>
|
>
>
|
<
|


<








|
|







 







|
|
|
|




|
|
|
|
|

|
|
|
<
|
|
|
|
|

|
|
|
<
|
|
|
|

|
|
|
<
|
>







 







|

|
|
|
|
<
|
<
|
<
|
<
|
<
|
<
<





|
|
<









|


<
<
<
<
<


|
<
>






|
|
>
|
>
>
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|

|
<
|
|
|
|
|
|
|
<
|
>



|
<






|
|













<
|


<
|
>
>







 







<


|

|

|


|
<
<





|
|
|









>



|
|
|
|

|
|
|

|


<
<



<
|





|
<




<


|








|

|
|







 







|
|


|


|



>






|
|

>



|
<

|







|


|


|



>








|
|












|
|







 







|
|







 







|
|
|












|
|


|







 







|
|


|


|






|
|

|
|










|








1
2
3
4
5
6
7
8
9
10
11
12
..
28
29
30
31
32
33
34

35
36
37
38
39
40
41
..
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
...
131
132
133
134
135
136
137
138

139
140
141
142
143
144
145
...
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
...
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
...
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
...
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
...
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
...
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
...
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
/*
 * tkMacOSXMenubutton.c --
 *
 *	This file implements the Macintosh specific portion of the menubutton
 *	widget.
 *
 * Copyright (c) 1996 by Sun Microsystems, Inc.
 * Copyright 2001, Apple Computer, Inc.
 * Copyright (c) 2006-2007 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright 2007 Revar Desmera.
 * Copyright 2015 Kevin Walzer/WordTech Communications LLC.
 *
................................................................................
typedef struct {
    Tk_3DBorder border;
    int relief;
    GC gc;
    int hasImageOrBitmap;
} DrawParams;


/*
 * Declaration of Mac specific button structure.
 */

typedef struct MacMenuButton {
    TkMenuButton info;		/* Generic button info. */
    int flags;
................................................................................
    DrawParams drawParams;
} MacMenuButton;

/*
 * Forward declarations for static functions defined later in this file:
 */

static void		MenuButtonEventProc(ClientData clientData,
			    XEvent *eventPtr);
static void		MenuButtonBackgroundDrawCB(MacMenuButton *ptr,
			    SInt16 depth, Boolean isColorDev);
static void		MenuButtonContentDrawCB(ThemeButtonKind kind,
			    const HIThemeButtonDrawInfo *info,
			    MacMenuButton *ptr, SInt16 depth,
			    Boolean isColorDev);
static void		MenuButtonEventProc(ClientData clientData,
			    XEvent *eventPtr);
static void		TkMacOSXComputeMenuButtonParams(TkMenuButton *butPtr,
			    ThemeButtonKind *btnkind,
			    HIThemeButtonDrawInfo *drawinfo);
static void		TkMacOSXComputeMenuButtonDrawParams(
			    TkMenuButton *butPtr, DrawParams *dpPtr);
static void		TkMacOSXDrawMenuButton(MacMenuButton *butPtr, GC gc,
			    Pixmap pixmap);
static void		DrawMenuButtonImageAndText(TkMenuButton *butPtr);

/*
 * The structure below defines menubutton class behavior by means of
 * procedures that can be invoked from generic window code.
 */

Tk_ClassProcs tkpMenubuttonClass = {
................................................................................

TkMenuButton *
TkpCreateMenuButton(
    Tk_Window tkwin)
{
    MacMenuButton *mbPtr = (MacMenuButton *) ckalloc(sizeof(MacMenuButton));

    Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc, mbPtr);

    mbPtr->flags = FIRST_DRAW;
    mbPtr->btnkind = kThemePopupButton;
    bzero(&mbPtr->drawinfo, sizeof(mbPtr->drawinfo));
    bzero(&mbPtr->lastdrawinfo, sizeof(mbPtr->lastdrawinfo));
    return (TkMenuButton *) mbPtr;
}
 
................................................................................
 *
 *	This procedure is invoked to display a menubutton widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the menubutton in its current mode.

 *
 *----------------------------------------------------------------------
 */

void
TkpDisplayMenuButton(
    ClientData clientData)	/* Information about widget. */
{
    MacMenuButton *mbPtr = clientData;
    TkMenuButton *butPtr = clientData;
    Tk_Window tkwin = butPtr->tkwin;
    Pixmap pixmap;
    DrawParams *dpPtr = &mbPtr->drawParams;

    butPtr->flags &= ~REDRAW_PENDING;
    if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
        return;
    }

    pixmap = (Pixmap) Tk_WindowId(tkwin);

    TkMacOSXComputeMenuButtonDrawParams(butPtr, dpPtr);

    /*
     * Set up clipping region.  Make sure the we are using the port for this
     * button, or we will set the wrong window's clip.
     */

    TkMacOSXSetUpClippingRgn(pixmap);

    /*
     * Draw the native portion of the buttons.
     */

    TkMacOSXDrawMenuButton(mbPtr,  dpPtr->gc, pixmap);

    /*
     * Draw highlight border, if needed.
     */

    if ((butPtr->highlightWidth < 3) && (butPtr->flags & GOT_FOCUS)) {

	Tk_Draw3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
                Tk_Width(tkwin), Tk_Height(tkwin),
                butPtr->highlightWidth, TK_RELIEF_SOLID);

    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyMenuButton --
 *
 *	Free data structures associated with the menubutton control. This is a
 *      no-op on the Mac.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
        txtWidth = butPtr->textWidth;
        txtHeight = butPtr->textHeight;
        avgWidth = Tk_TextWidth(butPtr->tkfont, "0", 1);
        Tk_GetFontMetrics(butPtr->tkfont, &fm);
    }

    /*
     * If the button is compound (ie, it shows both an image and text), the new
     * geometry is a combination of the image and text geometry. We only honor
     * the compound bit if the button has both text and an image, because
     * otherwise it is not really a compound button.
     */

    if (haveImage && haveText) {
        switch ((enum compound) butPtr->compound) {
	case COMPOUND_TOP:
	case COMPOUND_BOTTOM:
	    /*
	     * Image is above or below text
	     */

	    height += txtHeight + butPtr->padY;
	    width = (width > txtWidth ? width : txtWidth);
	    break;

	case COMPOUND_LEFT:
	case COMPOUND_RIGHT:
	    /*
	     * Image is left or right of text
	     */

	    width += txtWidth + butPtr->padX;
	    height = (height > txtHeight ? height : txtHeight);
	    break;

	case COMPOUND_CENTER:
	    /*
	     * Image and text are superimposed
	     */

	    width = (width > txtWidth ? width : txtWidth);
	    height = (height > txtHeight ? height : txtHeight);
	    break;

	case COMPOUND_NONE:
	    break;
        }

        if (butPtr->width > 0) {
            width = butPtr->width;
        }
        if (butPtr->height > 0) {
            height = butPtr->height;
................................................................................
 * Side effects:
 *        The image and text are drawn.
 *
 *----------------------------------------------------------------------
 */
void
DrawMenuButtonImageAndText(
    TkMenuButton *butPtr)
{
    MacMenuButton *mbPtr = (MacMenuButton *) butPtr;
    Tk_Window tkwin  = butPtr->tkwin;
    Pixmap pixmap;
    int haveImage = 0, haveText = 0;

    int imageWidth = 0, imageHeight = 0;

    int imageXOffset = 0, imageYOffset = 0;

    int textXOffset = 0, textYOffset = 0;

    int width = 0, height = 0;

    int fullWidth = 0, fullHeight = 0;



    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }

    DrawParams *dpPtr = &mbPtr->drawParams;
    pixmap = (Pixmap) Tk_WindowId(tkwin);


    if (butPtr->image != None) {
        Tk_SizeOfImage(butPtr->image, &width, &height);
        haveImage = 1;
    } else if (butPtr->bitmap != None) {
        Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
        haveImage = 1;
    }

    imageWidth = width;
    imageHeight = height;






    haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0);
    if (butPtr->compound != COMPOUND_NONE && haveImage && haveText) {
        int x = 0, y = 0;


        textXOffset = 0;
        textYOffset = 0;
        fullWidth = 0;
        fullHeight = 0;

        switch ((enum compound) butPtr->compound) {
	case COMPOUND_TOP:
	case COMPOUND_BOTTOM:
	    /*
	     * Image is above or below text.
	     */

	    if (butPtr->compound == COMPOUND_TOP) {
		textYOffset = height + butPtr->padY;
	    } else {
		imageYOffset = butPtr->textHeight + butPtr->padY;
	    }
	    fullHeight = height + butPtr->textHeight + butPtr->padY;
	    fullWidth = (width > butPtr->textWidth ?
		     width : butPtr->textWidth);
	    textXOffset = (fullWidth - butPtr->textWidth)/2;
	    imageXOffset = (fullWidth - width)/2;
	    break;

	case COMPOUND_LEFT:
	case COMPOUND_RIGHT:
	    /*
	     * Image is left or right of text
	     */

	    if (butPtr->compound == COMPOUND_LEFT) {
		textXOffset = width + butPtr->padX - 2;
	    } else {
		imageXOffset = butPtr->textWidth + butPtr->padX;
	    }
	    fullWidth = butPtr->textWidth + butPtr->padX + width;
	    fullHeight = (height > butPtr->textHeight ? height :
                    butPtr->textHeight);
	    textYOffset = (fullHeight - butPtr->textHeight)/2;
	    imageYOffset = (fullHeight - height)/2;
	    break;

	case COMPOUND_CENTER:
	    /*
	     * Image and text are superimposed
	     */

	    fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth);

	    fullHeight = (height > butPtr->textHeight ? height :
                    butPtr->textHeight);
	    textXOffset = (fullWidth - butPtr->textWidth) / 2;
	    imageXOffset = (fullWidth - width) / 2;
	    textYOffset = (fullHeight - butPtr->textHeight) / 2;
	    imageYOffset = (fullHeight - height) / 2;
	    break;

	case COMPOUND_NONE:
	    break;
	}

        TkComputeAnchor(butPtr->anchor, tkwin,
                butPtr->padX + butPtr->inset, butPtr->padY + butPtr->inset,

                fullWidth, fullHeight, &x, &y);
        imageXOffset = LEFT_INSET;
        imageYOffset += y;
        textYOffset -= 1;

        if (butPtr->image != NULL) {
	    Tk_RedrawImage(butPtr->image, 0, 0, width,
                    height, pixmap, imageXOffset, imageYOffset);
        } else {
            XSetClipOrigin(butPtr->display, dpPtr->gc,
                    imageXOffset, imageYOffset);
            XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc,
                    0, 0, (unsigned int) width, (unsigned int) height,
                    imageXOffset, imageYOffset, 1);
            XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
        }

        Tk_DrawTextLayout(butPtr->display, pixmap,
                dpPtr->gc, butPtr->textLayout,
                x + textXOffset, y + textYOffset, 0, -1);
        Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc,

                butPtr->textLayout, x + textXOffset, y + textYOffset,
                butPtr->underline);
    } else {

	int x, y;

        if (haveImage) {
            TkComputeAnchor(butPtr->anchor, tkwin,
                    butPtr->padX + butPtr->borderWidth,
                    butPtr->padY + butPtr->borderWidth,
                    width, height, &x, &y);
	    imageXOffset = LEFT_INSET;
	    imageYOffset += y;
	    if (butPtr->image != NULL) {
................................................................................
			   pixmap, dpPtr->gc,
			   0, 0, (unsigned int) width,
			   (unsigned int) height,
			   imageXOffset, imageYOffset, 1);
                XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
            }
        } else {

	    textXOffset = LEFT_INSET;
	    TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY,
		    butPtr->textWidth, butPtr->textHeight, &x, &y);
	    Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc,
		    butPtr->textLayout, textXOffset, y, 0, -1);
	    y += butPtr->textHeight/2;
	}
   }
}
 


/*
 *--------------------------------------------------------------
 *
 * TkMacOSXDrawMenuButton --
 *
 *        This function draws the tk menubutton using Mac controls. In
 *        addition, this code may apply custom colors passed in the
 *        TkMenubutton.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        None.
 *
 *--------------------------------------------------------------
 */

static void
TkMacOSXDrawMenuButton(
    MacMenuButton *mbPtr, /* Mac menubutton. */
    GC gc,                /* The GC we are drawing into - needed for the bevel
                           * button */
    Pixmap pixmap)        /* The pixmap we are drawing into - needed for the
                           * bevel button */
{
    TkMenuButton *butPtr = (TkMenuButton *) mbPtr;
    TkWindow *winPtr = (TkWindow *) butPtr->tkwin;
    HIRect cntrRect;
    TkMacOSXDrawingContext dc;
    DrawParams *dpPtr = &mbPtr->drawParams;
    int useNewerHITools = 1;



    TkMacOSXComputeMenuButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);

    cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff,

	    Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin));

    if (useNewerHITools == 1) {
        HIRect contHIRec;
        static HIThemeButtonDrawInfo hiinfo;

        MenuButtonBackgroundDrawCB(mbPtr, 32, true);

	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}


        hiinfo.version = 0;
        hiinfo.state = mbPtr->drawinfo.state;
        hiinfo.kind = mbPtr->btnkind;
        hiinfo.value = mbPtr->drawinfo.value;
        hiinfo.adornment = mbPtr->drawinfo.adornment;
        hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent();
        if (hiinfo.animation.time.start == 0) {
            hiinfo.animation.time.start = hiinfo.animation.time.current;
        }

        HIThemeDrawButton(&cntrRect, &hiinfo, dc.context,
		kHIThemeOrientationNormal, &contHIRec);
	TkMacOSXRestoreDrawingContext(&dc);
        MenuButtonContentDrawCB(mbPtr->btnkind, &mbPtr->drawinfo,
		mbPtr, 32, true);
    } else {
	if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
	    return;
	}
	TkMacOSXRestoreDrawingContext(&dc);
    }
    mbPtr->lastdrawinfo = mbPtr->drawinfo;
................................................................................
}
 
/*
 *--------------------------------------------------------------
 *
 * MenuButtonBackgroundDrawCB --
 *
 *      This function draws the background that lies under checkboxes and
 *      radiobuttons.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The background gets updated to the current color.
 *
 *--------------------------------------------------------------
 */

static void
MenuButtonBackgroundDrawCB (
    MacMenuButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    TkMenuButton* butPtr = (TkMenuButton *) ptr;
    Tk_Window tkwin = butPtr->tkwin;
    Pixmap pixmap;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }
    pixmap = (Pixmap) Tk_WindowId(tkwin);

    Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
            Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
}
 
/*
 *--------------------------------------------------------------
 *
 * MenuButtonContentDrawCB --
 *
 *      This function draws the label and image for the button.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The content of the button gets updated.
 *
 *--------------------------------------------------------------
 */

static void
MenuButtonContentDrawCB (
    ThemeButtonKind kind,
    const HIThemeButtonDrawInfo *drawinfo,
    MacMenuButton *ptr,
    SInt16 depth,
    Boolean isColorDev)
{
    TkMenuButton *butPtr = (TkMenuButton *) ptr;
    Tk_Window tkwin = butPtr->tkwin;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
        return;
    }
    DrawMenuButtonImageAndText(butPtr);
}
 
/*
 *--------------------------------------------------------------
 *
 * MenuButtonEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various events on
 *	buttons.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When it gets exposed, it is redisplayed.
 *
................................................................................
 */

static void
MenuButtonEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkMenuButton *buttonPtr = clientData;
    MacMenuButton *mbPtr = clientData;

    if (eventPtr->type == ActivateNotify
	    || eventPtr->type == DeactivateNotify) {
	if ((buttonPtr->tkwin == NULL) || (!Tk_IsMapped(buttonPtr->tkwin))) {
	    return;
	}
	if (eventPtr->type == ActivateNotify) {
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeMenuButtonParams --
 *
 *      This procedure computes the various parameters used when creating a
 *      Carbon Appearance control. These are determined by the various Tk
 *      button parameters
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        Sets the btnkind and drawinfo parameters
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXComputeMenuButtonParams(
    TkMenuButton *butPtr,
    ThemeButtonKind *btnkind,
    HIThemeButtonDrawInfo *drawinfo)
{
    MacMenuButton *mbPtr = (MacMenuButton *) butPtr;

    if (butPtr->image || butPtr->bitmap || butPtr->text) {
	/* TODO: allow for Small and Mini menubuttons. */
	*btnkind = kThemePopupButton;
    } else { /* This should never happen. */
	*btnkind = kThemeArrowButton;
    }
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXComputeMenuButtonDrawParams --
 *
 *      This procedure selects an appropriate drawing context for drawing a
 *      menubutton.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Sets the button draw parameters.
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXComputeMenuButtonDrawParams(
    TkMenuButton *butPtr,
    DrawParams *dpPtr)
{
    dpPtr->hasImageOrBitmap =
	    ((butPtr->image != NULL) || (butPtr->bitmap != None));
    dpPtr->border = butPtr->normalBorder;
    if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) {
        dpPtr->gc = butPtr->disabledGC;
    } else if (butPtr->state == STATE_ACTIVE) {
        dpPtr->gc = butPtr->activeTextGC;
        dpPtr->border = butPtr->activeBorder;
    } else {
        dpPtr->gc = butPtr->normalTextGC;
    }
}
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */

Changes to macosx/tkMacOSXMenus.c.

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
}

- (BOOL) validateUserInterfaceItem: (id <NSValidatedUserInterfaceItem>) anItem
{
    SEL action = [anItem action];

    if (sel_isEqual(action, @selector(preferences:))) {

	return (_eventInterp && Tcl_FindCommand(_eventInterp,
		"::tk::mac::ShowPreferences", NULL, 0));
    } else if (sel_isEqual(action, @selector(tkDemo:))) {
	BOOL haveDemo = NO;

	if (_eventInterp) {
	    Tcl_Obj *path = GetWidgetDemoPath(_eventInterp);







<







173
174
175
176
177
178
179

180
181
182
183
184
185
186
}

- (BOOL) validateUserInterfaceItem: (id <NSValidatedUserInterfaceItem>) anItem
{
    SEL action = [anItem action];

    if (sel_isEqual(action, @selector(preferences:))) {

	return (_eventInterp && Tcl_FindCommand(_eventInterp,
		"::tk::mac::ShowPreferences", NULL, 0));
    } else if (sel_isEqual(action, @selector(tkDemo:))) {
	BOOL haveDemo = NO;

	if (_eventInterp) {
	    Tcl_Obj *path = GetWidgetDemoPath(_eventInterp);

Changes to macosx/tkMacOSXNotify.c.

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
...
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
	Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData))

static void TkMacOSXNotifyExitHandler(ClientData clientData);
static void TkMacOSXEventsSetupProc(ClientData clientData, int flags);
static void TkMacOSXEventsCheckProc(ClientData clientData, int flags);

#ifdef TK_MAC_DEBUG_EVENTS
static char* Tk_EventName[39] = {
    "",
    "",
    "KeyPress",		/*2*/
    "KeyRelease",      	/*3*/
    "ButtonPress",     	/*4*/
    "ButtonRelease",	/*5*/
    "MotionNotify",    	/*6*/
................................................................................
 * no longer, and perhaps never did need to set autoDisplay to NO, nor call
 * displayIfNeeded on our windows.  We can just leave all of that to the window
 * manager.
 */

/*
 * Since the contentView is the first responder for a Tk Window, it is
 * responsible for sending events up the responder chain.  We also check
 * the pasteboard here.
 */
- (void) sendEvent: (NSEvent *) theEvent
{
    [super sendEvent:theEvent];
    [NSApp tkCheckPasteboard];
#ifdef TK_MAC_DEBUG_EVENTS
    fprintf(stderr, "Sending event of type %d\n", (int)[theEvent type]);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tk_MacOSXSetupTkNotifier --
 *
 *	This procedure is called during Tk initialization to create
 *	the event source for TkAqua events.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A new event source is created.
 *
................................................................................
		 * Panic if main runloop is not on the main application thread.
		 */

		Tcl_Panic("Tk_MacOSXSetupTkNotifier: %s",
		    "first [load] of TkAqua has to occur in the main thread!");
	    }
	    Tcl_CreateEventSource(TkMacOSXEventsSetupProc,
				  TkMacOSXEventsCheckProc,
				  NULL);
	    TkCreateExitHandler(TkMacOSXNotifyExitHandler, NULL);
	    Tcl_SetServiceMode(TCL_SERVICE_ALL);
	    TclMacOSXNotifierAddRunLoopMode(NSEventTrackingRunLoopMode);
	    TclMacOSXNotifierAddRunLoopMode(NSModalPanelRunLoopMode);
	}
    }
}
................................................................................
static void
TkMacOSXNotifyExitHandler(
    ClientData clientData)	/* Not used. */
{
    TSD_INIT();

    Tcl_DeleteEventSource(TkMacOSXEventsSetupProc,
			  TkMacOSXEventsCheckProc,
			  NULL);
    tsdPtr->initialized = 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsSetupProc --
 *
 *	This procedure implements the setup part of the MacOSX event
 *	source. It is invoked by Tcl_DoOneEvent before calling
 *      TkMacOSXEventsProc to process all queued NSEvents.  In our
 *      case, all we need to do is to set the Tcl MaxBlockTime to
 *      0 before starting the loop to process all queued NSEvents.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *
 *	If NSEvents are queued, then the maximum block time will be set
 *	to 0 to ensure that control returns immediately to Tcl.
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXEventsSetupProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];


    /* runloopMode will be nil if we are in a Tcl event loop. */


    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {
	static const Tcl_Time zeroBlockTime = { 0, 0 };
	[NSApp _resetAutoreleasePool];


	/* Call this with dequeue=NO -- just checking if the queue is empty. */



	NSEvent *currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
				       untilDate:[NSDate distantPast]
				       inMode:GetRunLoopMode(TkMacOSXGetModalSession())
				       dequeue:NO];
	if (currentEvent) {
	    if (currentEvent.type > 0) {
		Tcl_SetMaxBlockTime(&zeroBlockTime);
	    }
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsCheckProc --
 *
 *	This procedure loops through all NSEvents waiting in the
 *      TKApplication event queue, generating X events from them.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	NSevents are used to generate X events, which are added to the
 *      Tcl event queue.
 *
 *----------------------------------------------------------------------
 */
static void
TkMacOSXEventsCheckProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];


    /* runloopMode will be nil if we are in a Tcl event loop. */


    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {
	NSEvent *currentEvent = nil;
	NSEvent *testEvent = nil;
	NSModalSession modalSession;


	/* It is possible for the SetupProc to be called before this function
	 * returns.  This happens, for example, when we process an event which
	 * opens a modal window.  To prevent premature release of our
	 * application-wide autorelease pool by a nested call to the SetupProc,
	 * we must lock it here.
	 */

	[NSApp _lockAutoreleasePool];
	do {
	    modalSession = TkMacOSXGetModalSession();
	    	    testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
					      untilDate:[NSDate distantPast]
						 inMode:GetRunLoopMode(modalSession)
						dequeue:NO];


	    /* We must not steal any events during LiveResize. */


	    if (testEvent && [[testEvent window] inLiveResize]) {
		break;
	    }
	    currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
					      untilDate:[NSDate distantPast]
						 inMode:GetRunLoopMode(modalSession)
						dequeue:YES];
	    if (currentEvent) {

		/* Generate Xevents. */


		int oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);
		NSEvent *processedEvent = [NSApp tkProcessEvent:currentEvent];
		Tcl_SetServiceMode(oldServiceMode);
		if (processedEvent) {
#ifdef TK_MAC_DEBUG_EVENTS
		    TKLog(@"   event: %@", currentEvent);
#endif
		    if (modalSession) {
			[NSApp _modalSession:modalSession sendEvent:currentEvent];
		    } else {
			[NSApp sendEvent:currentEvent];
		    }
		}

	    } else {
		break;
	    }
	} while (1);


	/* Now we can unlock the pool. */


	[NSApp _unlockAutoreleasePool];
    }
}

 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */







|







 







|
|







 







|
|







 







|
<







 







|
<








|
|
|
|
|






|
|










>
>
|
>
>



>
>
|
>
>
>
|
|
|
|













|
|





|
|









>
>
|
>
>




>
>
|





>



|
|
|
|
>
>
|
>
>




|
|
|

>
|
>
>













<




>
>
|
>
>



<









29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
220
221
222
223
224
225
226
227

228
229
230
231
232
233
234
...
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
	Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData))

static void TkMacOSXNotifyExitHandler(ClientData clientData);
static void TkMacOSXEventsSetupProc(ClientData clientData, int flags);
static void TkMacOSXEventsCheckProc(ClientData clientData, int flags);

#ifdef TK_MAC_DEBUG_EVENTS
static const char *Tk_EventName[39] = {
    "",
    "",
    "KeyPress",		/*2*/
    "KeyRelease",      	/*3*/
    "ButtonPress",     	/*4*/
    "ButtonRelease",	/*5*/
    "MotionNotify",    	/*6*/
................................................................................
 * no longer, and perhaps never did need to set autoDisplay to NO, nor call
 * displayIfNeeded on our windows.  We can just leave all of that to the window
 * manager.
 */

/*
 * Since the contentView is the first responder for a Tk Window, it is
 * responsible for sending events up the responder chain.  We also check the
 * pasteboard here.
 */
- (void) sendEvent: (NSEvent *) theEvent
{
    [super sendEvent:theEvent];
    [NSApp tkCheckPasteboard];
#ifdef TK_MAC_DEBUG_EVENTS
    fprintf(stderr, "Sending event of type %d\n", (int)[theEvent type]);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * Tk_MacOSXSetupTkNotifier --
 *
 *	This procedure is called during Tk initialization to create the event
 *	source for TkAqua events.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A new event source is created.
 *
................................................................................
		 * Panic if main runloop is not on the main application thread.
		 */

		Tcl_Panic("Tk_MacOSXSetupTkNotifier: %s",
		    "first [load] of TkAqua has to occur in the main thread!");
	    }
	    Tcl_CreateEventSource(TkMacOSXEventsSetupProc,
		    TkMacOSXEventsCheckProc, NULL);

	    TkCreateExitHandler(TkMacOSXNotifyExitHandler, NULL);
	    Tcl_SetServiceMode(TCL_SERVICE_ALL);
	    TclMacOSXNotifierAddRunLoopMode(NSEventTrackingRunLoopMode);
	    TclMacOSXNotifierAddRunLoopMode(NSModalPanelRunLoopMode);
	}
    }
}
................................................................................
static void
TkMacOSXNotifyExitHandler(
    ClientData clientData)	/* Not used. */
{
    TSD_INIT();

    Tcl_DeleteEventSource(TkMacOSXEventsSetupProc,
	    TkMacOSXEventsCheckProc, NULL);

    tsdPtr->initialized = 0;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsSetupProc --
 *
 *	This procedure implements the setup part of the MacOSX event source. It
 *	is invoked by Tcl_DoOneEvent before calling TkMacOSXEventsProc to
 *	process all queued NSEvents.  In our case, all we need to do is to set
 *	the Tcl MaxBlockTime to 0 before starting the loop to process all
 *	queued NSEvents.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *
 *	If NSEvents are queued, then the maximum block time will be set to 0 to
 *	ensure that control returns immediately to Tcl.
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXEventsSetupProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];

    /*
     * runloopMode will be nil if we are in a Tcl event loop.
     */

    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {
	static const Tcl_Time zeroBlockTime = { 0, 0 };
	[NSApp _resetAutoreleasePool];

	/*
	 * Call this with dequeue=NO -- just checking if the queue is empty.
	 */

	NSEvent *currentEvent =
	        [NSApp nextEventMatchingMask:NSAnyEventMask
			untilDate:[NSDate distantPast]
			inMode:GetRunLoopMode(TkMacOSXGetModalSession())
			dequeue:NO];
	if (currentEvent) {
	    if (currentEvent.type > 0) {
		Tcl_SetMaxBlockTime(&zeroBlockTime);
	    }
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsCheckProc --
 *
 *	This procedure loops through all NSEvents waiting in the TKApplication
 *      event queue, generating X events from them.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	NSevents are used to generate X events, which are added to the Tcl
 *      event queue.
 *
 *----------------------------------------------------------------------
 */
static void
TkMacOSXEventsCheckProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];

    /*
     * runloopMode will be nil if we are in a Tcl event loop.
     */

    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {
	NSEvent *currentEvent = nil;
	NSEvent *testEvent = nil;
	NSModalSession modalSession;

	/*
	 * It is possible for the SetupProc to be called before this function
	 * returns.  This happens, for example, when we process an event which
	 * opens a modal window.  To prevent premature release of our
	 * application-wide autorelease pool by a nested call to the SetupProc,
	 * we must lock it here.
	 */

	[NSApp _lockAutoreleasePool];
	do {
	    modalSession = TkMacOSXGetModalSession();
	    testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
		    untilDate:[NSDate distantPast]
		    inMode:GetRunLoopMode(modalSession)
		    dequeue:NO];

	    /*
	     * We must not steal any events during LiveResize.
	     */

	    if (testEvent && [[testEvent window] inLiveResize]) {
		break;
	    }
	    currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
		    untilDate:[NSDate distantPast]
		    inMode:GetRunLoopMode(modalSession)
		    dequeue:YES];
	    if (currentEvent) {
		/*
		 * Generate Xevents.
		 */

		int oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);
		NSEvent *processedEvent = [NSApp tkProcessEvent:currentEvent];
		Tcl_SetServiceMode(oldServiceMode);
		if (processedEvent) {
#ifdef TK_MAC_DEBUG_EVENTS
		    TKLog(@"   event: %@", currentEvent);
#endif
		    if (modalSession) {
			[NSApp _modalSession:modalSession sendEvent:currentEvent];
		    } else {
			[NSApp sendEvent:currentEvent];
		    }
		}

	    } else {
		break;
	    }
	} while (1);

	/*
	 * Now we can unlock the pool.
	 */

	[NSApp _unlockAutoreleasePool];
    }
}

 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */

Changes to macosx/tkMacOSXRegion.c.

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
...
200
201
202
203
204
205
206
207
208
209
210
211

212
213
214
215
216
217
218
219
220
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
 *
 * TkRectInRegion --
 *
 *	Implements the equivelent of the X window function XRectInRegion. See
 *	Xwindow documentation for more details.
 *
 * Results:
 *	Returns RectanglePart or RectangleOut. Note that this is not a
 *	complete implementation since it doesn't test for RectangleIn.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

................................................................................
TkRectInRegion(
    TkRegion region,
    int x,
    int y,
    unsigned int width,
    unsigned int height)
{
    if ( TkMacOSXIsEmptyRegion(region) ) {
	    return RectangleOut;
	}
    else {
	const CGRect r = CGRectMake(x, y, width, height);

	return HIShapeIntersectsRect((HIShapeRef) region, &r) ?
	    RectanglePart : RectangleOut;
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkClipBox --
................................................................................
 *
 *----------------------------------------------------------------------
 */

void
TkClipBox(
    TkRegion r,
    XRectangle* rect_return)
{
    CGRect rect;

    HIShapeGetBounds((HIShapeRef) r, &rect);
    rect_return->x = rect.origin.x;
    rect_return->y = rect.origin.y;
    rect_return->width = rect.size.width;







|
|







 







|
|
<
|

>

|







 







|







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
...
200
201
202
203
204
205
206
207
208

209
210
211
212
213
214
215
216
217
218
219
220
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
 *
 * TkRectInRegion --
 *
 *	Implements the equivelent of the X window function XRectInRegion. See
 *	Xwindow documentation for more details.
 *
 * Results:
 *	Returns RectanglePart or RectangleOut. Note that this is not a complete
 *	implementation since it doesn't test for RectangleIn.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

................................................................................
TkRectInRegion(
    TkRegion region,
    int x,
    int y,
    unsigned int width,
    unsigned int height)
{
    if (TkMacOSXIsEmptyRegion(region)) {
	return RectangleOut;

    } else {
	const CGRect r = CGRectMake(x, y, width, height);

	return HIShapeIntersectsRect((HIShapeRef) region, &r) ?
		RectanglePart : RectangleOut;
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkClipBox --
................................................................................
 *
 *----------------------------------------------------------------------
 */

void
TkClipBox(
    TkRegion r,
    XRectangle *rect_return)
{
    CGRect rect;

    HIShapeGetBounds((HIShapeRef) r, &rect);
    rect_return->x = rect.origin.x;
    rect_return->y = rect.origin.y;
    rect_return->width = rect.size.width;

Changes to macosx/tkMacOSXScale.c.

47
48
49
50
51
52
53
54

55
56
57
58
59
60
61
62
63
64
..
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
...
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
...
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
...
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
...
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
...
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
...
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
...
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
...
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
...
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
 */
static ControlActionUPP scaleActionProc = NULL; /* Pointer to func. */

/*
 * Forward declarations for procedures defined later in this file:
 */

static void MacScaleEventProc(ClientData clientData, XEvent *eventPtr);

static pascal void ScaleActionProc(ControlRef theControl,
	ControlPartCode partCode);

 
/*
 *----------------------------------------------------------------------
 *
 * TkpCreateScale --
 *
 *	Allocate a new TkScale structure.
................................................................................

    macScalePtr->scaleHandle = NULL;
    if (scaleActionProc == NULL) {
	scaleActionProc = NewControlActionUPP(ScaleActionProc);
    }

    Tk_CreateEventHandler(tkwin, ButtonPressMask,
	    MacScaleEventProc, (ClientData) macScalePtr);

    return (TkScale *) macScalePtr;
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayScale --
 *
 *	This procedure is invoked as an idle handler to redisplay
 *	the contents of a scale widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The scale gets redisplayed.
 *
................................................................................
 *----------------------------------------------------------------------
 */

void
TkpDisplayScale(
    ClientData clientData)	/* Widget record for scale. */
{
    TkScale *scalePtr = (TkScale *) clientData;
    Tk_Window tkwin = scalePtr->tkwin;
    Tcl_Interp *interp = scalePtr->interp;
    int result;
    char string[TCL_DOUBLE_SPACE];
    MacScale *macScalePtr = (MacScale *) clientData;
    Rect r;
    WindowRef windowRef;
    CGrafPtr destPort, savePort;
    Boolean portChanged;
    MacDrawable *macDraw;
    SInt32 initialValue, minValue, maxValue;
    UInt16 numTicks;
................................................................................
	goto done;
    }

    /*
     * Invoke the scale's command if needed.
     */

    Tcl_Preserve((ClientData) scalePtr);
    if ((scalePtr->flags & INVOKE_COMMAND) && (scalePtr->command != NULL)) {
	Tcl_Preserve((ClientData) interp);
        if (snprintf(string, TCL_DOUBLE_SPACE, scalePtr->format,
                scalePtr->value) < 0) {
            string[TCL_DOUBLE_SPACE - 1] = '\0';
        }
	Tcl_DStringInit(&buf);
	Tcl_DStringAppend(&buf, scalePtr->command, -1);
	Tcl_DStringAppend(&buf, " ", -1);
................................................................................
	Tcl_DStringAppend(&buf, string, -1);
	result = Tcl_EvalEx(interp, Tcl_DStringValue(&buf), -1, 0);
	Tcl_DStringFree(&buf);
	if (result != TCL_OK) {
	    Tcl_AddErrorInfo(interp, "\n    (command executed by scale)");
	    Tcl_BackgroundException(interp, result);
	}
	Tcl_Release((ClientData) interp);
    }
    scalePtr->flags &= ~INVOKE_COMMAND;
    if (scalePtr->flags & SCALE_DELETED) {
	Tcl_Release((ClientData) scalePtr);
	return;
    }
    Tcl_Release((ClientData) scalePtr);

    /*
     * Now handle the part of redisplay that is the same for
     * horizontal and vertical scales: border and traversal
     * highlight.
     */

    if (scalePtr->highlightWidth != 0) {
	GC gc = Tk_GCForColor(scalePtr->highlightColorPtr, Tk_WindowId(tkwin));

	Tk_DrawFocusHighlight(tkwin, gc, scalePtr->highlightWidth,
		Tk_WindowId(tkwin));
................................................................................
    /*
     * Create Macintosh control.
     */

#define MAC_OSX_SCROLL_WIDTH 10

    if (scalePtr->orient == ORIENT_HORIZONTAL) {
	int offset = (Tk_Height(tkwin) - MAC_OSX_SCROLL_WIDTH)/2;

	if (offset < 0) {
	    offset = 0;
	}

	r.left = macDraw->xOff + scalePtr->inset;
	r.top = macDraw->yOff + offset;
	r.right = macDraw->xOff+Tk_Width(tkwin) - scalePtr->inset;
	r.bottom = macDraw->yOff + offset + MAC_OSX_SCROLL_WIDTH/2;
    } else {
	int offset = (Tk_Width(tkwin) - MAC_OSX_SCROLL_WIDTH)/2;

	if (offset < 0) {
	    offset = 0;
	}

	r.left = macDraw->xOff + offset;
	r.top = macDraw->yOff + scalePtr->inset;
	r.right = macDraw->xOff + offset + MAC_OSX_SCROLL_WIDTH/2;
	r.bottom = macDraw->yOff+Tk_Height(tkwin) - scalePtr->inset;
    }

    if (macScalePtr->scaleHandle == NULL) {
#ifdef TK_MAC_DEBUG_SCALE
	TkMacOSXDbgMsg("Initialising scale");
#endif
	initialValue = scalePtr->value;
................................................................................
	    numTicks = 0;
	} else {
	    numTicks = (maxValue - minValue)/scalePtr->tickInterval;
	}

	CreateSliderControl(windowRef, &r, initialValue, minValue, maxValue,
		kControlSliderPointsDownOrRight, numTicks, 1, scaleActionProc,
		&(macScalePtr->scaleHandle));
	SetControlReference(macScalePtr->scaleHandle, (UInt32) scalePtr);

	if (IsWindowActive(windowRef)) {
	    macScalePtr->flags |= ACTIVE;
	}
    } else {
	SetControlBounds(macScalePtr->scaleHandle, &r);
................................................................................
	SetControl32BitMaximum(macScalePtr->scaleHandle, scalePtr->toValue);
    }

    /*
     * Finally draw the control.
     */

    SetControlVisibility(macScalePtr->scaleHandle,true,true);
    HiliteControl(macScalePtr->scaleHandle,0);
    Draw1Control(macScalePtr->scaleHandle);

    if (portChanged) {
	QDSwapPort(savePort, NULL);
    }
done:
    scalePtr->flags &= ~REDRAW_ALL;
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpScaleElement --
 *
 *	Determine which part of a scale widget lies under a given
 *	point.
 *
 * Results:
 *	The return value is either TROUGH1, SLIDER, TROUGH2, or
 *	OTHER, depending on which of the scale's active elements
 *	(if any) is under the point at (x,y).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

................................................................................
    }

#ifdef TK_MAC_DEBUG_SCALE
    fprintf (stderr,"ScalePart %d, pos ( %d %d )\n", part, where.h, where.v );
#endif

    switch (part) {
	case inSlider:
	    return SLIDER;
	case inInc:
	    if (scalePtr->orient == ORIENT_VERTICAL) {
		return TROUGH1;
	    } else {
		return TROUGH2;
	    }
	case inDecr:
	    if (scalePtr->orient == ORIENT_VERTICAL) {
		return TROUGH2;
	    } else {
		return TROUGH1;
	    }
	default:
	    return OTHER;
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * MacScaleEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for
 *	ButtonPress events on scales.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get
 *	cleaned up. When it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
MacScaleEventProc(
    ClientData clientData,	/* Information about window. */
................................................................................
    Boolean portChanged;

#ifdef TK_MAC_DEBUG_SCALE
    fprintf(stderr,"MacScaleEventProc\n" );
#endif

    /*
     * To call Macintosh control routines we must have the port
     * set to the window containing the control. We will then test
     * which part of the control was hit and act accordingly.
     */

    destPort = TkMacOSXGetDrawablePort(Tk_WindowId(macScalePtr->info.tkwin));
    portChanged = QDSwapPort(destPort, &savePort);
    TkMacOSXSetUpClippingRgn(Tk_WindowId(macScalePtr->info.tkwin));

    TkMacOSXWinBounds((TkWindow *) macScalePtr->info.tkwin, &bounds);
................................................................................
 
/*
 *--------------------------------------------------------------
 *
 * ScaleActionProc --
 *
 *	Callback procedure used by the Macintosh toolbox call
 *	HandleControlClick. This call will update the display
 *	while the scrollbar is being manipulated by the user.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May change the display.
 *
................................................................................
    TkScale *scalePtr = (TkScale *) GetControlReference(theControl);

#ifdef TK_MAC_DEBUG_SCALE
    TkMacOSXDbgMsg("ScaleActionProc");
#endif
    value = GetControlValue(theControl);
    TkScaleSetValue(scalePtr, value, 1, 1);
    Tcl_Preserve((ClientData) scalePtr);
    TkMacOSXRunTclEventLoop();
    Tcl_Release((ClientData) scalePtr);
}
#endif
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */







|
>
|
|
<







 







|







 







|
|







 







|




|







 







|

|







 







|



|


|


|
|
<







 







|










|








|







 







|







 







|
|







 







|
<


|
|
|







 







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|








|
|





|
|







 







|
|
|







 







|
|







 







|

|











47
48
49
50
51
52
53
54
55
56
57

58
59
60
61
62
63
64
..
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
...
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
...
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
...
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
...
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
...
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
...
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
...
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
...
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
...
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
 */
static ControlActionUPP scaleActionProc = NULL; /* Pointer to func. */

/*
 * Forward declarations for procedures defined later in this file:
 */

static void		MacScaleEventProc(ClientData clientData,
			    XEvent *eventPtr);
static pascal void	ScaleActionProc(ControlRef theControl,
			    ControlPartCode partCode);

 
/*
 *----------------------------------------------------------------------
 *
 * TkpCreateScale --
 *
 *	Allocate a new TkScale structure.
................................................................................

    macScalePtr->scaleHandle = NULL;
    if (scaleActionProc == NULL) {
	scaleActionProc = NewControlActionUPP(ScaleActionProc);
    }

    Tk_CreateEventHandler(tkwin, ButtonPressMask,
	    MacScaleEventProc, macScalePtr);

    return (TkScale *) macScalePtr;
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayScale --
 *
 *	This procedure is invoked as an idle handler to redisplay the contents
 *	of a scale widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The scale gets redisplayed.
 *
................................................................................
 *----------------------------------------------------------------------
 */

void
TkpDisplayScale(
    ClientData clientData)	/* Widget record for scale. */
{
    TkScale *scalePtr = clientData;
    Tk_Window tkwin = scalePtr->tkwin;
    Tcl_Interp *interp = scalePtr->interp;
    int result;
    char string[TCL_DOUBLE_SPACE];
    MacScale *macScalePtr = clientData;
    Rect r;
    WindowRef windowRef;
    CGrafPtr destPort, savePort;
    Boolean portChanged;
    MacDrawable *macDraw;
    SInt32 initialValue, minValue, maxValue;
    UInt16 numTicks;
................................................................................
	goto done;
    }

    /*
     * Invoke the scale's command if needed.
     */

    Tcl_Preserve(scalePtr);
    if ((scalePtr->flags & INVOKE_COMMAND) && (scalePtr->command != NULL)) {
	Tcl_Preserve(interp);
        if (snprintf(string, TCL_DOUBLE_SPACE, scalePtr->format,
                scalePtr->value) < 0) {
            string[TCL_DOUBLE_SPACE - 1] = '\0';
        }
	Tcl_DStringInit(&buf);
	Tcl_DStringAppend(&buf, scalePtr->command, -1);
	Tcl_DStringAppend(&buf, " ", -1);
................................................................................
	Tcl_DStringAppend(&buf, string, -1);
	result = Tcl_EvalEx(interp, Tcl_DStringValue(&buf), -1, 0);
	Tcl_DStringFree(&buf);
	if (result != TCL_OK) {
	    Tcl_AddErrorInfo(interp, "\n    (command executed by scale)");
	    Tcl_BackgroundException(interp, result);
	}
	Tcl_Release(interp);
    }
    scalePtr->flags &= ~INVOKE_COMMAND;
    if (scalePtr->flags & SCALE_DELETED) {
	Tcl_Release(scalePtr);
	return;
    }
    Tcl_Release(scalePtr);

    /*
     * Now handle the part of redisplay that is the same for horizontal and
     * vertical scales: border and traversal highlight.

     */

    if (scalePtr->highlightWidth != 0) {
	GC gc = Tk_GCForColor(scalePtr->highlightColorPtr, Tk_WindowId(tkwin));

	Tk_DrawFocusHighlight(tkwin, gc, scalePtr->highlightWidth,
		Tk_WindowId(tkwin));
................................................................................
    /*
     * Create Macintosh control.
     */

#define MAC_OSX_SCROLL_WIDTH 10

    if (scalePtr->orient == ORIENT_HORIZONTAL) {
	int offset = (Tk_Height(tkwin) - MAC_OSX_SCROLL_WIDTH) / 2;

	if (offset < 0) {
	    offset = 0;
	}

	r.left = macDraw->xOff + scalePtr->inset;
	r.top = macDraw->yOff + offset;
	r.right = macDraw->xOff+Tk_Width(tkwin) - scalePtr->inset;
	r.bottom = macDraw->yOff + offset + MAC_OSX_SCROLL_WIDTH/2;
    } else {
	int offset = (Tk_Width(tkwin) - MAC_OSX_SCROLL_WIDTH) / 2;

	if (offset < 0) {
	    offset = 0;
	}

	r.left = macDraw->xOff + offset;
	r.top = macDraw->yOff + scalePtr->inset;
	r.right = macDraw->xOff + offset + MAC_OSX_SCROLL_WIDTH/2;
	r.bottom = macDraw->yOff + Tk_Height(tkwin) - scalePtr->inset;
    }

    if (macScalePtr->scaleHandle == NULL) {
#ifdef TK_MAC_DEBUG_SCALE
	TkMacOSXDbgMsg("Initialising scale");
#endif
	initialValue = scalePtr->value;
................................................................................
	    numTicks = 0;
	} else {
	    numTicks = (maxValue - minValue)/scalePtr->tickInterval;
	}

	CreateSliderControl(windowRef, &r, initialValue, minValue, maxValue,
		kControlSliderPointsDownOrRight, numTicks, 1, scaleActionProc,
		&macScalePtr->scaleHandle);
	SetControlReference(macScalePtr->scaleHandle, (UInt32) scalePtr);

	if (IsWindowActive(windowRef)) {
	    macScalePtr->flags |= ACTIVE;
	}
    } else {
	SetControlBounds(macScalePtr->scaleHandle, &r);
................................................................................
	SetControl32BitMaximum(macScalePtr->scaleHandle, scalePtr->toValue);
    }

    /*
     * Finally draw the control.
     */

    SetControlVisibility(macScalePtr->scaleHandle, true, true);
    HiliteControl(macScalePtr->scaleHandle, 0);
    Draw1Control(macScalePtr->scaleHandle);

    if (portChanged) {
	QDSwapPort(savePort, NULL);
    }
done:
    scalePtr->flags &= ~REDRAW_ALL;
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpScaleElement --
 *
 *	Determine which part of a scale widget lies under a given point.

 *
 * Results:
 *	The return value is either TROUGH1, SLIDER, TROUGH2, or OTHER,
 *	depending on which of the scale's active elements (if any) is under the
 *	point at (x,y).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

................................................................................
    }

#ifdef TK_MAC_DEBUG_SCALE
    fprintf (stderr,"ScalePart %d, pos ( %d %d )\n", part, where.h, where.v );
#endif

    switch (part) {
    case inSlider:
	return SLIDER;
    case inInc:
	if (scalePtr->orient == ORIENT_VERTICAL) {
	    return TROUGH1;
	} else {
	    return TROUGH2;
	}
    case inDecr:
	if (scalePtr->orient == ORIENT_VERTICAL) {
	    return TROUGH2;
	} else {
	    return TROUGH1;
	}
    default:
	return OTHER;
    }
}
 
/*
 *--------------------------------------------------------------
 *
 * MacScaleEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for ButtonPress events
 *	on scales.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get cleaned up. When
 *	it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
MacScaleEventProc(
    ClientData clientData,	/* Information about window. */
................................................................................
    Boolean portChanged;

#ifdef TK_MAC_DEBUG_SCALE
    fprintf(stderr,"MacScaleEventProc\n" );
#endif

    /*
     * To call Macintosh control routines we must have the port set to the
     * window containing the control. We will then test which part of the
     * control was hit and act accordingly.
     */

    destPort = TkMacOSXGetDrawablePort(Tk_WindowId(macScalePtr->info.tkwin));
    portChanged = QDSwapPort(destPort, &savePort);
    TkMacOSXSetUpClippingRgn(Tk_WindowId(macScalePtr->info.tkwin));

    TkMacOSXWinBounds((TkWindow *) macScalePtr->info.tkwin, &bounds);
................................................................................
 
/*
 *--------------------------------------------------------------
 *
 * ScaleActionProc --
 *
 *	Callback procedure used by the Macintosh toolbox call
 *	HandleControlClick. This call will update the display while the
 *	scrollbar is being manipulated by the user.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May change the display.
 *
................................................................................
    TkScale *scalePtr = (TkScale *) GetControlReference(theControl);

#ifdef TK_MAC_DEBUG_SCALE
    TkMacOSXDbgMsg("ScaleActionProc");
#endif
    value = GetControlValue(theControl);
    TkScaleSetValue(scalePtr, value, 1, 1);
    Tcl_Preserve(scalePtr);
    TkMacOSXRunTclEventLoop();
    Tcl_Release(scalePtr);
}
#endif
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */

Changes to macosx/tkMacOSXScrlbr.c.

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
..
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
...
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
...
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
...
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
...
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
...
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
...
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
...
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
...
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
 *	widget.
 *
 * Copyright (c) 1996 by Sun Microsystems, Inc.
 * Copyright 2001-2009, Apple Inc.
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright (c) 2015 Kevin Walzer/WordTech Commununications LLC.
 * Copyright (c) 2018 Marc Culler

 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"
#include "tkScrollbar.h"
#include "tkMacOSXPrivate.h"


#define MIN_SCROLLBAR_VALUE		0

/*
 * Minimum slider length, in pixels (designed to make sure that the slider is
 * always easy to grab with the mouse).
 */

#define MIN_SLIDER_LENGTH	5


/*Borrowed from ttkMacOSXTheme.c to provide appropriate scaling.*/


#ifdef __LP64__
#define RangeToFactor(maximum) (((double) (INT_MAX >> 1)) / (maximum))
#else
#define RangeToFactor(maximum) (((double) (LONG_MAX >> 1)) / (maximum))
#endif /* __LP64__ */

/*
 * Apple reversed the scroll direction with the release of OSX 10.7 Lion.
 */

#define SNOW_LEOPARD_STYLE (NSAppKitVersionNumber < 1138)

/*
 * Declaration of an extended scrollbar structure with Mac specific additions.
 */

typedef struct MacScrollbar {
    TkScrollbar information;	/* Generic scrollbar info. */
    GC troughGC;		/* For drawing trough. */
    GC copyGC;			/* Used for copying from pixmap onto screen. */
    Bool buttonDown;            /* Is the mouse button down? */
    Bool mouseOver;             /* Is the pointer over the scrollbar. */
    HIThemeTrackDrawInfo info;  /* Controls how the scrollbar is drawn. */
} MacScrollbar;

/* Used to initialize a MacScrollbar's info field. */
HIThemeTrackDrawInfo defaultInfo = {
    .version = 0,
    .min = 0.0,
    .max = 100.0,
................................................................................
 * The class procedure table for the scrollbar widget. All fields except size
 * are left initialized to NULL, which should happen automatically since the
 * variable is declared at this scope.
 */

const Tk_ClassProcs tkpScrollbarProcs = {
    sizeof(Tk_ClassProcs),	/* size */
    NULL,					/* worldChangedProc */
    NULL,					/* createProc */
    NULL					/* modalProc */
};





/* Information on scrollbar layout, metrics, and draw info.*/
typedef struct ScrollbarMetrics {
    SInt32 width, minThumbHeight;
    int minHeight, topArrowHeight, bottomArrowHeight;
    NSControlSize controlSize;
} ScrollbarMetrics;


static ScrollbarMetrics metrics = {
  15, 54, 26, 14, 14, kControlSizeNormal /* kThemeScrollBarMedium */
};


/*
 * Declarations of static functions defined later in this file:
 */

static void ScrollbarEventProc(ClientData clientData, XEvent *eventPtr);

static int ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr);

static void UpdateControlValues(TkScrollbar  *scrollPtr);

/*
 *----------------------------------------------------------------------
 *
 * TkpCreateScrollbar --
 *
 *	Allocate a new TkScrollbar structure.
 *
................................................................................
 *	Registers an event handler for the widget.
 *
 *----------------------------------------------------------------------
 */

TkScrollbar *
TkpCreateScrollbar(
		   Tk_Window tkwin)
{

    MacScrollbar *scrollPtr = (MacScrollbar *)ckalloc(sizeof(MacScrollbar));

    scrollPtr->troughGC = NULL;
    scrollPtr->copyGC = NULL;
    scrollPtr->info = defaultInfo;
    scrollPtr->buttonDown = false;

    Tk_CreateEventHandler(tkwin,
			  ExposureMask        |
			  StructureNotifyMask |
			  FocusChangeMask     |
			  ButtonPressMask     |
			  ButtonReleaseMask   |
			  EnterWindowMask     |
			  LeaveWindowMask     |
			  VisibilityChangeMask,
			  ScrollbarEventProc, scrollPtr);

    return (TkScrollbar *) scrollPtr;
}
 
/*
 *--------------------------------------------------------------
 *
 * TkpDisplayScrollbar --
 *
 *	This procedure redraws the contents of a scrollbar window. It is
 *	invoked as a do-when-idle handler, so it only runs when there's
 *	nothing else for the application to do.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws a scrollbar on the screen.
 *
 *--------------------------------------------------------------
 */

void
TkpDisplayScrollbar(
		    ClientData clientData)	/* Information about window. */
{
    register TkScrollbar *scrollPtr = (TkScrollbar *) clientData;
    MacScrollbar *msPtr = (MacScrollbar *) scrollPtr;
    register Tk_Window tkwin = scrollPtr->tkwin;
    TkWindow *winPtr = (TkWindow *) tkwin;
    TkMacOSXDrawingContext dc;

    scrollPtr->flags &= ~REDRAW_PENDING;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
  	return;
    }

    MacDrawable *macWin =  (MacDrawable *) winPtr->window;
    NSView *view = TkMacOSXDrawableView(macWin);
    if (!view ||


	macWin->flags & TK_DO_NOT_DRAW ||
	!TkMacOSXSetupDrawingContext((Drawable) macWin, NULL, 1, &dc)) {
      return;
    }

    CGFloat viewHeight = [view bounds].size.height;
    CGAffineTransform t = { .a = 1, .b = 0, .c = 0, .d = -1, .tx = 0,


			    .ty = viewHeight};


    CGContextConcatCTM(dc.context, t);


    /*Draw a 3D rectangle to provide a base for the native scrollbar.*/


    if (scrollPtr->highlightWidth != 0) {
    	GC fgGC, bgGC;

    	bgGC = Tk_GCForColor(scrollPtr->highlightBgColorPtr, (Pixmap) macWin);
    	if (scrollPtr->flags & GOT_FOCUS) {
    	    fgGC = Tk_GCForColor(scrollPtr->highlightColorPtr, (Pixmap) macWin);
    	} else {
    	    fgGC = bgGC;
    	}
    	TkpDrawHighlightBorder(tkwin, fgGC, bgGC, scrollPtr->highlightWidth,
    			       (Pixmap) macWin);
    }

    Tk_Draw3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder,
    		       scrollPtr->highlightWidth, scrollPtr->highlightWidth,
    		       Tk_Width(tkwin) - 2*scrollPtr->highlightWidth,
    		       Tk_Height(tkwin) - 2*scrollPtr->highlightWidth,
    		       scrollPtr->borderWidth, scrollPtr->relief);
    Tk_Fill3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder,
    		       scrollPtr->inset, scrollPtr->inset,
    		       Tk_Width(tkwin) - 2*scrollPtr->inset,
    		       Tk_Height(tkwin) - 2*scrollPtr->inset, 0, TK_RELIEF_FLAT);


    /* Update values and then draw the native scrollbar over the rectangle.*/


    UpdateControlValues(scrollPtr);

    if (SNOW_LEOPARD_STYLE) {

	HIThemeDrawTrack (&(msPtr->info), 0, dc.context, kHIThemeOrientationInverted);
    } else {

	HIThemeDrawTrack (&(msPtr->info), 0, dc.context, kHIThemeOrientationNormal);
    }
    TkMacOSXRestoreDrawingContext(&dc);

    scrollPtr->flags &= ~REDRAW_PENDING;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpComputeScrollbarGeometry --
 *
 *	After changes in a scrollbar's size or configuration, this procedure
 *	recomputes various geometry information used in displaying the
................................................................................
 *
 * Side effects:
 *	The scrollbar will be displayed differently.
 *
 *----------------------------------------------------------------------
 */



extern void
TkpComputeScrollbarGeometry(
    register TkScrollbar *scrollPtr)
                           /* Scrollbar whose geometry may have
                           * changed. */
{

   /*
    * The code below is borrowed from tkUnixScrlbr.c but has been adjusted to
    * account for some differences between macOS and X11. The Unix scrollbar
    * has an arrow button on each end.  On macOS 10.6 (Snow Leopard) the
    * scrollbars by default have both arrow buttons at the bottom or right.
    * (There is a preferences setting to use the Unix layout, but we are not
    * supporting that!)  On more recent versions of macOS there are no arrow
    * buttons at all. The case of no arrow buttons can be handled as a special
    * case of having both buttons at the end, but where scrollPtr->arrowLength
    * happens to be zero.  To adjust for having both arrows at the same end we
    * shift the scrollbar up by the arrowLength.
    */

    int fieldLength;

    if (scrollPtr->highlightWidth < 0) {
       scrollPtr->highlightWidth = 0;
    }
    scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth;
    if ([NSApp macMinorVersion] == 6) {
      scrollPtr->arrowLength = scrollPtr->width;
    } else {
      scrollPtr->arrowLength = 0;
    }
    fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin)
           : Tk_Width(scrollPtr->tkwin))
           - 2*(scrollPtr->arrowLength + scrollPtr->inset);
    if (fieldLength < 0) {
       fieldLength = 0;
    }
    scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction;
    scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction;

    /*
     * Adjust the slider so that some piece of it is always displayed in the
     * scrollbar and so that it has at least a minimal width (so it can be
     * grabbed with the mouse).
     */

    if (scrollPtr->sliderFirst > fieldLength - MIN_SLIDER_LENGTH) {
       scrollPtr->sliderFirst = fieldLength - MIN_SLIDER_LENGTH;
    }
    if (scrollPtr->sliderFirst < 0) {
       scrollPtr->sliderFirst = 0;
    }
    if (scrollPtr->sliderLast < scrollPtr->sliderFirst + MIN_SLIDER_LENGTH) {
       scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH;
    }
    if (scrollPtr->sliderLast > fieldLength) {
       scrollPtr->sliderLast = fieldLength;
    }
    scrollPtr->sliderFirst += -scrollPtr->arrowLength + scrollPtr->inset;
    scrollPtr->sliderLast += scrollPtr->inset;

    /*
     * Register the desired geometry for the window. Leave enough space for the
     * two arrows, if there are any arrows, plus a minimum-size slider, plus
     * border around the whole window, if any. Then arrange for the window to
     * be redisplayed.
     */

      if (scrollPtr->vertical) {
       Tk_GeometryRequest(scrollPtr->tkwin,
              scrollPtr->width + 2*scrollPtr->inset,
              2*(scrollPtr->arrowLength + scrollPtr->borderWidth
              + scrollPtr->inset) + metrics.minThumbHeight);
    } else {
       Tk_GeometryRequest(scrollPtr->tkwin,
              2*(scrollPtr->arrowLength + scrollPtr->borderWidth
              + scrollPtr->inset) + metrics.minThumbHeight,
              scrollPtr->width + 2*scrollPtr->inset);
    }
    Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset);
}

/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyScrollbar --
 *
 *	Free data structures associated with the scrollbar control.
 *
................................................................................
 *	Frees the GCs associated with the scrollbar.
 *
 *----------------------------------------------------------------------
 */

void
TkpDestroyScrollbar(
		    TkScrollbar *scrollPtr)
{
    MacScrollbar *macScrollPtr = (MacScrollbar *)scrollPtr;

    if (macScrollPtr->troughGC != None) {
	Tk_FreeGC(scrollPtr->display, macScrollPtr->troughGC);
    }
    if (macScrollPtr->copyGC != None) {
	Tk_FreeGC(scrollPtr->display, macScrollPtr->copyGC);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkpConfigureScrollbar --
 *
 *	This procedure is called after the generic code has finished
 *	processing configuration options, in order to configure platform
 *	specific options.  There are no such option on the Mac, however.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Currently, none.
 *
 *----------------------------------------------------------------------
 */

void
TkpConfigureScrollbar(
		      register TkScrollbar *scrollPtr)
{


}

/*
 *--------------------------------------------------------------
 *
 * TkpScrollbarPosition --
 *
 *	Determine the scrollbar element corresponding to a given position.
 *
................................................................................

int
TkpScrollbarPosition(
    register TkScrollbar *scrollPtr,
				/* Scrollbar widget record. */
    int x, int y)		/* Coordinates within scrollPtr's window. */
{

   /*
   * The code below is borrowed from tkUnixScrlbr.c and needs no adjustment
   * since it does not involve the arrow buttons.
   */

    int length, width, tmp;
    register const int inset = scrollPtr->inset;

    if (scrollPtr->vertical) {
  	length = Tk_Height(scrollPtr->tkwin);
  	width = Tk_Width(scrollPtr->tkwin);
    } else {
  	tmp = x;
  	x = y;
  	y = tmp;
  	length = Tk_Width(scrollPtr->tkwin);
  	width = Tk_Height(scrollPtr->tkwin);
    }

    if (x < inset || x >= width - inset ||
	y < inset || y >= length - inset) {
  	return OUTSIDE;
    }

    /*
     * Here we assume that the scrollbar is layed out with both arrow buttons
     * at the bottom (or right).  Except on 10.6, however, the arrows do not
     * actually exist, i.e. the arrowLength is 0.  These are the same
     * assumptions which are being made in TkpComputeScrollbarGeometry.
     */

    if (y < scrollPtr->sliderFirst + scrollPtr->arrowLength) {
  	return TOP_GAP;
      }
      if (y < scrollPtr->sliderLast) {
  	return SLIDER;
      }
      if (y < length - (2*scrollPtr->arrowLength + inset)) {
  	return BOTTOM_GAP;
      }


      /* On systems newer than 10.6 we have already returned. */


      if (y < length - (scrollPtr->arrowLength + inset)) {
  	return TOP_ARROW;
      }
      return BOTTOM_ARROW;
}

/*
 *--------------------------------------------------------------
 *
 * UpdateControlValues --
 *
 *	This procedure updates the Macintosh scrollbar control to
 *	display the values defined by the Tk scrollbar. This is the
 *	key interface to the Mac-native  scrollbar; the Unix bindings
 *	drive scrolling in the Tk window and all the Mac scrollbar has
 *	to do is redraw itself.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The Macintosh control is updated.
 *
 *--------------------------------------------------------------
 */

static void
UpdateControlValues(
		    TkScrollbar *scrollPtr)		/* Scrollbar data struct. */
{
    MacScrollbar *msPtr = (MacScrollbar *)scrollPtr;
    Tk_Window tkwin = scrollPtr->tkwin;
    MacDrawable *macWin = (MacDrawable *) Tk_WindowId(scrollPtr->tkwin);
    double dViewSize;
    HIRect  contrlRect;
    short width, height;

    NSView *view = TkMacOSXDrawableView(macWin);
    CGFloat viewHeight = [view bounds].size.height;
    NSRect frame;

    frame = NSMakeRect(macWin->xOff, macWin->yOff, Tk_Width(tkwin),
		       Tk_Height(tkwin));
    frame = NSInsetRect(frame, scrollPtr->inset, scrollPtr->inset);
    frame.origin.y = viewHeight - (frame.origin.y + frame.size.height);

    contrlRect = NSRectToCGRect(frame);
    msPtr->info.bounds = contrlRect;

    width = contrlRect.size.width;
................................................................................
    /*
     * Ensure we set scrollbar control bounds only once all size adjustments
     * have been computed.
     */

    msPtr->info.bounds = contrlRect;
    if (scrollPtr->vertical) {
      msPtr->info.attributes &= ~kThemeTrackHorizontal;
    } else {
      msPtr->info.attributes |= kThemeTrackHorizontal;
    }

    /*
     * Given the Tk parameters for the fractions of the start and end of the
     * thumb, the following calculation determines the location for the
     * Macintosh thumb. The Aqua scroll control works as follows. The
     * scrollbar's value is the position of the left (or top) side of the view
     * area in the content area being scrolled. The maximum value of the
     * control is therefore the dimension of the content area less the size of
     * the view area.
     */

    double maximum = 100,  factor;
    factor = RangeToFactor(maximum);

    dViewSize = (scrollPtr->lastFraction - scrollPtr->firstFraction)
	* factor;
    msPtr->info.max =  MIN_SCROLLBAR_VALUE +
	factor - dViewSize;
    msPtr->info.trackInfo.scrollbar.viewsize = dViewSize;
    if (scrollPtr->vertical) {
      if (SNOW_LEOPARD_STYLE) {
	msPtr->info.value = factor * scrollPtr->firstFraction;
      } else {
	msPtr->info.value = msPtr->info.max - factor * scrollPtr->firstFraction;

      }
    } else {

	 msPtr->info.value =  MIN_SCROLLBAR_VALUE + factor * scrollPtr->firstFraction;
    }

    if((scrollPtr->firstFraction <= 0.0 && scrollPtr->lastFraction >= 1.0)
       || height <= metrics.minHeight) {
    	msPtr->info.enableState = kThemeTrackHideTrack;
    } else {
        msPtr->info.enableState = kThemeTrackActive;
    	msPtr->info.attributes = kThemeTrackShowThumb |  kThemeTrackThumbRgnIsNotGhost;

    }

}

/*
 *--------------------------------------------------------------
 *
 * ScrollbarEvent --
 *
 *	This procedure is invoked in response to <ButtonPress>, <ButtonRelease>,
 *      <EnterNotify>, and <LeaveNotify> events. The Scrollbar appearance is
 *      modified for each event.
 *
 *--------------------------------------------------------------
 */

static int

ScrollbarEvent(TkScrollbar *scrollPtr, XEvent *eventPtr)

{
    MacScrollbar *msPtr = (MacScrollbar *)scrollPtr;


    /* The pressState does not indicate whether the moused button was
     * pressed at some location in the Scrollbar.  Rather, it indicates
     * that the scrollbar should appear as if it were pressed in that
     * location. The standard Mac behavior is that once the button is
     * pressed inside the Scrollbar the appearance should not change until
     * the button is released, even if the mouse moves outside of the
     * scrollbar.  However, if the mouse lies over the scrollbar but the
     * button is not pressed then the appearance should be the same as if
     * the button had been pressed on the slider, i.e. kThemeThumbPressed.
     * See the file Appearance.r, or HIToolbox.bridgesupport on 10.14.
     */

    if (eventPtr->type == ButtonPress) {
	msPtr->buttonDown = true;
	UpdateControlValues(scrollPtr);

	int where = TkpScrollbarPosition(scrollPtr,
					 eventPtr->xbutton.x,
					 eventPtr->xbutton.y);

	switch(where) {
	case OUTSIDE:
	    msPtr->info.trackInfo.scrollbar.pressState = 0;
	    break;
	case TOP_GAP:
	    msPtr->info.trackInfo.scrollbar.pressState = kThemeTopTrackPressed;
	    break;
	case SLIDER:
	    msPtr->info.trackInfo.scrollbar.pressState = kThemeThumbPressed;
	    break;
	case BOTTOM_GAP:
	    msPtr->info.trackInfo.scrollbar.pressState = kThemeBottomTrackPressed;

	    break;
	case TOP_ARROW:

	    /* This looks wrong and the docs say it is wrong but it works. */


	    msPtr->info.trackInfo.scrollbar.pressState = kThemeTopInsideArrowPressed;

	    break;
	case BOTTOM_ARROW:
	    msPtr->info.trackInfo.scrollbar.pressState = kThemeBottomOutsideArrowPressed;

	    break;
	}
    }
    if (eventPtr->type == ButtonRelease) {
	msPtr->buttonDown = false;
	if (!msPtr->mouseOver) {
	    msPtr->info.trackInfo.scrollbar.pressState = 0;
................................................................................
	msPtr->mouseOver = false;
	if (!msPtr->buttonDown) {
	    msPtr->info.trackInfo.scrollbar.pressState = 0;
	}
    }
    return TCL_OK;
}



/*
 *--------------------------------------------------------------
 *
 * ScrollbarEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various events on
 *	scrollbars.
................................................................................
 *	it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
ScrollbarEventProc(
		   ClientData clientData,	/* Information about window. */
		   XEvent *eventPtr)		/* Information about event. */
{
    TkScrollbar *scrollPtr = clientData;

    switch (eventPtr->type) {
    case UnmapNotify:
	TkMacOSXSetScrollbarGrow((TkWindow *) scrollPtr->tkwin, false);
	break;
................................................................................
    case LeaveNotify:
    	ScrollbarEvent(clientData, eventPtr);
	break;
    default:
	TkScrollbarEventProc(clientData, eventPtr);
    }
}

/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */







>







<










>
|
>
>

|

|






|











|







 







|
|
|


>
>
>

<






<

|

<





|
>
|
>
|
|







 







|

<
|







|
|
|
|
|
|
|
|
|










|
|












|

|








|


|

<
>
>
|
|
|



|
>
>
|
>
>


>
|
>
>










|



|
|
|
|

|
|
|

>
|
>
>



>
|

>
|





|







 







<
<



|
|

<
|
|
|
|
|
|
|
|
|
|
|
|




|



|

|


|
|

|











|


|


|


|











|
|
|
|
|

|
|
|
|



|







 







|

|








|





|
|
|












|

>
|
|
<







 







<
|
|
|
|





|
|

|
|
|
|
|



|
|










|
|
|
|
|
|
|
|
>
>
|
>
>
|
|
|
|

|





|
|
|
|
<












|

|



|





>

|







 







|

|












<
|
>
|
<
<
|


|
|
|
|
>
|

>
|


|
|



|
>

|
|
<





|
|
|





>
|
>

|

>
|
|
|
|
|
|
|
|
|
|





>

|
<
>
|










|
>


>
|
>
>
|
>


|
>







 







|
<
<







 







|
|







 







|








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
..
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
...
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
...
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
...
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
...
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
...
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
...
645
646
647
648
649
650
651
652


653
654
655
656
657
658
659
...
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
...
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
 *	widget.
 *
 * Copyright (c) 1996 by Sun Microsystems, Inc.
 * Copyright 2001-2009, Apple Inc.
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright (c) 2015 Kevin Walzer/WordTech Commununications LLC.
 * Copyright (c) 2018 Marc Culler
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"
#include "tkScrollbar.h"
#include "tkMacOSXPrivate.h"


#define MIN_SCROLLBAR_VALUE		0

/*
 * Minimum slider length, in pixels (designed to make sure that the slider is
 * always easy to grab with the mouse).
 */

#define MIN_SLIDER_LENGTH	5

/*
 * Borrowed from ttkMacOSXTheme.c to provide appropriate scaling.
 */

#ifdef __LP64__
#define RangeToFactor(maximum)	(((double) (INT_MAX >> 1)) / (maximum))
#else
#define RangeToFactor(maximum)	(((double) (LONG_MAX >> 1)) / (maximum))
#endif /* __LP64__ */

/*
 * Apple reversed the scroll direction with the release of OSX 10.7 Lion.
 */

#define SNOW_LEOPARD_STYLE	(NSAppKitVersionNumber < 1138)

/*
 * Declaration of an extended scrollbar structure with Mac specific additions.
 */

typedef struct MacScrollbar {
    TkScrollbar information;	/* Generic scrollbar info. */
    GC troughGC;		/* For drawing trough. */
    GC copyGC;			/* Used for copying from pixmap onto screen. */
    Bool buttonDown;            /* Is the mouse button down? */
    Bool mouseOver;             /* Is the pointer over the scrollbar. */
    HIThemeTrackDrawInfo info;	/* Controls how the scrollbar is drawn. */
} MacScrollbar;

/* Used to initialize a MacScrollbar's info field. */
HIThemeTrackDrawInfo defaultInfo = {
    .version = 0,
    .min = 0.0,
    .max = 100.0,
................................................................................
 * The class procedure table for the scrollbar widget. All fields except size
 * are left initialized to NULL, which should happen automatically since the
 * variable is declared at this scope.
 */

const Tk_ClassProcs tkpScrollbarProcs = {
    sizeof(Tk_ClassProcs),	/* size */
    NULL,			/* worldChangedProc */
    NULL,			/* createProc */
    NULL			/* modalProc */
};

/*
 * Information on scrollbar layout, metrics, and draw info.
 */


typedef struct ScrollbarMetrics {
    SInt32 width, minThumbHeight;
    int minHeight, topArrowHeight, bottomArrowHeight;
    NSControlSize controlSize;
} ScrollbarMetrics;


static ScrollbarMetrics metrics = {
    15, 54, 26, 14, 14, kControlSizeNormal /* kThemeScrollBarMedium */
};


/*
 * Declarations of static functions defined later in this file:
 */

static void		ScrollbarEventProc(ClientData clientData,
			    XEvent *eventPtr);
static int		ScrollbarEvent(TkScrollbar *scrollPtr,
			    XEvent *eventPtr);
static void		UpdateControlValues(TkScrollbar *scrollPtr);
 
/*
 *----------------------------------------------------------------------
 *
 * TkpCreateScrollbar --
 *
 *	Allocate a new TkScrollbar structure.
 *
................................................................................
 *	Registers an event handler for the widget.
 *
 *----------------------------------------------------------------------
 */

TkScrollbar *
TkpCreateScrollbar(
    Tk_Window tkwin)
{

    MacScrollbar *scrollPtr = ckalloc(sizeof(MacScrollbar));

    scrollPtr->troughGC = NULL;
    scrollPtr->copyGC = NULL;
    scrollPtr->info = defaultInfo;
    scrollPtr->buttonDown = false;

    Tk_CreateEventHandler(tkwin,
	    ExposureMask        |
	    StructureNotifyMask |
	    FocusChangeMask     |
	    ButtonPressMask     |
	    ButtonReleaseMask   |
	    EnterWindowMask     |
	    LeaveWindowMask     |
	    VisibilityChangeMask,
	    ScrollbarEventProc, scrollPtr);

    return (TkScrollbar *) scrollPtr;
}
 
/*
 *--------------------------------------------------------------
 *
 * TkpDisplayScrollbar --
 *
 *	This procedure redraws the contents of a scrollbar window. It is
 *	invoked as a do-when-idle handler, so it only runs when there's nothing
 *	else for the application to do.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Draws a scrollbar on the screen.
 *
 *--------------------------------------------------------------
 */

void
TkpDisplayScrollbar(
    ClientData clientData)	/* Information about window. */
{
    register TkScrollbar *scrollPtr = clientData;
    MacScrollbar *msPtr = (MacScrollbar *) scrollPtr;
    register Tk_Window tkwin = scrollPtr->tkwin;
    TkWindow *winPtr = (TkWindow *) tkwin;
    TkMacOSXDrawingContext dc;

    scrollPtr->flags &= ~REDRAW_PENDING;

    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
	return;
    }

    MacDrawable *macWin = (MacDrawable *) winPtr->window;
    NSView *view = TkMacOSXDrawableView(macWin);


    if ((view == NULL)
	    || (macWin->flags & TK_DO_NOT_DRAW)
	    || !TkMacOSXSetupDrawingContext((Drawable) macWin, NULL, 1, &dc)) {
	return;
    }

    CGFloat viewHeight = [view bounds].size.height;
    CGAffineTransform t = {
	.a = 1, .b = 0,
	.c = 0, .d = -1,
	.tx = 0, .ty = viewHeight
    };

    CGContextConcatCTM(dc.context, t);

    /*
     * Draw a 3D rectangle to provide a base for the native scrollbar.
     */

    if (scrollPtr->highlightWidth != 0) {
    	GC fgGC, bgGC;

    	bgGC = Tk_GCForColor(scrollPtr->highlightBgColorPtr, (Pixmap) macWin);
    	if (scrollPtr->flags & GOT_FOCUS) {
    	    fgGC = Tk_GCForColor(scrollPtr->highlightColorPtr, (Pixmap) macWin);
    	} else {
    	    fgGC = bgGC;
    	}
    	TkpDrawHighlightBorder(tkwin, fgGC, bgGC, scrollPtr->highlightWidth,
    		(Pixmap) macWin);
    }

    Tk_Draw3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder,
	    scrollPtr->highlightWidth, scrollPtr->highlightWidth,
	    Tk_Width(tkwin) - 2*scrollPtr->highlightWidth,
	    Tk_Height(tkwin) - 2*scrollPtr->highlightWidth,
	    scrollPtr->borderWidth, scrollPtr->relief);
    Tk_Fill3DRectangle(tkwin, (Pixmap) macWin, scrollPtr->bgBorder,
	    scrollPtr->inset, scrollPtr->inset,
	    Tk_Width(tkwin) - 2*scrollPtr->inset,
	    Tk_Height(tkwin) - 2*scrollPtr->inset, 0, TK_RELIEF_FLAT);

    /*
     * Update values and then draw the native scrollbar over the rectangle.
     */

    UpdateControlValues(scrollPtr);

    if (SNOW_LEOPARD_STYLE) {
	HIThemeDrawTrack(&msPtr->info, 0, dc.context,
		kHIThemeOrientationInverted);
    } else {
	HIThemeDrawTrack(&msPtr->info, 0, dc.context,
		kHIThemeOrientationNormal);
    }
    TkMacOSXRestoreDrawingContext(&dc);

    scrollPtr->flags &= ~REDRAW_PENDING;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpComputeScrollbarGeometry --
 *
 *	After changes in a scrollbar's size or configuration, this procedure
 *	recomputes various geometry information used in displaying the
................................................................................
 *
 * Side effects:
 *	The scrollbar will be displayed differently.
 *
 *----------------------------------------------------------------------
 */



extern void
TkpComputeScrollbarGeometry(
    register TkScrollbar *scrollPtr)
				/* Scrollbar whose geometry may have
				 * changed. */
{

    /*
     * The code below is borrowed from tkUnixScrlbr.c but has been adjusted to
     * account for some differences between macOS and X11. The Unix scrollbar
     * has an arrow button on each end.  On macOS 10.6 (Snow Leopard) the
     * scrollbars by default have both arrow buttons at the bottom or right.
     * (There is a preferences setting to use the Unix layout, but we are not
     * supporting that!)  On more recent versions of macOS there are no arrow
     * buttons at all. The case of no arrow buttons can be handled as a special
     * case of having both buttons at the end, but where scrollPtr->arrowLength
     * happens to be zero.  To adjust for having both arrows at the same end we
     * shift the scrollbar up by the arrowLength.
     */

    int fieldLength;

    if (scrollPtr->highlightWidth < 0) {
	scrollPtr->highlightWidth = 0;
    }
    scrollPtr->inset = scrollPtr->highlightWidth + scrollPtr->borderWidth;
    if ([NSApp macMinorVersion] == 6) {
	scrollPtr->arrowLength = scrollPtr->width;
    } else {
	scrollPtr->arrowLength = 0;
    }
    fieldLength = (scrollPtr->vertical ? Tk_Height(scrollPtr->tkwin)
	    : Tk_Width(scrollPtr->tkwin))
	    - 2*(scrollPtr->arrowLength + scrollPtr->inset);
    if (fieldLength < 0) {
	fieldLength = 0;
    }
    scrollPtr->sliderFirst = fieldLength*scrollPtr->firstFraction;
    scrollPtr->sliderLast = fieldLength*scrollPtr->lastFraction;

    /*
     * Adjust the slider so that some piece of it is always displayed in the
     * scrollbar and so that it has at least a minimal width (so it can be
     * grabbed with the mouse).
     */

    if (scrollPtr->sliderFirst > fieldLength - MIN_SLIDER_LENGTH) {
	scrollPtr->sliderFirst = fieldLength - MIN_SLIDER_LENGTH;
    }
    if (scrollPtr->sliderFirst < 0) {
	scrollPtr->sliderFirst = 0;
    }
    if (scrollPtr->sliderLast < scrollPtr->sliderFirst + MIN_SLIDER_LENGTH) {
	scrollPtr->sliderLast = scrollPtr->sliderFirst + MIN_SLIDER_LENGTH;
    }
    if (scrollPtr->sliderLast > fieldLength) {
	scrollPtr->sliderLast = fieldLength;
    }
    scrollPtr->sliderFirst += -scrollPtr->arrowLength + scrollPtr->inset;
    scrollPtr->sliderLast += scrollPtr->inset;

    /*
     * Register the desired geometry for the window. Leave enough space for the
     * two arrows, if there are any arrows, plus a minimum-size slider, plus
     * border around the whole window, if any. Then arrange for the window to
     * be redisplayed.
     */

    if (scrollPtr->vertical) {
	Tk_GeometryRequest(scrollPtr->tkwin,
		scrollPtr->width + 2*scrollPtr->inset,
		2*(scrollPtr->arrowLength + scrollPtr->borderWidth
		+ scrollPtr->inset) + metrics.minThumbHeight);
    } else {
	Tk_GeometryRequest(scrollPtr->tkwin,
		2*(scrollPtr->arrowLength + scrollPtr->borderWidth
		+ scrollPtr->inset) + metrics.minThumbHeight,
		scrollPtr->width + 2*scrollPtr->inset);
    }
    Tk_SetInternalBorder(scrollPtr->tkwin, scrollPtr->inset);
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDestroyScrollbar --
 *
 *	Free data structures associated with the scrollbar control.
 *
................................................................................
 *	Frees the GCs associated with the scrollbar.
 *
 *----------------------------------------------------------------------
 */

void
TkpDestroyScrollbar(
    TkScrollbar *scrollPtr)
{
    MacScrollbar *macScrollPtr = (MacScrollbar *) scrollPtr;

    if (macScrollPtr->troughGC != None) {
	Tk_FreeGC(scrollPtr->display, macScrollPtr->troughGC);
    }
    if (macScrollPtr->copyGC != None) {
	Tk_FreeGC(scrollPtr->display, macScrollPtr->copyGC);
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpConfigureScrollbar --
 *
 *	This procedure is called after the generic code has finished processing
 *	configuration options, in order to configure platform specific options.
 *	There are no such option on the Mac, however.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Currently, none.
 *
 *----------------------------------------------------------------------
 */

void
TkpConfigureScrollbar(
    register TkScrollbar *scrollPtr)
{
    /* empty */
}
 

/*
 *--------------------------------------------------------------
 *
 * TkpScrollbarPosition --
 *
 *	Determine the scrollbar element corresponding to a given position.
 *
................................................................................

int
TkpScrollbarPosition(
    register TkScrollbar *scrollPtr,
				/* Scrollbar widget record. */
    int x, int y)		/* Coordinates within scrollPtr's window. */
{

    /*
     * The code below is borrowed from tkUnixScrlbr.c and needs no adjustment
     * since it does not involve the arrow buttons.
     */

    int length, width, tmp;
    register const int inset = scrollPtr->inset;

    if (scrollPtr->vertical) {
	length = Tk_Height(scrollPtr->tkwin);
	width = Tk_Width(scrollPtr->tkwin);
    } else {
	tmp = x;
	x = y;
	y = tmp;
	length = Tk_Width(scrollPtr->tkwin);
	width = Tk_Height(scrollPtr->tkwin);
    }

    if (x < inset || x >= width - inset ||
	    y < inset || y >= length - inset) {
	return OUTSIDE;
    }

    /*
     * Here we assume that the scrollbar is layed out with both arrow buttons
     * at the bottom (or right).  Except on 10.6, however, the arrows do not
     * actually exist, i.e. the arrowLength is 0.  These are the same
     * assumptions which are being made in TkpComputeScrollbarGeometry.
     */

    if (y < scrollPtr->sliderFirst + scrollPtr->arrowLength) {
	return TOP_GAP;
    }
    if (y < scrollPtr->sliderLast) {
	return SLIDER;
    }
    if (y < length - (2*scrollPtr->arrowLength + inset)) {
	return BOTTOM_GAP;
    }

    /*
     * On systems newer than 10.6 we have already returned.
     */

    if (y < length - (scrollPtr->arrowLength + inset)) {
	return TOP_ARROW;
    }
    return BOTTOM_ARROW;
}
 
/*
 *--------------------------------------------------------------
 *
 * UpdateControlValues --
 *
 *	This procedure updates the Macintosh scrollbar control to display the
 *	values defined by the Tk scrollbar. This is the key interface to the
 *	Mac-native scrollbar; the Unix bindings drive scrolling in the Tk
 *	window and all the Mac scrollbar has to do is redraw itself.

 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The Macintosh control is updated.
 *
 *--------------------------------------------------------------
 */

static void
UpdateControlValues(
    TkScrollbar *scrollPtr)		/* Scrollbar data struct. */
{
    MacScrollbar *msPtr = (MacScrollbar *) scrollPtr;
    Tk_Window tkwin = scrollPtr->tkwin;
    MacDrawable *macWin = (MacDrawable *) Tk_WindowId(scrollPtr->tkwin);
    double dViewSize;
    HIRect contrlRect;
    short width, height;

    NSView *view = TkMacOSXDrawableView(macWin);
    CGFloat viewHeight = [view bounds].size.height;
    NSRect frame;

    frame = NSMakeRect(macWin->xOff, macWin->yOff, Tk_Width(tkwin),
	    Tk_Height(tkwin));
    frame = NSInsetRect(frame, scrollPtr->inset, scrollPtr->inset);
    frame.origin.y = viewHeight - (frame.origin.y + frame.size.height);

    contrlRect = NSRectToCGRect(frame);
    msPtr->info.bounds = contrlRect;

    width = contrlRect.size.width;
................................................................................
    /*
     * Ensure we set scrollbar control bounds only once all size adjustments
     * have been computed.
     */

    msPtr->info.bounds = contrlRect;
    if (scrollPtr->vertical) {
	msPtr->info.attributes &= ~kThemeTrackHorizontal;
    } else {
	msPtr->info.attributes |= kThemeTrackHorizontal;
    }

    /*
     * Given the Tk parameters for the fractions of the start and end of the
     * thumb, the following calculation determines the location for the
     * Macintosh thumb. The Aqua scroll control works as follows. The
     * scrollbar's value is the position of the left (or top) side of the view
     * area in the content area being scrolled. The maximum value of the
     * control is therefore the dimension of the content area less the size of
     * the view area.
     */


    double maximum = 100, factor = RangeToFactor(maximum);

    dViewSize = (scrollPtr->lastFraction - scrollPtr->firstFraction) * factor;


    msPtr->info.max = MIN_SCROLLBAR_VALUE + factor - dViewSize;
    msPtr->info.trackInfo.scrollbar.viewsize = dViewSize;
    if (scrollPtr->vertical) {
	if (SNOW_LEOPARD_STYLE) {
	    msPtr->info.value = factor * scrollPtr->firstFraction;
	} else {
	    msPtr->info.value = msPtr->info.max -
		    factor * scrollPtr->firstFraction;
	}
    } else {
	msPtr->info.value = MIN_SCROLLBAR_VALUE +
		factor * scrollPtr->firstFraction;
    }

    if ((scrollPtr->firstFraction <= 0.0 && scrollPtr->lastFraction >= 1.0)
	    || height <= metrics.minHeight) {
    	msPtr->info.enableState = kThemeTrackHideTrack;
    } else {
        msPtr->info.enableState = kThemeTrackActive;
    	msPtr->info.attributes =
		kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost;
    }
}
 

/*
 *--------------------------------------------------------------
 *
 * ScrollbarEvent --
 *
 *	This procedure is invoked in response to <ButtonPress>,
 *      <ButtonRelease>, <EnterNotify>, and <LeaveNotify> events.  The
 *      Scrollbar appearance is modified for each event.
 *
 *--------------------------------------------------------------
 */

static int
ScrollbarEvent(
    TkScrollbar *scrollPtr,
    XEvent *eventPtr)
{
    MacScrollbar *msPtr = (MacScrollbar *) scrollPtr;

    /*
     * The pressState does not indicate whether the moused button was pressed
     * at some location in the Scrollbar.  Rather, it indicates that the
     * scrollbar should appear as if it were pressed in that location. The
     * standard Mac behavior is that once the button is pressed inside the
     * Scrollbar the appearance should not change until the button is released,
     * even if the mouse moves outside of the scrollbar.  However, if the mouse
     * lies over the scrollbar but the button is not pressed then the
     * appearance should be the same as if the button had been pressed on the
     * slider, i.e. kThemeThumbPressed.  See the file Appearance.r, or
     * HIToolbox.bridgesupport on 10.14.
     */

    if (eventPtr->type == ButtonPress) {
	msPtr->buttonDown = true;
	UpdateControlValues(scrollPtr);

	int where = TkpScrollbarPosition(scrollPtr,
		eventPtr->xbutton.x, eventPtr->xbutton.y);


	switch (where) {
	case OUTSIDE:
	    msPtr->info.trackInfo.scrollbar.pressState = 0;
	    break;
	case TOP_GAP:
	    msPtr->info.trackInfo.scrollbar.pressState = kThemeTopTrackPressed;
	    break;
	case SLIDER:
	    msPtr->info.trackInfo.scrollbar.pressState = kThemeThumbPressed;
	    break;
	case BOTTOM_GAP:
	    msPtr->info.trackInfo.scrollbar.pressState =
		    kThemeBottomTrackPressed;
	    break;
	case TOP_ARROW:
	    /*
	     * This looks wrong and the docs say it is wrong but it works.
	     */

	    msPtr->info.trackInfo.scrollbar.pressState =
		    kThemeTopInsideArrowPressed;
	    break;
	case BOTTOM_ARROW:
	    msPtr->info.trackInfo.scrollbar.pressState =
		    kThemeBottomOutsideArrowPressed;
	    break;
	}
    }
    if (eventPtr->type == ButtonRelease) {
	msPtr->buttonDown = false;
	if (!msPtr->mouseOver) {
	    msPtr->info.trackInfo.scrollbar.pressState = 0;
................................................................................
	msPtr->mouseOver = false;
	if (!msPtr->buttonDown) {
	    msPtr->info.trackInfo.scrollbar.pressState = 0;
	}
    }
    return TCL_OK;
}
 


/*
 *--------------------------------------------------------------
 *
 * ScrollbarEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various events on
 *	scrollbars.
................................................................................
 *	it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
ScrollbarEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkScrollbar *scrollPtr = clientData;

    switch (eventPtr->type) {
    case UnmapNotify:
	TkMacOSXSetScrollbarGrow((TkWindow *) scrollPtr->tkwin, false);
	break;
................................................................................
    case LeaveNotify:
    	ScrollbarEvent(clientData, eventPtr);
	break;
    default:
	TkScrollbarEventProc(clientData, eventPtr);
    }
}
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */

Changes to macosx/tkMacOSXSend.c.

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
..
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
				 * list. */
} RegisteredInterp;

/*
 * A registry of all interpreters for a display is kept in a property
 * "InterpRegistry" on the root window of the display. It is organized as a
 * series of zero or more concatenated strings (in no particular order), each
 * of the form
 *	window space name '\0'
 * where "window" is the hex id of the comm. window to use to talk to an
 * interpreter named "name".
 *
 * When the registry is being manipulated by an application (e.g. to add or
 * remove an entry), it is loaded into memory using a structure of the
 * following type:
................................................................................
				 * none. See format description above; this is
				 * *not* terminated by the first null
				 * character. Dynamically allocated. */
    int allocedByX;		/* Non-zero means must free property with
				 * XFree; zero means use ckfree. */
} NameRegistry;

static int initialized = 0; /* A flag to denote if we have initialized
				 * yet. */

static RegisteredInterp *interpListPtr = NULL;
				/* List of all interpreters registered by this
				 * process. */

/*







|







 







|







47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
..
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
				 * list. */
} RegisteredInterp;

/*
 * A registry of all interpreters for a display is kept in a property
 * "InterpRegistry" on the root window of the display. It is organized as a
 * series of zero or more concatenated strings (in no particular order), each
 * of the form:
 *	window space name '\0'
 * where "window" is the hex id of the comm. window to use to talk to an
 * interpreter named "name".
 *
 * When the registry is being manipulated by an application (e.g. to add or
 * remove an entry), it is loaded into memory using a structure of the
 * following type:
................................................................................
				 * none. See format description above; this is
				 * *not* terminated by the first null
				 * character. Dynamically allocated. */
    int allocedByX;		/* Non-zero means must free property with
				 * XFree; zero means use ckfree. */
} NameRegistry;

static int initialized = 0;	/* A flag to denote if we have initialized
				 * yet. */

static RegisteredInterp *interpListPtr = NULL;
				/* List of all interpreters registered by this
				 * process. */

/*

Changes to macosx/tkMacOSXSubwindows.c.

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
...
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
...
181
182
183
184
185
186
187

188
189
190
191
192
193
194
195
...
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
...
294
295
296
297
298
299
300

301
302
303
304
305
306
307
...
312
313
314
315
316
317
318
319
320
321
322
323
324
325

326
327
328
329
330
331
332
333
334
...
353
354
355
356
357
358
359

360
361
362

363
364

365
366
367
368
369
370
371
...
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
...
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
...
449
450
451
452
453
454
455

456

457
458
459
460
461
462
463
464
...
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
...
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
...
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
...
690
691
692
693
694
695
696
697
698
699
700
701
702

703
704

705
706
707
708
709
710
711
...
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
...
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
...
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
...
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
...
968
969
970
971
972
973
974



975


976
977
978
979
980
981
982
....
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
....
1066
1067
1068
1069
1070
1071
1072

1073
1074
1075
1076
1077
1078
1079
....
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
....
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
....
1277
1278
1279
1280
1281
1282
1283
1284

1285
1286
1287
1288
1289
1290
1291
....
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
     * deleting is being tracked by the grab code.
     */

    TkPointerDeadWindow(macWin->winPtr);
    TkMacOSXSelDeadWindow(macWin->winPtr);
    macWin->toplevel->referenceCount--;

    if (!Tk_IsTopLevel(macWin->winPtr) ) {
	TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW);
	if (macWin->winPtr->parentPtr != NULL) {
	    TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr);
	}
	if (macWin->visRgn) {
	    CFRelease(macWin->visRgn);
	}
................................................................................
    display->request++;
    macWin->winPtr->flags |= TK_MAPPED;
    if (Tk_IsTopLevel(macWin->winPtr)) {
	if (!Tk_IsEmbedded(macWin->winPtr)) {
	    NSWindow *win = TkMacOSXDrawableWindow(window);

	    /*
	     * We want to activate Tk when a toplevel is mapped
	     * but we must not supply YES here.  This is because
	     * during Tk initialization the root window is mapped
	     * before applicationDidFinishLaunching returns. Forcing
	     * the app to activate too early can make the menu bar
	     * unresponsive.
	     */

	    TkMacOSXApplyWindowAttributes(macWin->winPtr, win);
	    [win setExcludedFromWindowsMenu:NO];
	    [NSApp activateIgnoringOtherApps:NO];
	    [[win contentView] setNeedsDisplay:YES];
	    if ( [win canBecomeKeyWindow] ) {
		[win makeKeyAndOrderFront:NSApp];
	    } else {
		[win orderFrontRegardless];
	    }
	    
	    /*
	     * In some cases the toplevel will not be drawn unless we process
................................................................................

	    /*
	     * Rebuild the container's clipping region and display
	     * the window.
	     */

	    TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr);

	    TkMacOSXInvalClipRgns((Tk_Window)contWinPtr);
	    TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW);
	}
	TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr);

	/*
	 * We only need to send the MapNotify event for toplevel windows.
	 */
................................................................................
	event.xany.display = display;

	event.xmap.window = window;
	event.xmap.type = MapNotify;
	event.xmap.event = window;
	event.xmap.override_redirect = macWin->winPtr->atts.override_redirect;
	Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL);

    } else {

	/*
	 * Rebuild the parent's clipping region and display the window.
	 *
	 */

	TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr);
	TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW);
    }

    /*
................................................................................
    XEvent event;

    display->request++;
    if (Tk_IsTopLevel(winPtr)) {
	if (!Tk_IsEmbedded(winPtr) &&
		winPtr->wmInfoPtr->hints.initial_state!=IconicState) {
	    NSWindow *win = TkMacOSXDrawableWindow(window);

	    [win orderOut:nil];
	}
	TkMacOSXInvalClipRgns((Tk_Window) winPtr);

	/*
	 * We only need to send the UnmapNotify event for toplevel windows.
	 */
................................................................................

	event.xunmap.type = UnmapNotify;
	event.xunmap.window = window;
	event.xunmap.event = window;
	event.xunmap.from_configure = false;
	Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL);
    } else {

	/*
	 * Rebuild the visRgn clip region for the parent so it will be allowed
	 * to draw in the space from which this subwindow was removed.
	 */

	if (parentPtr && parentPtr->privatePtr->visRgn) {

	    TkMacOSXInvalidateViewRegion(TkMacOSXDrawableView(parentPtr->privatePtr),
					 parentPtr->privatePtr->visRgn);
	}
	TkMacOSXInvalClipRgns((Tk_Window) parentPtr);
	TkMacOSXUpdateClipRgn(parentPtr);
    }
    winPtr->flags &= ~TK_MAPPED;
}
 
................................................................................
XResizeWindow(
    Display *display,		/* Display. */
    Window window,		/* Window. */
    unsigned int width,
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    NSRect r = [w contentRectForFrameRect:[w frame]];

	    r.origin.y += r.size.height - height;
	    r.size.width = width;
	    r.size.height = height;
	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
    } else {
	MoveResizeWindow(macWin);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * XMoveResizeWindow --
 *
 *	Move or resize a given X window. See X windows documentation
 *	for further details.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;
	if (w) {



	    /* We explicitly convert everything to doubles so we don't get
	     * surprised (again) by what happens when you do arithmetic with
	     * unsigned ints.
	     */

	    CGFloat X = (CGFloat)x;
	    CGFloat Y = (CGFloat)y;
	    CGFloat Width = (CGFloat)width;
	    CGFloat Height = (CGFloat)height;
	    CGFloat XOff = (CGFloat)macWin->winPtr->wmInfoPtr->xInParent;
	    CGFloat YOff = (CGFloat)macWin->winPtr->wmInfoPtr->yInParent;
	    NSRect r = NSMakeRect(X + XOff,
	    			  tkMacOSXZeroScreenHeight - Y - YOff - Height,
	    			  Width, Height);

	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
    } else {
	MoveResizeWindow(macWin);
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * XMoveWindow --
 *
 *	Move a given X window. See X windows documentation for further
 *	details.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
    int x, int y)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {

	    [w setFrameTopLeftPoint:NSMakePoint(x, tkMacOSXZeroScreenHeight - y)];
	}
    } else {
	MoveResizeWindow(macWin);
    }
}
 
/*
................................................................................

    if (Tk_IsEmbedded(macWin->winPtr)) {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr);

	if (contWinPtr) {
	    macParent = contWinPtr->privatePtr;
	} else {

	    /*
	     * Here we should handle out of process embedding. At this point,
	     * we are assuming that the changes.x,y is not maintained, if you
	     * need the info get it from Tk_GetRootCoords, and that the
	     * toplevel sits at 0,0 when it is drawn.
	     */
	}
    } else {

	/*
	 * TODO: update all xOff & yOffs
	 */

	macParent = macWin->winPtr->parentPtr->privatePtr;
	parentBorderwidth = macWin->winPtr->parentPtr->changes.border_width;
    }
................................................................................
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	TkWmRestackToplevel(macWin->winPtr, Above, NULL);
    } else {

	/*
	 * TODO: this should generate damage
	 */
    }
}
 
#if 0
................................................................................
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	TkWmRestackToplevel(macWin->winPtr, Below, NULL);
    } else {

        /*
	 * TODO: this should generate damage
	 */
    }
}
#endif
 
................................................................................
	Rect bounds;
	NSRect r;

	if (view) {
	    TkMacOSXInvalClipRgns((Tk_Window) winPtr->parentPtr);
	    TkMacOSXWinBounds(winPtr, &bounds);
	    r = NSMakeRect(bounds.left,
		[view bounds].size.height - bounds.bottom,
		bounds.right - bounds.left, bounds.bottom - bounds.top);
	    [view setNeedsDisplayInRect:r];
	}
    }


    /* TkGenWMMoveRequestEvent(macWin->winPtr,
	    macWin->winPtr->changes.x, macWin->winPtr->changes.y); */

}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetDrawingEnabled --
 *
................................................................................
 *	The clipping regions for the window and its children are cleared.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXSetDrawingEnabled(
	TkWindow *winPtr,
	int flag)
{
    TkWindow *childPtr;
    MacDrawable *macWin = winPtr->privatePtr;

    if (macWin) {
	if (flag ) {
	    macWin->flags &= ~TK_DO_NOT_DRAW;
	} else {
	    macWin->flags |= TK_DO_NOT_DRAW;
	}
    }

    /*
     * Set the flag for all children & their descendants, excluding
     * Toplevels. (??? Do we need to exclude Toplevels?)
     */

    childPtr = winPtr->childList;
    while (childPtr) {
	if (!Tk_IsTopLevel(childPtr)) {
	    TkMacOSXSetDrawingEnabled(childPtr, flag);
	}
................................................................................
		if (!HIShapeIsEmpty(diffRgn)) {
		    macWin->visRgn = HIShapeCreateCopy(rgn);
		}
		CFRelease(diffRgn);
	    }
	    CFRelease(rgn);
	} else {

	    /*
	     * An unmapped window has empty clip regions to prevent any
	     * (erroneous) drawing into it or its children from becoming
	     * visible. [Bug 940117]
	     */

	    if (!Tk_IsTopLevel(winPtr)) {
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXVisableClipRgn --
 *
 *	This function returns the Macintosh clipping region for the given
 *	window. The caller is responsible for disposing of the returned
 *	region via TkDestroyRegion().
 *
 * Results:
 *	The region.
 *
 * Side effects:
 *	None.
 *
................................................................................
TkRegion
TkMacOSXVisableClipRgn(
    TkWindow *winPtr)
{
    if (winPtr->privatePtr->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(winPtr);
    }
    return (TkRegion)HIShapeCreateMutableCopy(winPtr->privatePtr->visRgn);
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXInvalidateViewRegion --
 *
................................................................................
 * Side effects:
 *	Damage is created.
 *
 *----------------------------------------------------------------------
 */

static OSStatus



InvalViewRect(int msg, HIShapeRef rgn, const CGRect *rect, void *ref) {


    static CGAffineTransform t;
    NSView *view = ref;

    if (!view) {
	return paramErr;
    }
    switch (msg) {
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSWindow*
TkMacOSXDrawableWindow(
    Drawable drawable)
{
    MacDrawable *macWin = (MacDrawable *) drawable;
    NSWindow *result = nil;

    if (!macWin || macWin->flags & TK_IS_PIXMAP) {
................................................................................
	    macWin->toplevel->winPtr->wmInfoPtr->window) {
	result = macWin->toplevel->winPtr->wmInfoPtr->window;
    } else if (macWin->winPtr && macWin->winPtr->wmInfoPtr &&
	    macWin->winPtr->wmInfoPtr->window) {
	result = macWin->winPtr->wmInfoPtr->window;
    } else if (macWin->toplevel && (macWin->toplevel->flags & TK_EMBEDDED)) {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);

	if (contWinPtr) {
	    result = TkMacOSXDrawableWindow((Drawable) contWinPtr->privatePtr);
	}
    }
    return result;
}

................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSView*
TkMacOSXDrawableView(
    MacDrawable *macWin)
{
    NSView *result = nil;

    if (!macWin) {
	result = nil;
    } else if (!macWin->toplevel) {
	result = macWin->view;
    } else if (!(macWin->toplevel->flags & TK_EMBEDDED)) {
	result = macWin->toplevel->view;
    } else {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);

	if (contWinPtr) {
	    result = TkMacOSXDrawableView(contWinPtr->privatePtr);
	}
    }
    return result;
}
 
................................................................................
 *----------------------------------------------------------------------
 */

void *
TkMacOSXGetRootControl(
    Drawable drawable)
{

    /*
     * will probably need to fix this up for embedding
     */

    return TkMacOSXDrawableView((MacDrawable *) drawable);
}
 
................................................................................
 */

void
TkMacOSXWinBounds(
    TkWindow *winPtr,
    void *bounds)
{
    Rect *b = (Rect *)bounds;

    b->left = winPtr->privatePtr->xOff;
    b->top = winPtr->privatePtr->yOff;
    b->right = b->left + winPtr->changes.width;
    b->bottom = b->top + winPtr->changes.height;
}
 
/*
................................................................................
    TkWindow *winPtr,
    int deltaX,
    int deltaY)
{
    TkWindow *childPtr;

    if (winPtr->privatePtr == NULL) {

	/*
	 * We haven't called Tk_MakeWindowExist for this window yet. The offset
	 * information will be postponed and calulated at that time. (This will
	 * usually only happen when a mapped parent is being moved but has
	 * child windows that have yet to be mapped.)
	 */








|







 







|
|
<
|
|
|






|







 







>
|







 







<

<


<







 







>







 







<






>
|
|







 







>



>


>







 







|
|







 







<

>
>
|




|
|
|
|
|
|
|
|
|
>












|
<







 







>

>
|







 







<








<







 







<







 







<







 







|
|




>
|
|
>







 







|
|





|







|
|







 







<







 







|
|







 







|







 







>
>
>
|
>
>







 







|







 







>







 







|













>







 







<







 







|
>







 







<







61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
...
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
...
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
...
199
200
201
202
203
204
205

206

207
208

209
210
211
212
213
214
215
...
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
...
310
311
312
313
314
315
316

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
...
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
...
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
...
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
...
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
...
495
496
497
498
499
500
501

502
503
504
505
506
507
508
509

510
511
512
513
514
515
516
...
594
595
596
597
598
599
600

601
602
603
604
605
606
607
...
628
629
630
631
632
633
634

635
636
637
638
639
640
641
...
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
...
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
...
901
902
903
904
905
906
907

908
909
910
911
912
913
914
...
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
...
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
...
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
....
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
....
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
....
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
....
1168
1169
1170
1171
1172
1173
1174

1175
1176
1177
1178
1179
1180
1181
....
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
....
1349
1350
1351
1352
1353
1354
1355

1356
1357
1358
1359
1360
1361
1362
     * deleting is being tracked by the grab code.
     */

    TkPointerDeadWindow(macWin->winPtr);
    TkMacOSXSelDeadWindow(macWin->winPtr);
    macWin->toplevel->referenceCount--;

    if (!Tk_IsTopLevel(macWin->winPtr)) {
	TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW);
	if (macWin->winPtr->parentPtr != NULL) {
	    TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr);
	}
	if (macWin->visRgn) {
	    CFRelease(macWin->visRgn);
	}
................................................................................
    display->request++;
    macWin->winPtr->flags |= TK_MAPPED;
    if (Tk_IsTopLevel(macWin->winPtr)) {
	if (!Tk_IsEmbedded(macWin->winPtr)) {
	    NSWindow *win = TkMacOSXDrawableWindow(window);

	    /*
	     * We want to activate Tk when a toplevel is mapped but we must not
	     * supply YES here.  This is because during Tk initialization the

	     * root window is mapped before applicationDidFinishLaunching
	     * returns. Forcing the app to activate too early can make the menu
	     * bar unresponsive.
	     */

	    TkMacOSXApplyWindowAttributes(macWin->winPtr, win);
	    [win setExcludedFromWindowsMenu:NO];
	    [NSApp activateIgnoringOtherApps:NO];
	    [[win contentView] setNeedsDisplay:YES];
	    if ([win canBecomeKeyWindow]) {
		[win makeKeyAndOrderFront:NSApp];
	    } else {
		[win orderFrontRegardless];
	    }
	    
	    /*
	     * In some cases the toplevel will not be drawn unless we process
................................................................................

	    /*
	     * Rebuild the container's clipping region and display
	     * the window.
	     */

	    TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr);

	    TkMacOSXInvalClipRgns((Tk_Window) contWinPtr);
	    TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW);
	}
	TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr);

	/*
	 * We only need to send the MapNotify event for toplevel windows.
	 */
................................................................................
	event.xany.display = display;

	event.xmap.window = window;
	event.xmap.type = MapNotify;
	event.xmap.event = window;
	event.xmap.override_redirect = macWin->winPtr->atts.override_redirect;
	Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL);

    } else {

	/*
	 * Rebuild the parent's clipping region and display the window.

	 */

	TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr->parentPtr);
	TkMacOSXInvalidateWindow(macWin, TK_PARENT_WINDOW);
    }

    /*
................................................................................
    XEvent event;

    display->request++;
    if (Tk_IsTopLevel(winPtr)) {
	if (!Tk_IsEmbedded(winPtr) &&
		winPtr->wmInfoPtr->hints.initial_state!=IconicState) {
	    NSWindow *win = TkMacOSXDrawableWindow(window);

	    [win orderOut:nil];
	}
	TkMacOSXInvalClipRgns((Tk_Window) winPtr);

	/*
	 * We only need to send the UnmapNotify event for toplevel windows.
	 */
................................................................................

	event.xunmap.type = UnmapNotify;
	event.xunmap.window = window;
	event.xunmap.event = window;
	event.xunmap.from_configure = false;
	Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL);
    } else {

	/*
	 * Rebuild the visRgn clip region for the parent so it will be allowed
	 * to draw in the space from which this subwindow was removed.
	 */

	if (parentPtr && parentPtr->privatePtr->visRgn) {
	    TkMacOSXInvalidateViewRegion(
		    TkMacOSXDrawableView(parentPtr->privatePtr),
		    parentPtr->privatePtr->visRgn);
	}
	TkMacOSXInvalClipRgns((Tk_Window) parentPtr);
	TkMacOSXUpdateClipRgn(parentPtr);
    }
    winPtr->flags &= ~TK_MAPPED;
}
 
................................................................................
XResizeWindow(
    Display *display,		/* Display. */
    Window window,		/* Window. */
    unsigned int width,
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    NSRect r = [w contentRectForFrameRect:[w frame]];

	    r.origin.y += r.size.height - height;
	    r.size.width = width;
	    r.size.height = height;
	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
    } else {
	MoveResizeWindow(macWin);
................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * XMoveResizeWindow --
 *
 *	Move or resize a given X window. See X windows documentation for
 *	further details.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;


	if (w) {
	    /*
	     * We explicitly convert everything to doubles so we don't get
	     * surprised (again) by what happens when you do arithmetic with
	     * unsigned ints.
	     */

	    CGFloat X = (CGFloat) x;
	    CGFloat Y = (CGFloat) y;
	    CGFloat Width = (CGFloat) width;
	    CGFloat Height = (CGFloat) height;
	    CGFloat XOff = (CGFloat) macWin->winPtr->wmInfoPtr->xInParent;
	    CGFloat YOff = (CGFloat) macWin->winPtr->wmInfoPtr->yInParent;
	    NSRect r = NSMakeRect(
		    X + XOff, tkMacOSXZeroScreenHeight - Y - YOff - Height,
	    	    Width, Height);

	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
    } else {
	MoveResizeWindow(macWin);
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * XMoveWindow --
 *
 *	Move a given X window. See X windows documentation for further details.

 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
................................................................................
    int x, int y)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    [w setFrameTopLeftPoint: NSMakePoint(
		    x, tkMacOSXZeroScreenHeight - y)];
	}
    } else {
	MoveResizeWindow(macWin);
    }
}
 
/*
................................................................................

    if (Tk_IsEmbedded(macWin->winPtr)) {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->winPtr);

	if (contWinPtr) {
	    macParent = contWinPtr->privatePtr;
	} else {

	    /*
	     * Here we should handle out of process embedding. At this point,
	     * we are assuming that the changes.x,y is not maintained, if you
	     * need the info get it from Tk_GetRootCoords, and that the
	     * toplevel sits at 0,0 when it is drawn.
	     */
	}
    } else {

	/*
	 * TODO: update all xOff & yOffs
	 */

	macParent = macWin->winPtr->parentPtr->privatePtr;
	parentBorderwidth = macWin->winPtr->parentPtr->changes.border_width;
    }
................................................................................
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	TkWmRestackToplevel(macWin->winPtr, Above, NULL);
    } else {

	/*
	 * TODO: this should generate damage
	 */
    }
}
 
#if 0
................................................................................
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	TkWmRestackToplevel(macWin->winPtr, Below, NULL);
    } else {

        /*
	 * TODO: this should generate damage
	 */
    }
}
#endif
 
................................................................................
	Rect bounds;
	NSRect r;

	if (view) {
	    TkMacOSXInvalClipRgns((Tk_Window) winPtr->parentPtr);
	    TkMacOSXWinBounds(winPtr, &bounds);
	    r = NSMakeRect(bounds.left,
		    [view bounds].size.height - bounds.bottom,
		    bounds.right - bounds.left, bounds.bottom - bounds.top);
	    [view setNeedsDisplayInRect:r];
	}
    }

#if 0
    TkGenWMMoveRequestEvent(macWin->winPtr,
	    macWin->winPtr->changes.x, macWin->winPtr->changes.y);
#endif
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetDrawingEnabled --
 *
................................................................................
 *	The clipping regions for the window and its children are cleared.
 *
 *----------------------------------------------------------------------
 */

void
TkMacOSXSetDrawingEnabled(
    TkWindow *winPtr,
    int flag)
{
    TkWindow *childPtr;
    MacDrawable *macWin = winPtr->privatePtr;

    if (macWin) {
	if (flag) {
	    macWin->flags &= ~TK_DO_NOT_DRAW;
	} else {
	    macWin->flags |= TK_DO_NOT_DRAW;
	}
    }

    /*
     * Set the flag for all children & their descendants, excluding Toplevels.
     * (??? Do we need to exclude Toplevels?)
     */

    childPtr = winPtr->childList;
    while (childPtr) {
	if (!Tk_IsTopLevel(childPtr)) {
	    TkMacOSXSetDrawingEnabled(childPtr, flag);
	}
................................................................................
		if (!HIShapeIsEmpty(diffRgn)) {
		    macWin->visRgn = HIShapeCreateCopy(rgn);
		}
		CFRelease(diffRgn);
	    }
	    CFRelease(rgn);
	} else {

	    /*
	     * An unmapped window has empty clip regions to prevent any
	     * (erroneous) drawing into it or its children from becoming
	     * visible. [Bug 940117]
	     */

	    if (!Tk_IsTopLevel(winPtr)) {
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXVisableClipRgn --
 *
 *	This function returns the Macintosh clipping region for the given
 *	window. The caller is responsible for disposing of the returned region
 *	via TkDestroyRegion().
 *
 * Results:
 *	The region.
 *
 * Side effects:
 *	None.
 *
................................................................................
TkRegion
TkMacOSXVisableClipRgn(
    TkWindow *winPtr)
{
    if (winPtr->privatePtr->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(winPtr);
    }
    return (TkRegion) HIShapeCreateMutableCopy(winPtr->privatePtr->visRgn);
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXInvalidateViewRegion --
 *
................................................................................
 * Side effects:
 *	Damage is created.
 *
 *----------------------------------------------------------------------
 */

static OSStatus
InvalViewRect(
    int msg,
    HIShapeRef rgn,
    const CGRect *rect,
    void *ref)
{
    static CGAffineTransform t;
    NSView *view = ref;

    if (!view) {
	return paramErr;
    }
    switch (msg) {
................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSWindow *
TkMacOSXDrawableWindow(
    Drawable drawable)
{
    MacDrawable *macWin = (MacDrawable *) drawable;
    NSWindow *result = nil;

    if (!macWin || macWin->flags & TK_IS_PIXMAP) {
................................................................................
	    macWin->toplevel->winPtr->wmInfoPtr->window) {
	result = macWin->toplevel->winPtr->wmInfoPtr->window;
    } else if (macWin->winPtr && macWin->winPtr->wmInfoPtr &&
	    macWin->winPtr->wmInfoPtr->window) {
	result = macWin->winPtr->wmInfoPtr->window;
    } else if (macWin->toplevel && (macWin->toplevel->flags & TK_EMBEDDED)) {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);

	if (contWinPtr) {
	    result = TkMacOSXDrawableWindow((Drawable) contWinPtr->privatePtr);
	}
    }
    return result;
}

................................................................................
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

NSView *
TkMacOSXDrawableView(
    MacDrawable *macWin)
{
    NSView *result = nil;

    if (!macWin) {
	result = nil;
    } else if (!macWin->toplevel) {
	result = macWin->view;
    } else if (!(macWin->toplevel->flags & TK_EMBEDDED)) {
	result = macWin->toplevel->view;
    } else {
	TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);

	if (contWinPtr) {
	    result = TkMacOSXDrawableView(contWinPtr->privatePtr);
	}
    }
    return result;
}
 
................................................................................
 *----------------------------------------------------------------------
 */

void *
TkMacOSXGetRootControl(
    Drawable drawable)
{

    /*
     * will probably need to fix this up for embedding
     */

    return TkMacOSXDrawableView((MacDrawable *) drawable);
}
 
................................................................................
 */

void
TkMacOSXWinBounds(
    TkWindow *winPtr,
    void *bounds)
{
    Rect *b = (Rect *) bounds;

    b->left = winPtr->privatePtr->xOff;
    b->top = winPtr->privatePtr->yOff;
    b->right = b->left + winPtr->changes.width;
    b->bottom = b->top + winPtr->changes.height;
}
 
/*
................................................................................
    TkWindow *winPtr,
    int deltaX,
    int deltaY)
{
    TkWindow *childPtr;

    if (winPtr->privatePtr == NULL) {

	/*
	 * We haven't called Tk_MakeWindowExist for this window yet. The offset
	 * information will be postponed and calulated at that time. (This will
	 * usually only happen when a mapped parent is being moved but has
	 * child windows that have yet to be mapped.)
	 */

Changes to macosx/tkMacOSXWindowEvent.c.

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
..
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
...
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
...
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
...
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
...
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
...
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
...
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
...
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
...
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
....
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
....
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110

- (void) windowBoundsChanged: (NSNotification *) notification
{
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
#endif
    BOOL movedOnly = [[notification name]
			 isEqualToString:NSWindowDidMoveNotification];
    NSWindow *w = [notification object];
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);

    if (winPtr) {
	WmInfo *wmPtr = winPtr->wmInfoPtr;
	NSRect bounds = [w frame];
	int x, y, width = -1, height = -1, flags = 0;
................................................................................
	if (!movedOnly && (winPtr->changes.width != bounds.size.width ||
		winPtr->changes.height !=  bounds.size.height)) {
	    width = bounds.size.width - wmPtr->xInParent;
	    height = bounds.size.height - wmPtr->yInParent;
	    flags |= TK_SIZE_CHANGED;
	}
	if (Tcl_GetServiceMode() != TCL_SERVICE_NONE) {

	    /*
	     * Propagate geometry changes immediately.
	     */

	    flags |= TK_MACOSX_HANDLE_EVENT_IMMEDIATELY;
	}

................................................................................
	}
    }
}

- (NSRect)windowWillUseStandardFrame:(NSWindow *)window
                        defaultFrame:(NSRect)newFrame
{

    /*
     * This method needs to be implemented in order for [NSWindow isZoomed]
     * to give the correct answer.  But it suffices to always validate
     * every request.
     */

    return newFrame;
}

- (NSSize)window:(NSWindow *)window
  willUseFullScreenContentSize:(NSSize)proposedSize
{

    /*
     * We don't need to change the proposed size, but we do need to
     * implement this method.  Otherwise the full screen window will
     * be sized to the screen's visibleFrame, leaving black bands at
     * the top and bottom.
     */

    return proposedSize;
}

- (void) windowEnteredFullScreen: (NSNotification *) notification
{
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
................................................................................
	if (_windowWithMouse == w) {
	    _windowWithMouse = nil;
	    [w release];
	}
    }

    /*
     * If necessary, TkGenWMDestroyEvent() handles [close]ing the window,
     * so can always return NO from -windowShouldClose: for a Tk window.
     */

    return (winPtr ? NO : YES);
}


#ifdef TK_MAC_DEBUG_NOTIFICATIONS

- (void) windowDragStart: (NSNotification *) notification
{
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
}
................................................................................
    NSWindow *w = [notification object];
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);

    if (winPtr) {
	//Tk_UnmapWindow((Tk_Window) winPtr);
    }
}


#endif /* TK_MAC_DEBUG_NOTIFICATIONS */

- (void) _setupWindowNotifications
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

................................................................................
#pragma mark -
 
/*
 *----------------------------------------------------------------------
 *
 * TkpAppIsDrawing --
 *
 *      A widget display procedure can call this to determine whether it
 *      is being run inside of the drawRect method.  This is needed for
 *      some tests, especially of the Text widget, which record data in
 *      a global Tcl variable and assume that display procedures will be
 *      run in a predictable sequence as Tcl idle tasks.
 *
 * Results:
 *	True only while running the drawRect method of a TKContentView;
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE Bool
TkpAppIsDrawing(void) {
    return [NSApp isDrawing];
}

 
/*
 *----------------------------------------------------------------------
 *
 * GenerateUpdates --
 *
 *	Given a Macintosh update region and a Tk window this function geneates
................................................................................
	if (flags & TK_LOCATION_CHANGED) {
	    wmPtr->x = x;
	    wmPtr->y = y;
	}
	if ((flags & TK_SIZE_CHANGED) && !(wmPtr->flags & WM_SYNC_PENDING) &&
		((width != Tk_Width(tkwin)) || (height != Tk_Height(tkwin)))) {
	    if ((wmPtr->width == -1) && (width == winPtr->reqWidth)) {

		/*
		 * Don't set external width, since the user didn't change it
		 * from what the widgets asked for.
		 */

	    } else if (wmPtr->gridWin != NULL) {
		wmPtr->width = wmPtr->reqGridWidth
			+ (width - winPtr->reqWidth)/wmPtr->widthInc;
		if (wmPtr->width < 0) {
		    wmPtr->width = 0;
		}
	    } else {
		wmPtr->width = width;
	    }

	    if ((wmPtr->height == -1) && (height == winPtr->reqHeight)) {

		/*
		 * Don't set external height, since the user didn't change it
		 * from what the widgets asked for.
		 */

	    } else if (wmPtr->gridWin != NULL) {
		wmPtr->height = wmPtr->reqGridHeight
			+ (height - winPtr->reqHeight)/wmPtr->heightInc;
		if (wmPtr->height < 0) {
		    wmPtr->height = 0;
		}
	    } else {
................................................................................
		wmPtr->height = height;
	    }

	    wmPtr->configWidth = width;
	    wmPtr->configHeight = height;
	}
    }


    /*
     * Now set up the changes structure. Under X we wait for the
     * ConfigureNotify to set these values. On the Mac we know imediatly that
     * this is what we want - so we just set them. However, we need to make
     * sure the windows clipping region is marked invalid so the change is
     * visible to the subwindow.
................................................................................
#ifdef TK_MAC_DEBUG_DRAWING
    TkWindow *winPtr = TkMacOSXGetTkWindow([self window]);
    if (winPtr) fprintf(stderr, "drawRect: drawing %s\n",
			Tk_PathName(winPtr));
#endif

    /*
     * We do not allow recursive calls to drawRect, but we only log
     * them on OSX > 10.13, where they should never happen.
     */

    if ([NSApp isDrawing]) {
	if ([NSApp macMinorVersion] > 13) {
	    TKLog(@"WARNING: a recursive call to drawRect was aborted.");
	}
	return;
................................................................................
    if (winPtr) {
	unsigned int width = (unsigned int)newsize.width;
	unsigned int height=(unsigned int)newsize.height;
	ClientData oldArg;
    	Tk_RestrictProc *oldProc;

	/*
	 * This can be called from outside the Tk event loop.
	 * Since it calls Tcl_DoOneEvent, we need to make sure we
	 * don't clobber the AutoreleasePool set up by the caller.
	 */

	[NSApp _lockAutoreleasePool];

	/*
	 * Disable Tk drawing until the window has been completely configured.
	 */
................................................................................
	TkMacOSXSetDrawingEnabled(winPtr, 0);

	 /*
	  * Generate and handle a ConfigureNotify event for the new size.
	  */

	TkGenWMConfigureEvent(tkwin, Tk_X(tkwin), Tk_Y(tkwin), width, height,
			      TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY);
    	oldProc = Tk_RestrictEvents(ConfigureRestrictProc, NULL, &oldArg);
    	Tk_RestrictEvents(oldProc, oldArg, &oldArg);

	/*
	 * Now that Tk has configured all subwindows, create the clip regions.
	 */

................................................................................
	 * were created when the expose events were processed.
	 */
	while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) {}
    }
}

/*
 * This method is called when a user changes between light and dark mode.
 * The implementation here generates a Tk virtual event which can be bound
 * to a function that redraws the window in an appropriate style.
 */

- (void) viewDidChangeEffectiveAppearance
{
    XVirtualEvent event;
    int x, y;
    NSWindow *w = [self window];
................................................................................
    } else {
        event.name = Tk_GetUid("LightAqua");
    }
    Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL);
}

/*
 * This is no-op on 10.7 and up because Apple has removed this widget,
 * but we are leaving it here for backwards compatibility.
 */

- (void) tkToolbarButton: (id) sender
{
#ifdef TK_MAC_DEBUG_EVENTS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd);
#endif







|







 







<







 







<

|
|
|








<

|
|
|
<

>







 







|
|




<







 







<







 







|
|
|
|
|









>




<







 







<




<











<




<







 







<







 







|
|







 







|
|
|







 







|







 







|
|
|







 







|
|







64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
..
87
88
89
90
91
92
93

94
95
96
97
98
99
100
...
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
...
201
202
203
204
205
206
207
208
209
210
211
212
213

214
215
216
217
218
219
220
...
247
248
249
250
251
252
253

254
255
256
257
258
259
260
...
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
...
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
...
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
...
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
...
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
....
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
....
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

- (void) windowBoundsChanged: (NSNotification *) notification
{
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
#endif
    BOOL movedOnly = [[notification name]
	    isEqualToString:NSWindowDidMoveNotification];
    NSWindow *w = [notification object];
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);

    if (winPtr) {
	WmInfo *wmPtr = winPtr->wmInfoPtr;
	NSRect bounds = [w frame];
	int x, y, width = -1, height = -1, flags = 0;
................................................................................
	if (!movedOnly && (winPtr->changes.width != bounds.size.width ||
		winPtr->changes.height !=  bounds.size.height)) {
	    width = bounds.size.width - wmPtr->xInParent;
	    height = bounds.size.height - wmPtr->yInParent;
	    flags |= TK_SIZE_CHANGED;
	}
	if (Tcl_GetServiceMode() != TCL_SERVICE_NONE) {

	    /*
	     * Propagate geometry changes immediately.
	     */

	    flags |= TK_MACOSX_HANDLE_EVENT_IMMEDIATELY;
	}

................................................................................
	}
    }
}

- (NSRect)windowWillUseStandardFrame:(NSWindow *)window
                        defaultFrame:(NSRect)newFrame
{

    /*
     * This method needs to be implemented in order for [NSWindow isZoomed] to
     * give the correct answer. But it suffices to always validate every
     * request.
     */

    return newFrame;
}

- (NSSize)window:(NSWindow *)window
  willUseFullScreenContentSize:(NSSize)proposedSize
{

    /*
     * We don't need to change the proposed size, but we do need to implement
     * this method.  Otherwise the full screen window will be sized to the
     * screen's visibleFrame, leaving black bands at the top and bottom.

     */

    return proposedSize;
}

- (void) windowEnteredFullScreen: (NSNotification *) notification
{
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
................................................................................
	if (_windowWithMouse == w) {
	    _windowWithMouse = nil;
	    [w release];
	}
    }

    /*
     * If necessary, TkGenWMDestroyEvent() handles [close]ing the window, so
     * can always return NO from -windowShouldClose: for a Tk window.
     */

    return (winPtr ? NO : YES);
}


#ifdef TK_MAC_DEBUG_NOTIFICATIONS

- (void) windowDragStart: (NSNotification *) notification
{
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
}
................................................................................
    NSWindow *w = [notification object];
    TkWindow *winPtr = TkMacOSXGetTkWindow(w);

    if (winPtr) {
	//Tk_UnmapWindow((Tk_Window) winPtr);
    }
}


#endif /* TK_MAC_DEBUG_NOTIFICATIONS */

- (void) _setupWindowNotifications
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

................................................................................
#pragma mark -
 
/*
 *----------------------------------------------------------------------
 *
 * TkpAppIsDrawing --
 *
 *      A widget display procedure can call this to determine whether it is
 *      being run inside of the drawRect method. This is needed for some tests,
 *      especially of the Text widget, which record data in a global Tcl
 *      variable and assume that display procedures will be run in a
 *      predictable sequence as Tcl idle tasks.
 *
 * Results:
 *	True only while running the drawRect method of a TKContentView;
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE Bool
TkpAppIsDrawing(void) {
    return [NSApp isDrawing];
}

 
/*
 *----------------------------------------------------------------------
 *
 * GenerateUpdates --
 *
 *	Given a Macintosh update region and a Tk window this function geneates
................................................................................
	if (flags & TK_LOCATION_CHANGED) {
	    wmPtr->x = x;
	    wmPtr->y = y;
	}
	if ((flags & TK_SIZE_CHANGED) && !(wmPtr->flags & WM_SYNC_PENDING) &&
		((width != Tk_Width(tkwin)) || (height != Tk_Height(tkwin)))) {
	    if ((wmPtr->width == -1) && (width == winPtr->reqWidth)) {

		/*
		 * Don't set external width, since the user didn't change it
		 * from what the widgets asked for.
		 */

	    } else if (wmPtr->gridWin != NULL) {
		wmPtr->width = wmPtr->reqGridWidth
			+ (width - winPtr->reqWidth)/wmPtr->widthInc;
		if (wmPtr->width < 0) {
		    wmPtr->width = 0;
		}
	    } else {
		wmPtr->width = width;
	    }

	    if ((wmPtr->height == -1) && (height == winPtr->reqHeight)) {

		/*
		 * Don't set external height, since the user didn't change it
		 * from what the widgets asked for.
		 */

	    } else if (wmPtr->gridWin != NULL) {
		wmPtr->height = wmPtr->reqGridHeight
			+ (height - winPtr->reqHeight)/wmPtr->heightInc;
		if (wmPtr->height < 0) {
		    wmPtr->height = 0;
		}
	    } else {
................................................................................
		wmPtr->height = height;
	    }

	    wmPtr->configWidth = width;
	    wmPtr->configHeight = height;
	}
    }


    /*
     * Now set up the changes structure. Under X we wait for the
     * ConfigureNotify to set these values. On the Mac we know imediatly that
     * this is what we want - so we just set them. However, we need to make
     * sure the windows clipping region is marked invalid so the change is
     * visible to the subwindow.
................................................................................
#ifdef TK_MAC_DEBUG_DRAWING
    TkWindow *winPtr = TkMacOSXGetTkWindow([self window]);
    if (winPtr) fprintf(stderr, "drawRect: drawing %s\n",
			Tk_PathName(winPtr));
#endif

    /*
     * We do not allow recursive calls to drawRect, but we only log them on OSX
     * > 10.13, where they should never happen.
     */

    if ([NSApp isDrawing]) {
	if ([NSApp macMinorVersion] > 13) {
	    TKLog(@"WARNING: a recursive call to drawRect was aborted.");
	}
	return;
................................................................................
    if (winPtr) {
	unsigned int width = (unsigned int)newsize.width;
	unsigned int height=(unsigned int)newsize.height;
	ClientData oldArg;
    	Tk_RestrictProc *oldProc;

	/*
	 * This can be called from outside the Tk event loop.  Since it calls
	 * Tcl_DoOneEvent, we need to make sure we don't clobber the
	 * AutoreleasePool set up by the caller.
	 */

	[NSApp _lockAutoreleasePool];

	/*
	 * Disable Tk drawing until the window has been completely configured.
	 */
................................................................................
	TkMacOSXSetDrawingEnabled(winPtr, 0);

	 /*
	  * Generate and handle a ConfigureNotify event for the new size.
	  */

	TkGenWMConfigureEvent(tkwin, Tk_X(tkwin), Tk_Y(tkwin), width, height,
		TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY);
    	oldProc = Tk_RestrictEvents(ConfigureRestrictProc, NULL, &oldArg);
    	Tk_RestrictEvents(oldProc, oldArg, &oldArg);

	/*
	 * Now that Tk has configured all subwindows, create the clip regions.
	 */

................................................................................
	 * were created when the expose events were processed.
	 */
	while (Tcl_DoOneEvent(TCL_IDLE_EVENTS)) {}
    }
}

/*
 * This method is called when a user changes between light and dark mode. The
 * implementation here generates a Tk virtual event which can be bound to a
 * function that redraws the window in an appropriate style.
 */

- (void) viewDidChangeEffectiveAppearance
{
    XVirtualEvent event;
    int x, y;
    NSWindow *w = [self window];
................................................................................
    } else {
        event.name = Tk_GetUid("LightAqua");
    }
    Tk_QueueWindowEvent((XEvent *) &event, TCL_QUEUE_TAIL);
}

/*
 * This is no-op on 10.7 and up because Apple has removed this widget, but we
 * are leaving it here for backwards compatibility.
 */

- (void) tkToolbarButton: (id) sender
{
#ifdef TK_MAC_DEBUG_EVENTS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd);
#endif

Changes to macosx/tkMacOSXWm.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
...
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
...
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
....
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
....
3451
3452
3453
3454
3455
3456
3457

3458
3459
3460
3461
3462
3463
3464


3465
3466
3467
3468
3469
3470
3471
3472
....
3476
3477
3478
3479
3480
3481
3482

3483
3484

3485
3486

3487
3488
3489
3490
3491
3492
3493
....
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
....
3624
3625
3626
3627
3628
3629
3630


3631


3632
3633
3634
3635
3636
3637
3638
....
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
....
3782
3783
3784
3785
3786
3787
3788

3789
3790
3791
3792
3793
3794
3795
....
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
....
4413
4414
4415
4416
4417
4418
4419

4420
4421
4422
4423
4424
4425
4426
4427
4428
4429

4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
....
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
....
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
....
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
....
7234
7235
7236
7237
7238
7239
7240

7241
7242
7243
7244
7245
7246
7247
/*
 * tkMacOSXWm.c --
 *
 *	This module takes care of the interactions between a Tk-based
 *	application and the window manager. Among other things, it implements
 *	the "wm" command and passes geometry information to the window
 *	manager.
 *
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright 2001-2009, Apple Inc.
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright (c) 2010 Kevin Walzer/WordTech Communications LLC.
 * Copyright (c) 2017-2019 Marc Culler.
 *
................................................................................
	/*
	 * This avoids including the title bar for full screen windows
	 * but does include it for normal windows.
	 */

	if ([self styleMask] & NSFullScreenWindowMask) {
 	    frameRect = [NSWindow frameRectForContentRect:NSZeroRect
				  styleMask:[self styleMask]];
	} else {
	    frameRect = [self frameRectForContentRect:NSZeroRect];
	}

	WmInfo *wmPtr = winPtr->wmInfoPtr;

	wmPtr->xInParent = -frameRect.origin.x;
................................................................................
- (id) retain
{
    id result = [super retain];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1){
	fprintf(stderr, "Retained <%s>. Count is: %lu\n",
		title, [self retainCount]);
    }
    return result;
}

- (id) autorelease
{
    id result = [super autorelease];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1){
	fprintf(stderr, "Autoreleased <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    return result;
}

- (oneway void) release {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1){
	fprintf(stderr, "Releasing <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    [super release];
}

- (void) dealloc {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 0){
	fprintf(stderr, ">>>> Freeing <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    [super dealloc];
}

#endif
................................................................................
	/* Activate the highest window left on the screen. */
	NSArray *windows = [NSApp orderedWindows];
	for (id nswindow in windows) {
	    TkWindow *winPtr2 = TkMacOSXGetTkWindow(nswindow);

	    if (winPtr2 && nswindow != window) {
		WmInfo *wmPtr = winPtr2->wmInfoPtr;
		BOOL minimized = (wmPtr->hints.initial_state == IconicState ||
				  wmPtr->hints.initial_state == WithdrawnState);

		/*
		 * If no windows are left on the screen and the next window is
		 * iconified or withdrawn, we don't want to make it be the
		 * KeyWindow because that would cause it to be displayed on the
		 * screen.
		 */

		if ([nswindow canBecomeKeyWindow] && !minimized) {
		    [nswindow makeKeyAndOrderFront:NSApp];
		    break;
		}
	    }
	}

	/*
	 * Process all window events immediately to force the closed window to
	 * be deallocated.  But don't do this for the root window as that is
	 * unnecessary and can lead to segfaults.
	 */

	if (winPtr->parentPtr) {
	    while (Tk_DoOneEvent(TK_WINDOW_EVENTS|TK_DONT_WAIT)) {}
	}
	[NSApp _resetAutoreleasePool];
#if DEBUG_ZOMBIES > 0
	fprintf(stderr, "================= Pool dump ===================\n");
	[NSAutoreleasePool showPools];
................................................................................
	return TCL_OK;
    }

    if (*Tcl_GetString(objv[3]) == '\0') {
	wmPtr->hints.flags &= ~IconPositionHint;
    } else {
	if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK)
	    || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)){
	    return TCL_ERROR;
	}
	wmPtr->hints.icon_x = x;
	wmPtr->hints.icon_y = y;
	wmPtr->hints.flags |= IconPositionHint;
    }
    return TCL_OK;
................................................................................
	}

	if (Tcl_GetIndexFromObjStruct(interp, objv[3], optionStrings,
		sizeof(char *), "argument", 0, &index) != TCL_OK) {
	    return TCL_ERROR;
	}


	if (index == OPT_NORMAL) {
	    TkpWmSetState(winPtr, NormalState);

	    /*
	     * This varies from 'wm deiconify' because it does not force the
	     * window to be raised and receive focus
	     */


	} else if (index == OPT_ICONIC) {
	    if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"can't iconify \"%s\": override-redirect flag is set",
			winPtr->pathName));
		Tcl_SetErrorCode(interp, "TK", "WM", "STATE",
			"OVERRIDE_REDIRECT", NULL);
		return TCL_ERROR;
................................................................................
			"can't iconify \"%s\": it is a transient",
			winPtr->pathName));
		Tcl_SetErrorCode(interp, "TK", "WM", "STATE", "TRANSIENT",
			NULL);
		return TCL_ERROR;
	    }
	    TkpWmSetState(winPtr, IconicState);

	} else if (index == OPT_WITHDRAWN) {
	    TkpWmSetState(winPtr, WithdrawnState);

	} else { /* OPT_ZOOMED */
	    TkpWmSetState(winPtr, ZoomState);

	}
    } else if (wmPtr->iconFor != NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("icon", -1));
    } else {
	if (wmPtr->hints.initial_state == NormalState ||
		wmPtr->hints.initial_state == ZoomState) {
	    wmPtr->hints.initial_state = (TkMacOSXIsWindowZoomed(winPtr) ?
................................................................................
	    Tcl_SetObjResult(interp,
		Tcl_NewStringObj(Tk_PathName(wmPtr->master), -1));
	}
	return TCL_OK;
    }
    if (Tcl_GetString(objv[3])[0] == '\0') {
	RemoveTransient(winPtr);

    } else {
	if (TkGetWindowFromObj(interp, tkwin, objv[3], &master) != TCL_OK) {
	    return TCL_ERROR;
	}
	masterPtr = (TkWindow*) master;
	while (!Tk_TopWinHierarchy(masterPtr)) {

            /*
             * Ensure that the master window is actually a Tk toplevel.
             */

            masterPtr = masterPtr->parentPtr;
        }
	Tk_MakeWindowExist((Tk_Window)masterPtr);
................................................................................
		    "can't make \"%s\" a transient: it is an icon for %s",
		    Tcl_GetString(objv[2]), Tk_PathName(wmPtr->iconFor)));
	    Tcl_SetErrorCode(interp, "TK", "WM", "TRANSIENT", "ICON", NULL);
	    return TCL_ERROR;
	}

	wmPtr2 = masterPtr->wmInfoPtr;


	/* Under some circumstances, wmPtr2 is NULL here. */


	if (wmPtr2 != NULL && wmPtr2->iconFor != NULL) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "can't make \"%s\" a master: it is an icon for %s",
		    Tcl_GetString(objv[3]), Tk_PathName(wmPtr2->iconFor)));
	    Tcl_SetErrorCode(interp, "TK", "WM", "TRANSIENT", "ICON", NULL);
	    return TCL_ERROR;
	}
................................................................................
	}

	wmPtr->master = (Tk_Window) masterPtr;
    }
    ApplyMasterOverrideChanges(winPtr, NULL);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RemoveTransient --
 *
 *      Clears the transient's master record and removes the transient from the
 *      master's list.
................................................................................
    NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);
    [win orderOut:nil];
    [win setExcludedFromWindowsMenu:YES];

    /*
     * If this window has a transient, the transient must also be withdrawn.
     */

    for (Transient *transientPtr = wmPtr->transientPtr;
	    transientPtr != NULL; transientPtr = transientPtr->nextPtr) {
	TkWindow *winPtr2 = transientPtr->winPtr;
	TkWindow *masterPtr = (TkWindow *) TkGetTransientMaster(winPtr2);

    	if (masterPtr == winPtr &&
		winPtr2->wmInfoPtr->hints.initial_state != WithdrawnState) {
................................................................................
	    TkpWmSetState(winPtr2, WithdrawnState);
	    transientPtr->flags |= WITHDRAWN_BY_MASTER;
	}
    }

    return TCL_OK;
}

/*
 * Invoked by those wm subcommands that affect geometry.
 * Schedules a geometry update.
 */

static void
WmUpdateGeom(
    WmInfo *wmPtr,
    TkWindow *winPtr)
{
................................................................................
     */

    wmPtr->width = width;
    wmPtr->height = height;
    if (flags & WM_NEGATIVE_X) {
	int borderwidth = wmPtr->parentWidth - winPtr->changes.width;
	int newWidth = width == -1 ? winPtr->changes.width : width;

	x = (x == -1) ?
	    wmPtr->x + winPtr->changes.width - newWidth :
	    wmPtr->vRootWidth - x - newWidth - borderwidth;
    }
    if (x == -1) {
	x = wmPtr->x;
    }
    if (flags & WM_NEGATIVE_Y) {
	int borderheight = wmPtr->parentHeight - winPtr->changes.height;
	int newHeight = height == -1 ? winPtr->changes.height : height;

	y = (y == -1) ?
	    wmPtr->y + winPtr->changes.height - newHeight :
	    wmPtr->vRootHeight - y - newHeight - borderheight;
    }
    if (y == -1) {
	y = wmPtr->y;
    }
    if (wmPtr->flags & WM_FULLSCREEN) {
	wmPtr->configX = x;
	wmPtr->configY = y;
................................................................................
 *	This is a Macintosh specific implementation of this function. Given
 *	the root coordinates of a point, this procedure returns the token for
 *	the top-most window covering that point, if there exists such a window
 *	in this application.
 *
 * Results:
 *	The return result is either a token for the window corresponding to
 *	rootX and rootY, or else NULL to indicate that there is no such
 *	window.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayWindow --
 *
 *      Mark the contentView of this window as needing display so the
 *      window will be drawn by the window manager.  If this is called
 *      within the drawRect method, do nothing.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The window's contentView is marked as needing display.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE void
TkpDisplayWindow(Tk_Window tkwin) {
    if (![NSApp isDrawing]) {
    	TkWindow *winPtr = (TkWindow*)tkwin;
    	NSWindow *w = TkMacOSXDrawableWindow(winPtr->window);

    	[[w contentView] setNeedsDisplay: YES];
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXRegisterOffScreenWindow --
 *
 *	This function adds the passed in Off Screen Port to the hash table
 *	that maps Mac windows to root X windows.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	An entry is added to the windowTable hash table.
 *
................................................................................
		        NSResizableWindowMask;
	} else {
	    styleMask |= NSTitledWindowMask;
	}
    }
    if (macWindow) {
	structureRect = [NSWindow frameRectForContentRect:NSZeroRect
				  styleMask:styleMask];

	/*
	 * Synchronize the wmInfoPtr to match the new window configuration
	 * so windowBoundsChanged won't corrupt the window manager info.
	 */

	wmPtr->xInParent = -structureRect.origin.x;
................................................................................

static void
RemapWindows(
    TkWindow *winPtr,
    MacDrawable *parentWin)
{
    TkWindow *childPtr;

    /*
     * Remove the OS specific window. It will get rebuilt when the window gets
     * Mapped.
     */

    if (winPtr->window != None) {
	MacDrawable *macWin = (MacDrawable *) winPtr->window;





|
<







 







|







 







|













|











|











|







 







|
|
>






>






>





>







 







|







 







>
|






>
>
|







 







>
|

>
|

>







 







<






<







 







>
>
|
>
>







 







|







 







>







 







|

|
|







 







>

|
|







>

|
|







 







|
<







 







|
|
|













|











|
|







 







|







 







>







1
2
3
4
5
6

7
8
9
10
11
12
13
...
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
...
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
...
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
....
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
....
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
....
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
....
3608
3609
3610
3611
3612
3613
3614

3615
3616
3617
3618
3619
3620

3621
3622
3623
3624
3625
3626
3627
....
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
....
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
....
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
....
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
....
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
....
4566
4567
4568
4569
4570
4571
4572
4573

4574
4575
4576
4577
4578
4579
4580
....
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
....
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
....
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
/*
 * tkMacOSXWm.c --
 *
 *	This module takes care of the interactions between a Tk-based
 *	application and the window manager. Among other things, it implements
 *	the "wm" command and passes geometry information to the window manager.

 *
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright 2001-2009, Apple Inc.
 * Copyright (c) 2006-2009 Daniel A. Steffen <das@users.sourceforge.net>
 * Copyright (c) 2010 Kevin Walzer/WordTech Communications LLC.
 * Copyright (c) 2017-2019 Marc Culler.
 *
................................................................................
	/*
	 * This avoids including the title bar for full screen windows
	 * but does include it for normal windows.
	 */

	if ([self styleMask] & NSFullScreenWindowMask) {
 	    frameRect = [NSWindow frameRectForContentRect:NSZeroRect
		    styleMask:[self styleMask]];
	} else {
	    frameRect = [self frameRectForContentRect:NSZeroRect];
	}

	WmInfo *wmPtr = winPtr->wmInfoPtr;

	wmPtr->xInParent = -frameRect.origin.x;
................................................................................
- (id) retain
{
    id result = [super retain];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1) {
	fprintf(stderr, "Retained <%s>. Count is: %lu\n",
		title, [self retainCount]);
    }
    return result;
}

- (id) autorelease
{
    id result = [super autorelease];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1) {
	fprintf(stderr, "Autoreleased <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    return result;
}

- (oneway void) release {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1) {
	fprintf(stderr, "Releasing <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    [super release];
}

- (void) dealloc {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 0) {
	fprintf(stderr, ">>>> Freeing <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    [super dealloc];
}

#endif
................................................................................
	/* Activate the highest window left on the screen. */
	NSArray *windows = [NSApp orderedWindows];
	for (id nswindow in windows) {
	    TkWindow *winPtr2 = TkMacOSXGetTkWindow(nswindow);

	    if (winPtr2 && nswindow != window) {
		WmInfo *wmPtr = winPtr2->wmInfoPtr;
		BOOL minimized = (wmPtr->hints.initial_state == IconicState
			|| wmPtr->hints.initial_state == WithdrawnState);

		/*
		 * If no windows are left on the screen and the next window is
		 * iconified or withdrawn, we don't want to make it be the
		 * KeyWindow because that would cause it to be displayed on the
		 * screen.
		 */

		if ([nswindow canBecomeKeyWindow] && !minimized) {
		    [nswindow makeKeyAndOrderFront:NSApp];
		    break;
		}
	    }
	}

	/*
	 * Process all window events immediately to force the closed window to
	 * be deallocated.  But don't do this for the root window as that is
	 * unnecessary and can lead to segfaults.
	 */

	if (winPtr->parentPtr) {
	    while (Tk_DoOneEvent(TK_WINDOW_EVENTS|TK_DONT_WAIT)) {}
	}
	[NSApp _resetAutoreleasePool];
#if DEBUG_ZOMBIES > 0
	fprintf(stderr, "================= Pool dump ===================\n");
	[NSAutoreleasePool showPools];
................................................................................
	return TCL_OK;
    }

    if (*Tcl_GetString(objv[3]) == '\0') {
	wmPtr->hints.flags &= ~IconPositionHint;
    } else {
	if ((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK)
		|| (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)) {
	    return TCL_ERROR;
	}
	wmPtr->hints.icon_x = x;
	wmPtr->hints.icon_y = y;
	wmPtr->hints.flags |= IconPositionHint;
    }
    return TCL_OK;
................................................................................
	}

	if (Tcl_GetIndexFromObjStruct(interp, objv[3], optionStrings,
		sizeof(char *), "argument", 0, &index) != TCL_OK) {
	    return TCL_ERROR;
	}

	switch (index) {
	case OPT_NORMAL:
	    TkpWmSetState(winPtr, NormalState);

	    /*
	     * This varies from 'wm deiconify' because it does not force the
	     * window to be raised and receive focus
	     */

	    break;
	case OPT_ICONIC:
	    if (Tk_Attributes((Tk_Window) winPtr)->override_redirect) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"can't iconify \"%s\": override-redirect flag is set",
			winPtr->pathName));
		Tcl_SetErrorCode(interp, "TK", "WM", "STATE",
			"OVERRIDE_REDIRECT", NULL);
		return TCL_ERROR;
................................................................................
			"can't iconify \"%s\": it is a transient",
			winPtr->pathName));
		Tcl_SetErrorCode(interp, "TK", "WM", "STATE", "TRANSIENT",
			NULL);
		return TCL_ERROR;
	    }
	    TkpWmSetState(winPtr, IconicState);
	    break;
	case OPT_WITHDRAWN:
	    TkpWmSetState(winPtr, WithdrawnState);
	    break;
	default: /* OPT_ZOOMED */
	    TkpWmSetState(winPtr, ZoomState);
	    break;
	}
    } else if (wmPtr->iconFor != NULL) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj("icon", -1));
    } else {
	if (wmPtr->hints.initial_state == NormalState ||
		wmPtr->hints.initial_state == ZoomState) {
	    wmPtr->hints.initial_state = (TkMacOSXIsWindowZoomed(winPtr) ?
................................................................................
	    Tcl_SetObjResult(interp,
		Tcl_NewStringObj(Tk_PathName(wmPtr->master), -1));
	}
	return TCL_OK;
    }
    if (Tcl_GetString(objv[3])[0] == '\0') {
	RemoveTransient(winPtr);

    } else {
	if (TkGetWindowFromObj(interp, tkwin, objv[3], &master) != TCL_OK) {
	    return TCL_ERROR;
	}
	masterPtr = (TkWindow*) master;
	while (!Tk_TopWinHierarchy(masterPtr)) {

            /*
             * Ensure that the master window is actually a Tk toplevel.
             */

            masterPtr = masterPtr->parentPtr;
        }
	Tk_MakeWindowExist((Tk_Window)masterPtr);
................................................................................
		    "can't make \"%s\" a transient: it is an icon for %s",
		    Tcl_GetString(objv[2]), Tk_PathName(wmPtr->iconFor)));
	    Tcl_SetErrorCode(interp, "TK", "WM", "TRANSIENT", "ICON", NULL);
	    return TCL_ERROR;
	}

	wmPtr2 = masterPtr->wmInfoPtr;

	/*
	 * Under some circumstances, wmPtr2 is NULL here.
	 */

	if (wmPtr2 != NULL && wmPtr2->iconFor != NULL) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "can't make \"%s\" a master: it is an icon for %s",
		    Tcl_GetString(objv[3]), Tk_PathName(wmPtr2->iconFor)));
	    Tcl_SetErrorCode(interp, "TK", "WM", "TRANSIENT", "ICON", NULL);
	    return TCL_ERROR;
	}
................................................................................
	}

	wmPtr->master = (Tk_Window) masterPtr;
    }
    ApplyMasterOverrideChanges(winPtr, NULL);
    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * RemoveTransient --
 *
 *      Clears the transient's master record and removes the transient from the
 *      master's list.
................................................................................
    NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);
    [win orderOut:nil];
    [win setExcludedFromWindowsMenu:YES];

    /*
     * If this window has a transient, the transient must also be withdrawn.
     */

    for (Transient *transientPtr = wmPtr->transientPtr;
	    transientPtr != NULL; transientPtr = transientPtr->nextPtr) {
	TkWindow *winPtr2 = transientPtr->winPtr;
	TkWindow *masterPtr = (TkWindow *) TkGetTransientMaster(winPtr2);

    	if (masterPtr == winPtr &&
		winPtr2->wmInfoPtr->hints.initial_state != WithdrawnState) {
................................................................................
	    TkpWmSetState(winPtr2, WithdrawnState);
	    transientPtr->flags |= WITHDRAWN_BY_MASTER;
	}
    }

    return TCL_OK;
}
 
/*
 * Invoked by those wm subcommands that affect geometry.  Schedules a geometry
 * update.
 */

static void
WmUpdateGeom(
    WmInfo *wmPtr,
    TkWindow *winPtr)
{
................................................................................
     */

    wmPtr->width = width;
    wmPtr->height = height;
    if (flags & WM_NEGATIVE_X) {
	int borderwidth = wmPtr->parentWidth - winPtr->changes.width;
	int newWidth = width == -1 ? winPtr->changes.width : width;

	x = (x == -1) ?
		wmPtr->x + winPtr->changes.width - newWidth :
		wmPtr->vRootWidth - x - newWidth - borderwidth;
    }
    if (x == -1) {
	x = wmPtr->x;
    }
    if (flags & WM_NEGATIVE_Y) {
	int borderheight = wmPtr->parentHeight - winPtr->changes.height;
	int newHeight = height == -1 ? winPtr->changes.height : height;

	y = (y == -1) ?
		wmPtr->y + winPtr->changes.height - newHeight :
		wmPtr->vRootHeight - y - newHeight - borderheight;
    }
    if (y == -1) {
	y = wmPtr->y;
    }
    if (wmPtr->flags & WM_FULLSCREEN) {
	wmPtr->configX = x;
	wmPtr->configY = y;
................................................................................
 *	This is a Macintosh specific implementation of this function. Given
 *	the root coordinates of a point, this procedure returns the token for
 *	the top-most window covering that point, if there exists such a window
 *	in this application.
 *
 * Results:
 *	The return result is either a token for the window corresponding to
 *	rootX and rootY, or else NULL to indicate that there is no such window.

 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

................................................................................
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpDisplayWindow --
 *
 *      Mark the contentView of this window as needing display so the window
 *      will be drawn by the window manager.  If this is called within the
 *      drawRect method, do nothing.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The window's contentView is marked as needing display.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE void
TkpDisplayWindow(Tk_Window tkwin) {
    if (![NSApp isDrawing]) {
    	TkWindow *winPtr = (TkWindow *) tkwin;
    	NSWindow *w = TkMacOSXDrawableWindow(winPtr->window);

    	[[w contentView] setNeedsDisplay: YES];
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXRegisterOffScreenWindow --
 *
 *	This function adds the passed in Off Screen Port to the hash table that
 *	maps Mac windows to root X windows.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	An entry is added to the windowTable hash table.
 *
................................................................................
		        NSResizableWindowMask;
	} else {
	    styleMask |= NSTitledWindowMask;
	}
    }
    if (macWindow) {
	structureRect = [NSWindow frameRectForContentRect:NSZeroRect
		styleMask:styleMask];

	/*
	 * Synchronize the wmInfoPtr to match the new window configuration
	 * so windowBoundsChanged won't corrupt the window manager info.
	 */

	wmPtr->xInParent = -structureRect.origin.x;
................................................................................

static void
RemapWindows(
    TkWindow *winPtr,
    MacDrawable *parentWin)
{
    TkWindow *childPtr;

    /*
     * Remove the OS specific window. It will get rebuilt when the window gets
     * Mapped.
     */

    if (winPtr->window != None) {
	MacDrawable *macWin = (MacDrawable *) winPtr->window;

Changes to macosx/ttkMacOSXTheme.c.

56
57
58
59
60
61
62
63
64
65

66



67
68
69
70
71
72
73
..
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
...
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
...
215
216
217
218
219
220
221

222
223
224
225
226
227
228
...
251
252
253
254
255
256
257

258
259
260
261
262
263
264
...
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
...
364
365
366
367
368
369
370

371
372
373
374
375
376
377
...
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
...
448
449
450
451
452
453
454

455
456
457
458
459

460
461
462


463
464
465
466
467
468
469
...
479
480
481
482
483
484
485

486
487
488
489
490
491
492
...
504
505
506
507
508
509
510

511
512
513
514
515
516
517
...
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
...
636
637
638
639
640
641
642

643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
...
710
711
712
713
714
715
716

717
718
719
720
721
722
723
...
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
...
794
795
796
797
798
799
800
801
802


803
804
805
806

807
808
809
810
811
812
813
...
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
...
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
...
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
....
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
....
1078
1079
1080
1081
1082
1083
1084

1085
1086
1087
1088
1089
1090
1091
....
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
....
1125
1126
1127
1128
1129
1130
1131

1132

1133

1134

1135
1136
1137
1138
1139
1140
1141
....
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
....
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
....
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
....
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
....
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
....
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
....
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
....
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
....
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620

1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
....
1670
1671
1672
1673
1674
1675
1676

1677
1678
1679
1680
1681
1682

1683
1684
1685
1686
1687
1688
1689

1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
....
1721
1722
1723
1724
1725
1726
1727

1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750

1751
1752
1753
1754
1755
1756
1757
1758
1759
....
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860

1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
....
1883
1884
1885
1886
1887
1888
1889

1890
1891
1892
1893
1894
1895
1896
....
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
....
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
....
2050
2051
2052
2053
2054
2055
2056

2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
....
2101
2102
2103
2104
2105
2106
2107

2108
2109
2110
2111
2112
2113
2114
....
2125
2126
2127
2128
2129
2130
2131

2132
2133
2134
2135
2136
2137

2138

2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
....
2160
2161
2162
2163
2164
2165
2166

2167
2168
2169
2170
2171
2172
2173

2174
2175
2176
2177
2178
2179
2180
....
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
....
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
....
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
....
2377
2378
2379
2380
2381
2382
2383

2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395

2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
....
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
....
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
....
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
....
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
....
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
....
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
....
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743


2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754

2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782

2783
2784
2785
2786

2787
2788
2789
2790
2791
2792
2793
....
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809

2810

2811

2812

2813
2814
2815
2816
2817
2818
2819

2820

2821

2822

2823
2824
2825
2826
2827
2828
2829

/*----------------------------------------------------------------------
 * +++ Utilities.
 */

/*
 * BoxToRect --
 *    Convert a Ttk_Box in Tk coordinates relative to the given Drawable
 *    to a native Rect relative to the containing port.
 */

static inline CGRect BoxToRect(Drawable d, Ttk_Box b)



{
    MacDrawable *md = (MacDrawable*)d;
    CGRect rect;

    rect.origin.y	= b.y + md->yOff;
    rect.origin.x	= b.x + md->xOff;
    rect.size.height	= b.height;
................................................................................
};

/*
 * NormalizeButtonBounds --
 *
 * Apple's Human Interface Guidelines only allow three specific heights for
 * most buttons: Regular, small and mini. We always use the regular size.
 * However, Ttk may provide an arbitrary bounding rectangle.  We always draw
 * the button centered vertically on the rectangle, and having the same width
 * as the rectangle.  This function returns the actual bounding rectangle that
 * will be used in drawing the button.
 *
 * The BevelButton is allowed to have arbitrary size, and also has external
 * padding.  This is handled separately here.
 */

static CGRect NormalizeButtonBounds(
    SInt32 heightMetric,
    CGRect bounds)
{

    SInt32 height;
    if (heightMetric != NoThemeMetric) {

	ChkErr(GetThemeMetric, heightMetric, &height);
	bounds.origin.y += (bounds.size.height - height)/2;
	bounds.size.height = height;
    }
    return bounds;
}

................................................................................
/*----------------------------------------------------------------------
 * GetBackgroundColor --
 *
 *	Fills the array rgba with the color coordinates for a background color.
 *	Start with the background color of a window's geometry master, or the
 *	standard ttk window background if not. If the contrast parameter is
 *	nonzero modify this color to be darker, for the aqua appearance, or
 *	lighter for the DarkAqua appearance.  This is primarily used by the
 *	Fill and Background elements.
 */

static void GetBackgroundColor(
    CGContextRef context,
    Tk_Window tkwin,
    int contrast,
    CGFloat *rgba)
{
    TkWindow *winPtr = (TkWindow *) tkwin;
    TkWindow *masterPtr = (TkWindow *) TkGetGeomMaster(tkwin);

    while (masterPtr != NULL) {
	if (masterPtr->privatePtr->flags & TTK_HAS_CONTRASTING_BG) {
	    break;
	}
	masterPtr = (TkWindow *)TkGetGeomMaster(masterPtr);
    }
    if (masterPtr) {
	for (int i = 0; i < 4; i++) {
	    rgba[i] = masterPtr->privatePtr->fillRGBA[i];
	}
    } else {
	if ([NSApp macMinorVersion] > 13) {
	    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	    NSColor *windowColor = [[NSColor windowBackgroundColor]
				       colorUsingColorSpace: deviceRGB];

	    [windowColor getComponents: rgba];
	} else {
	    for (int i = 0; i < 4; i++) {
		rgba[i] = windowBackground[i];
	    }
	}
    }
................................................................................
    Tk_Window tkwin)
{
    CGPathRef path;
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *borderColor, *bgColor;
    static CGFloat border[4] = {1.0, 1.0, 1.0, 0.25};
    CGFloat fill[4];

    GetBackgroundColor(context, tkwin, 1, fill);
    bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill
				     count: 4];
    CGContextSetFillColorSpace(context, deviceRGB.CGColorSpace);
    CGContextSetFillColorWithColor(context, bgColor.CGColor);
    path = CGPathCreateWithRoundedRect(bounds, 4, 4, NULL);
    CGContextClipToRect(context, bounds);
................................................................................
static void SolidFillRoundedRectangle(
    CGContextRef context,
    CGRect bounds,
    CGFloat radius,
    NSColor *color)
{
    CGPathRef path;

    CGContextSetFillColorWithColor(context, color.CGColor);
    path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL);
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextFillPath(context);
    CFRelease(path);
}
................................................................................
    CGContextRef context,
    CGRect bounds,
    CGFloat inset,
    CGFloat size,
    CGFloat *rgba)
{
    CGFloat x, y;

    CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]);
    CGContextSetLineWidth(context, 1.5);
    x = bounds.origin.x + inset;
    y = bounds.origin.y + trunc(bounds.size.height/2);
    CGContextBeginPath(context);
    CGPoint arrow[3] = {
	{x, y-size/4}, {x+size/2, y+size/4}, {x+size, y-size/4}
    };


    CGContextAddLines(context, arrow, 3);
    CGContextStrokePath(context);
}

static void DrawUpArrow(
    CGContextRef context,
    CGRect bounds,
    CGFloat inset,
    CGFloat size,
    CGFloat *rgba)
{
    CGFloat x, y;

    CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]);
    CGContextSetLineWidth(context, 1.5);
    x = bounds.origin.x + inset;
    y = bounds.origin.y + trunc(bounds.size.height/2);
    CGContextBeginPath(context);
    CGPoint arrow[3] = {
	{x, y+size/4}, {x+size/2, y-size/4}, {x+size, y+size/4}
    };


    CGContextAddLines(context, arrow, 3);
    CGContextStrokePath(context);
}

/*----------------------------------------------------------------------
 * DrawListHeader --
 *
................................................................................
    CGContextStrokePath(context);
    CGContextAddLines(context, bottom, 2);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);

    if (state & TTK_TREEVIEW_STATE_SORTARROW) {
	CGRect arrowBounds = bounds;

	arrowBounds.origin.x = bounds.origin.x + bounds.size.width - 16;
	arrowBounds.size.width = 16;
	if (state & TTK_STATE_ALTERNATE) {
	    DrawUpArrow(context, arrowBounds, 3, 8, blackRGBA);
	} else if (state & TTK_STATE_SELECTED) {
	    DrawDownArrow(context, arrowBounds, 3, 8, blackRGBA);
	}
................................................................................
static CGFloat darkBackgroundGradient[8] = {0.0, 0.0, 0.0, 0.1,
					    0.0, 0.0, 0.0, 0.25};
static CGFloat darkInactiveGradient[8] = {89.0/255, 90.0/255, 93.0/255, 1.0,
				       119.0/255, 120.0/255, 122.0/255, 1.0};
static CGFloat darkSelectedGradient[8] = {23.0/255, 111.0/255, 232.0/255, 1.0,
					  20.0/255, 94.0/255,  206.0/255, 1.0};

 
/*----------------------------------------------------------------------
 * GradientFillRoundedRectangle --
 *
 *	Fill a rounded rectangle with a specified gradient.
 */

static void GradientFillRoundedRectangle(
    CGContextRef context,
    CGRect bounds,
    CGFloat radius,
    CGFloat* colors,
    int numColors)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    CGPathRef path;
    CGPoint end = {
	bounds.origin.x,
	bounds.origin.y + bounds.size.height
    };
    CGGradientRef gradient = CGGradientCreateWithColorComponents(
	    deviceRGB.CGColorSpace, colors, NULL, numColors);

    path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL);
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0);
    CFRelease(path);
    CFRelease(gradient);
................................................................................
    CGContextRef context,
    CGRect bounds,
    CGFloat inset,
    CGFloat size,
    CGFloat *rgba)
{
    CGFloat x, y;

    CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]);
    CGContextSetLineWidth(context, 1.5);
    x = bounds.origin.x + inset;
    y = bounds.origin.y + trunc(bounds.size.height/2);
    CGContextBeginPath(context);

    CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}};
    CGContextAddLines(context, bottomArrow, 3);
    CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}};


    CGContextAddLines(context, topArrow, 3);
    CGContextStrokePath(context);
}

/*----------------------------------------------------------------------
 * FillButtonBackground --
 *
................................................................................
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents(
	    deviceRGB.CGColorSpace, darkBackgroundGradient, NULL, 2);
    CGPoint backgroundEnd = {
	bounds.origin.x,
	bounds.origin.y + bounds.size.height
    };

    CGContextBeginPath(context);
    path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, backgroundGradient,
	    bounds.origin, backgroundEnd, 0);
    CFRelease(path);
................................................................................
    CGContextRef context,
    CGRect bounds)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3};
    CGGradientRef topGradient = CGGradientCreateWithColorComponents(
	    deviceRGB.CGColorSpace, darkTopGradient, NULL, 2);

    CGContextSaveGState(context);
    CGContextBeginPath(context);
    CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4,
	    4, PI, 3*PI/2, 0);
    CGContextAddArc(context, bounds.origin.x + bounds.size.width - 4,
	    bounds.origin.y + 4, 4, 3*PI/2, 0, 0);
    CGContextReplacePathWithStrokedPath(context);
................................................................................

    /*
     * If this is a popup, draw the arrow button.
     */

    if (kind == kThemePopupButton | kind == kThemeComboBox) {
	CGRect arrowBounds = bounds;

	arrowBounds.size.width = 16;
	arrowBounds.origin.x += bounds.size.width - 16;

	/*
	 * If the toplevel is front, paint the button blue.
	 */

	if (!(state & TTK_STATE_BACKGROUND) &&
	    !(state & TTK_STATE_DISABLED)) {
	    GradientFillRoundedRectangle(context, arrowBounds, 4,
				   darkSelectedGradient, 2);
	}
	if (kind == kThemePopupButton) {
	    DrawUpDownArrows(context, arrowBounds, 3, 7, whiteRGBA);
	} else {
	    DrawDownArrow(context, arrowBounds, 4, 8, whiteRGBA);
	}
    }
................................................................................

    HighlightButtonBorder(context, bounds);
}

/*----------------------------------------------------------------------
 * DrawDarkIncDecButton --
 *
 *	This is a standalone drawing procedure which draws an IncDecButton
 *	(as used in a Spinbox) in the Dark Mode style.
 */

static void DrawDarkIncDecButton(
    CGRect bounds,
    ThemeDrawState drawState,
    Ttk_State state,
    CGContextRef context)
................................................................................

    /*
     * If pressed, paint the appropriate half blue.
     */
    
    if (state & TTK_STATE_PRESSED) {
	CGRect clip = bounds;

	clip.size.height /= 2;
	CGContextSaveGState(context);
	if (drawState == kThemeStatePressedDown) {
	    clip.origin.y += clip.size.height;
	}
	CGContextClipToRect(context, clip);
	GradientFillRoundedRectangle(context, bounds, 5,
				   darkSelectedGradient, 2);
	CGContextRestoreGState(context);
    }
    DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA);
    HighlightButtonBorder(context, bounds);
}

/*----------------------------------------------------------------------
................................................................................
    Ttk_State state,
    CGContextRef context)
{
    CGRect checkbounds = {{0, bounds.size.height/2 - 8},{16, 16}};
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *stroke;
    CGFloat x, y;

    bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y);
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 4);
    bounds = CGRectInset(bounds, 1, 1);
................................................................................
	    stroke = [NSColor disabledControlTextColor];
	} else {
	    stroke = [NSColor controlTextColor];
	}
	CGContextSetStrokeColorWithColor(context, stroke.CGColor);
    }
    if (state & TTK_STATE_SELECTED) {


	CGContextSetLineWidth(context, 1.5);
	CGContextBeginPath(context);
	CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}};
	CGContextAddLines(context, check, 3);
	CGContextStrokePath(context);
    } else if (state & TTK_STATE_ALTERNATE) {


	CGContextSetLineWidth(context, 2.0);
	CGContextBeginPath(context);
	CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}};
	CGContextAddLines(context, bar, 2);
	CGContextStrokePath(context);
    }
}

/*----------------------------------------------------------------------
 * DrawDarkRadioButton --
 *
 *    This is a standalone drawing procedure which draws RadioButtons
 *    in the Dark Mode style.
 */

static void DrawDarkRadioButton(
    CGRect bounds,
    Ttk_State state,
    CGContextRef context)
{
    CGRect checkbounds = {{0, bounds.size.height/2 - 9},{18, 18}};
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *fill;
    CGFloat x, y;

    bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y);
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 9);
    bounds = CGRectInset(bounds, 1, 1);
................................................................................
	    fill = [NSColor disabledControlTextColor];
	} else {
	    fill = [NSColor controlTextColor];
	}
	CGContextSetFillColorWithColor(context, fill.CGColor);
    }
    if (state & TTK_STATE_SELECTED) {
	CGContextBeginPath(context);
	CGRect dot = {{x + 6, y + 6}, {6, 6}};


	CGContextAddEllipseInRect(context, dot);
	CGContextFillPath(context);
    } else if (state & TTK_STATE_ALTERNATE) {
	CGRect bar = {{x + 5, y + 8}, {8, 2}};

	CGContextFillRect(context, bar);
    }
}

/*----------------------------------------------------------------------
 * DrawDarkTab --
 *
................................................................................
	    CGContextSetShouldAntialias(context, false);
	    stroke = [NSColor colorWithColorSpace: deviceRGB
				       components: darkTabSeparator
					    count: 4];
	    CGContextSetStrokeColorWithColor(context, stroke.CGColor);
	    CGContextBeginPath(context);
	    CGContextMoveToPoint(context, originalBounds.origin.x,
	        originalBounds.origin.y + 1);
	    CGContextAddLineToPoint(context, originalBounds.origin.x,
	        originalBounds.origin.y + originalBounds.size.height - 1);
	    CGContextStrokePath(context);
	    CGContextRestoreGState(context);
	}
    } else {
	/*
	 * This is the selected tab; paint it blue.  If it is first, cover up
	 * the separator line drawn by the second one.  (The selected tab is
................................................................................
	 */

	if ((state & TTK_STATE_FIRST_TAB) && !(state & TTK_STATE_LAST_TAB)) {
	    bounds.size.width += 1;
	}
	if (!(state & TTK_STATE_BACKGROUND)) {
	    GradientFillRoundedRectangle(context, bounds, 4,
					 darkSelectedGradient, 2);
	} else {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
				     components: darkInactiveSelectedTab
					  count: 4];
	    SolidFillRoundedRectangle(context, bounds, 4, faceColor);
	}
	HighlightButtonBorder(context, bounds);
    }
}

/*----------------------------------------------------------------------
 * DrawDarkSeparator --
 *
 *    This is a standalone drawing procedure which draws a separator widget
 *    in Dark Mode.
 */

static void DrawDarkSeparator(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin)
{
    static CGFloat fill[4] = {1.0, 1.0, 1.0, 0.3};
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *fillColor = [NSColor colorWithColorSpace: deviceRGB
					   components: fill
						count:4];

    CGContextSetFillColorWithColor(context, fillColor.CGColor);
    CGContextFillRect(context, bounds);
}

/*----------------------------------------------------------------------
 * DrawDarkFrame --
 *
 *    This is a standalone drawing procedure which draws various
 *    types of borders in Dark Mode.
 */

static void DrawDarkFrame(
    CGRect bounds,
    CGContextRef context,
    HIThemeFrameKind kind)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *stroke;
    CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
    CGFloat x = bounds.origin.x, y = bounds.origin.y;
    CGFloat w = bounds.size.width, h = bounds.size.height;
    CGPoint topPart[4] = {
	{x, y + h - 1}, {x, y}, {x + w, y}, {x + w, y + h - 1}
    };
    CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; 
    CGPoint accent[2] = {{x, y + 1}, {x + w, y + 1}};


    switch(kind) {
    case kHIThemeFrameTextFieldSquare:
	CGContextSaveGState(context);
	CGContextSetShouldAntialias(context, false);
	CGContextBeginPath(context);
	stroke = [NSColor colorWithColorSpace: deviceRGB
				       components: darkFrameTop
					    count: 4];
................................................................................
	break;
    }
}

/*----------------------------------------------------------------------
 * DrawListHeader --
 *
 *    This is a standalone drawing procedure which draws column
 *    headers for a Treeview in the Dark Mode.
 */

static void DrawDarkListHeader(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin,
    int state)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *stroke;
    CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
    CGFloat x = bounds.origin.x, y = bounds.origin.y;
    CGFloat w = bounds.size.width, h = bounds.size.height;
    CGPoint top[2] = {{x, y}, {x + w, y}};
    CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; 
    CGPoint separator[2] = {{x + w, y + 3}, {x + w, y + h - 3}};


    CGContextSaveGState(context);
    CGContextSetShouldAntialias(context, false);
    stroke = [NSColor colorWithColorSpace: deviceRGB
			       components: darkFrameBottom
				    count: 4];
    CGContextSetStrokeColorWithColor(context, stroke.CGColor);
    CGContextBeginPath(context);
................................................................................
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED >101300 */

/*----------------------------------------------------------------------
 * +++ Button element: Used for elements drawn with DrawThemeButton.
 */

/*
 * When Ttk draws the various types of buttons, a pointer to one of these
 * is passed as the clientData.
 */

typedef struct {
    ThemeButtonKind kind;
    ThemeMetric heightMetric;
} ThemeButtonParams;

................................................................................
{
    /*
     * See ButtonElementDraw for the explanation of why we always draw
     * PushButtons in the active state.
     */

    SInt32 HIThemeState;

    switch (params->kind) {
    case kThemePushButton:
	HIThemeState = kThemeStateActive;
	break;
    default:
	HIThemeState = Ttk_StateTableLookup(ThemeStateTable, state);
	break;
................................................................................
	.kind = params ? params->kind : 0,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state),
    };
    return info;
}


static void ButtonElementMinSize(

    void *clientData, void *elementRecord, Tk_Window tkwin,

    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)

{
    ThemeButtonParams *params = clientData;

    if (params->heightMetric != NoThemeMetric) {
	ChkErr(GetThemeMetric, params->heightMetric, minHeight);

	/*
	 * The theme height does not include the 1-pixel border around
	 * the button, although it does include the 1-pixel shadow at
	 * the bottom.
	 */

	*minHeight += 2;

	/*
	 * The minwidth must be 0 to force the generic ttk code to compute the
	 * correct text layout.  For example, a non-zero value will cause the
................................................................................
	 * the style.
	 */

	*minWidth = 0;
    }
}


static void ButtonElementSize(

    void *clientData, void *elementRecord, Tk_Window tkwin,

    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)

{
    ThemeButtonParams *params = clientData;
    const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin);
    static const CGRect scratchBounds = {{0, 0}, {100, 100}};
    CGRect contentBounds, backgroundBounds;
    int verticalPad;

................................................................................
     * enough to contain the image of the button in any state, which might
     * include highlight borders, shadows, etc.  The content rectangle is not
     * centered vertically within the background rectangle, presumably because
     * shadows only appear on the bottom.  Nonetheless, when HITools is asked
     * to draw a button with a certain bounding rectangle it draws the button
     * centered within the rectangle.
     *
     * To compute the effective padding around a button we request the
     * content and bounding rectangles for a 100x100 button and use the
     * padding between those.  However, we symmetrize the padding on the
     * top and bottom, because that is how the button will be drawn.
     */

    ChkErr(HIThemeGetButtonContentBounds,
	    &scratchBounds, &info, &contentBounds);
    ChkErr(HIThemeGetButtonBackgroundBounds,
	    &scratchBounds, &info, &backgroundBounds);
    paddingPtr->left = contentBounds.origin.x - backgroundBounds.origin.x;
    paddingPtr->right =
	    CGRectGetMaxX(backgroundBounds) - CGRectGetMaxX(contentBounds);
    verticalPad = backgroundBounds.size.height - contentBounds.size.height;
    paddingPtr->top = paddingPtr->bottom = verticalPad / 2;
}


static void ButtonElementDraw(

    void *clientData, void *elementRecord, Tk_Window tkwin,



    Drawable d, Ttk_Box b, Ttk_State state)
{
    ThemeButtonParams *params = clientData;
    CGRect bounds = BoxToRect(d, b);
    HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, state, tkwin);
    bounds = NormalizeButtonBounds(params->heightMetric, bounds);
    
    BEGIN_DRAWING(d)
    if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	switch (info.kind) {
	case kThemePushButton:
	case kThemePopupButton:
	    DrawDarkButton(bounds, info.kind, state, dc.context);
	    break;
................................................................................
	    info.value == kThemeButtonMixed) {
	    info.value = kThemeButtonOff;
	    info.state = kThemeStateInactive;
	}
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation,
		NULL);
    }
    END_DRAWING
}

static Ttk_ElementSpec ButtonElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    ButtonElementSize,
................................................................................
 * between the content in the tab view and the tab-view edges.
 *
 * <URL: http://developer.apple.com/documentation/userexperience/Conceptual/
 *       AppleHIGuidelines/XHIGControls/XHIGControls.html#//apple_ref/doc/uid/
 *       TP30000359-TPXREF116>
 */


static void TabElementSize(

    void *clientData, void *elementRecord, Tk_Window tkwin,

    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)

{
    GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *)minHeight);
    *paddingPtr = Ttk_MakePadding(0, 0, 0, 2);

}


static void TabElementDraw(

    void *clientData, void *elementRecord, Tk_Window tkwin,



    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);
    HIThemeTabDrawInfo info = {
	.version = 1,
	.style = Ttk_StateTableLookup(TabStyleTable, state),
	.direction = kThemeTabNorth,
	.size = kHIThemeTabSizeNormal,
	.adornment = Ttk_StateTableLookup(TabAdornmentTable, state),
	.kind = kHIThemeTabKindNormal,
	.position = Ttk_StateTableLookup(TabPositionTable, state),
    };

    BEGIN_DRAWING(d)
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkTab(bounds, state, dc.context);
    } else {
	ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL);
    }
#else
    ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL);
#endif
    END_DRAWING
}

static Ttk_ElementSpec TabElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TabElementSize,
................................................................................
}

static void PaneElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);

    bounds.origin.y -= kThemeMetricTabFrameOverlap;
    bounds.size.height += kThemeMetricTabFrameOverlap;
    BEGIN_DRAWING(d)
    if ([NSApp macMinorVersion] > 9) {
#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080
    DrawGroupBox(bounds, dc.context, tkwin);
#endif
    } else { 
    HIThemeTabPaneDrawInfo info = {
	.version = 1,
	.state = Ttk_StateTableLookup(ThemeStateTable, state),
	.direction = kThemeTabNorth,
	.size = kHIThemeTabSizeNormal,
	.kind = kHIThemeTabKindNormal,
	.adornment = kHIThemeTabPaneAdornmentNormal,
    };
    bounds.origin.y -= kThemeMetricTabFrameOverlap;
    bounds.size.height += kThemeMetricTabFrameOverlap;
    ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation);
    }
    END_DRAWING
}

static Ttk_ElementSpec PaneElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    PaneElementSize,
................................................................................
 * a maximum of 2 pixels thick."
 *
 * "Maximum of 2 pixels thick" is apparently a lie; looks more like 4 to me
 * with shading.
 */

static void GroupElementSize(

    void *clientData, void *elementRecord, Tk_Window tkwin,

    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)

{
    *paddingPtr = Ttk_UniformPadding(4);
}

static void GroupElementDraw(

    void *clientData, void *elementRecord, Tk_Window tkwin,



    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);

    BEGIN_DRAWING(d)
    if ([NSApp macMinorVersion] > 9) {
#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080
    DrawGroupBox(bounds, dc.context, tkwin);
#endif
    } else { 
    const HIThemeGroupBoxDrawInfo info = {
	.version = 0,
	.state = Ttk_StateTableLookup(ThemeStateTable, state),
	.kind = kHIThemeGroupBoxKindPrimaryOpaque,
    };
    ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation);
    }
    END_DRAWING
}

static Ttk_ElementSpec GroupElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    GroupElementSize,
................................................................................
    Tcl_Obj	*fieldbackgroundObj;
} EntryElement;

#define ENTRY_DEFAULT_BACKGROUND "systemTextBackgroundColor"

static Ttk_ElementOptionSpec EntryElementOptions[] = {
    { "-background", TK_OPTION_BORDER,
      Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND },
    { "-fieldbackground", TK_OPTION_BORDER,
      Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND },
    {0}
};

static void EntryElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
................................................................................
    CGRect bounds = BoxToRect(d, inner);
    NSColor *background;
    Tk_3DBorder backgroundPtr = NULL;
    static const char *defaultBG = ENTRY_DEFAULT_BACKGROUND;

    if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	BEGIN_DRAWING(d)
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	CGFloat fill[4];

	GetBackgroundColor(dc.context, tkwin, 1, fill);
	background = [NSColor colorWithColorSpace: deviceRGB
				       components: fill
					    count: 4];
	CGContextSetFillColorWithColor(dc.context, background.CGColor);
	CGContextFillRect(dc.context, bounds);
	DrawDarkFrame(bounds, dc.context, kHIThemeFrameTextFieldSquare);
	END_DRAWING
#endif
    } else {
	const HIThemeFrameDrawInfo info = {
	    .version = 0,
	    .kind = kHIThemeFrameTextFieldSquare,
	    .state = Ttk_StateTableLookup(ThemeStateTable, state),
	    .isFocused = state & TTK_STATE_FOCUS,
................................................................................
	    backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->backgroundObj);
	}
	if (backgroundPtr != NULL) {
	    XFillRectangle(Tk_Display(tkwin), d,
		    Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC),
		    inner.x, inner.y, inner.width, inner.height);
	}
	BEGIN_DRAWING(d)
	if (backgroundPtr == NULL) {
	    background = [NSColor textBackgroundColor];
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	    CGContextSetFillColorWithColor(dc.context, background.CGColor);
#else
	    CGContextSetRGBFillColor(dc.context, 1.0, 1.0, 1.0, 1.0);
#endif
	    CGContextFillRect(dc.context, bounds);
	}
	ChkErr(HIThemeDrawFrame, &bounds, &info, dc.context, HIOrientation);
	END_DRAWING
    }
    /*if (state & TTK_STATE_FOCUS) {
	ChkErr(DrawThemeFocusRect, &bounds, 1);
    }*/
}

static Ttk_ElementSpec EntryElementSpec = {
................................................................................
	.version = 0,
	.state = Ttk_StateTableLookup(ThemeStateTable, state),
	.kind = kThemeComboBox,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state),
    };

    BEGIN_DRAWING(d)
    bounds.origin.y += 1;
    if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	bounds.size.height += 1;
	DrawDarkButton(bounds, info.kind, state, dc.context);
#endif
    } else
	{
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	if ((state & TTK_STATE_BACKGROUND) &&
	    !(state & TTK_STATE_DISABLED)) {
	    NSColor *background = [NSColor textBackgroundColor];
	    CGRect innerBounds = CGRectInset(bounds, 1, 2);

	    SolidFillRoundedRectangle(dc.context, innerBounds, 4, background);
	}
#endif
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}

static Ttk_ElementSpec ComboboxElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    ComboboxElementSize,
................................................................................

static void SpinButtonUpElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins));
    int infoState;

    bounds.size.height *= 2;
    if (state & TTK_STATE_PRESSED) {
	infoState = kThemeStatePressedUp;
    } else {
	infoState = Ttk_StateTableLookup(ThemeStateTable, state);
    }

    const HIThemeButtonDrawInfo info = {
	.version = 0,
	.state = infoState,
	.kind = kThemeIncDecButton,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = kThemeAdornmentNone,
    };

    BEGIN_DRAWING(d)
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkIncDecButton(bounds, infoState, state, dc.context);
    } else
#endif
    {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}

static Ttk_ElementSpec SpinButtonUpElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SpinButtonUpElementSize,
................................................................................

static void SpinButtonDownElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins));
    int infoState = 0;

    bounds.origin.y -= bounds.size.height;
    bounds.size.height *= 2;
    if (state & TTK_STATE_PRESSED) {
	infoState = kThemeStatePressedDown;
    } else {
	return;
    }
    const HIThemeButtonDrawInfo info = {
	.version = 0,
	.state = infoState,
	.kind = kThemeIncDecButton,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = kThemeAdornmentNone,
    };

    BEGIN_DRAWING(d)
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkIncDecButton(bounds, infoState, state, dc.context);
    } else
#endif
    {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);

    }
    END_DRAWING
}

static Ttk_ElementSpec SpinButtonDownElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SpinButtonDownElementSize,
................................................................................
		kThemeThumbPressed : 0;
	if (state & TTK_STATE_ALTERNATE) {
	    info.trackInfo.slider.thumbDir = kThemeThumbDownward;
	} else {
	    info.trackInfo.slider.thumbDir = kThemeThumbPlain;
	}
    }
    BEGIN_DRAWING(d)
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	CGRect bounds = BoxToRect(d, b);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB
	 					components: darkTrack
	 					     count: 4];

	if (orientation == TTK_ORIENT_HORIZONTAL) {
	    bounds = CGRectInset(bounds, 1, bounds.size.height/2 - 2);
	} else {
	    bounds = CGRectInset(bounds, bounds.size.width/2 - 3, 2);
	}
	SolidFillRoundedRectangle(dc.context, bounds, 2, trackColor);
    }
#endif
    ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation);
    END_DRAWING
}

static Ttk_ElementSpec TrackElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(TrackElement),
    TrackElementOptions,
    TrackElementSize,
................................................................................
 * Has geometry only. The Scale widget adjusts the position of this element,
 * and uses it for hit detection. In the Aqua theme, the slider is actually
 * drawn as part of the trough element.
 *
 * Also buggy: The geometry here is a Wild-Assed-Guess; I can't figure out how
 * to get the Appearance Manager to tell me the slider size.
 */

static void SliderElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
    *minWidth = *minHeight = 24;
}

................................................................................
	.attributes = kThemeTrackShowThumb |
		(orientation == TTK_ORIENT_HORIZONTAL ?
		kThemeTrackHorizontal : 0),
	.enableState = Ttk_StateTableLookup(ThemeTrackEnableTable, state),
	.trackInfo.progress.phase = phase,
    };

    BEGIN_DRAWING(d)
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	CGRect bounds = BoxToRect(d, b);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB
	 					components: darkTrack
	 					     count: 4];
................................................................................
	} else {
	    bounds = CGRectInset(bounds, bounds.size.width/2 - 3, 1);
	}
	SolidFillRoundedRectangle(dc.context, bounds, 3, trackColor);
    }
#endif
    ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation);
    END_DRAWING
}

static Ttk_ElementSpec PbarElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(PbarElement),
    PbarElementOptions,
    PbarElementSize,
................................................................................
{
    ScrollbarElement *scrollbar = elementRecord;
    int orientation = TTK_ORIENT_HORIZONTAL;
    CGRect bounds = BoxToRect(d, b);
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *troughColor;
    CGFloat *rgba = TkMacOSXInDarkMode(tkwin) ? darkTrough : lightTrough;

    Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation);
    if (orientation == TTK_ORIENT_HORIZONTAL) {
	bounds = CGRectInset(bounds, 0, 1);
    } else {
	bounds = CGRectInset(bounds, 1, 0);
    }
    troughColor = [NSColor colorWithColorSpace: deviceRGB
				    components: rgba
					 count: 4];
    BEGIN_DRAWING(d)
    if ([NSApp macMinorVersion] > 8) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	CGContextSetFillColorWithColor(dc.context, troughColor.CGColor);
#endif
    } else {
	ChkErr(HIThemeSetFill, kThemeBrushDocumentWindowBackground, NULL,
	       dc.context, HIOrientation);
    }
    CGContextFillRect(dc.context, bounds);
    END_DRAWING
}

static Ttk_ElementSpec TroughElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(ScrollbarElement),
    ScrollbarElementOptions,
    TroughElementSize,
................................................................................

static void ThumbElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    ScrollbarElement *scrollbar = elementRecord;
    int orientation = TTK_ORIENT_HORIZONTAL;

    Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation);

    /*
     * In order to make ttk scrollbars work correctly it is necessary to be
     * able to display the thumb element at the size and location which the ttk
     * scrollbar widget requests.  The algorithm that HIToolbox uses to
     * determine the thumb geometry from the input values of min, max, value
................................................................................

    if ([NSApp macMinorVersion] > 8) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	CGRect thumbBounds = BoxToRect(d, b);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	NSColor *thumbColor;
	CGFloat *rgba;

	if ((orientation == TTK_ORIENT_HORIZONTAL &&
	     thumbBounds.size.width >= Tk_Width(tkwin) - 8) ||
	    (orientation == TTK_ORIENT_VERTICAL &&
	     thumbBounds.size.height >= Tk_Height(tkwin) - 8)) {
	    return;
	}

	int isDark = TkMacOSXInDarkMode(tkwin);

	if ((state & TTK_STATE_PRESSED) ||
	    (state & TTK_STATE_HOVER) ) {
	    rgba = isDark ? darkActiveThumb : lightActiveThumb;
	} else {
	    rgba = isDark ? darkInactiveThumb : lightInactiveThumb;
	}
	thumbColor = [NSColor colorWithColorSpace: deviceRGB
				       components: rgba
					    count: 4];
	BEGIN_DRAWING(d)
	    SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor);
	END_DRAWING
#endif
    } else {
	double thumbSize, trackSize, visibleSize, viewSize;
	MacDrawable *macWin = (MacDrawable *) Tk_WindowId(tkwin);
	CGRect troughBounds = {{macWin->xOff, macWin->yOff},
			       {Tk_Width(tkwin), Tk_Height(tkwin)}};

................................................................................
	 * floats in the drawing routine.  All of values provided in the info
	 * struct, namely min, max, value, and viewSize are only defined up to
	 * an arbitrary scale factor.  To avoid roundoff error we scale so that
	 * the viewSize is a large float which is smaller than the largest int.
	 */
    
	viewSize = RangeToFactor(100.0);

	HIThemeTrackDrawInfo info = {
	    .version = 0,
	    .bounds = troughBounds,
	    .min = 0,
	    .attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost,
	    .enableState = kThemeTrackActive
	};

	info.trackInfo.scrollbar.viewsize = viewSize*.8; 
	if (orientation == TTK_ORIENT_HORIZONTAL) {
	    trackSize = troughBounds.size.width;
	    thumbSize = b.width;
	    visibleSize = (thumbSize / trackSize) * viewSize;
	    info.max = viewSize - visibleSize;
	    info.value = info.max * (b.x / (trackSize - thumbSize)); 
................................................................................
	    thumbSize = b.height;
	    trackSize = troughBounds.size.height;
	    visibleSize = (thumbSize / trackSize) * viewSize;
	    info.max = viewSize - visibleSize;
	    info.value = info.max * (b.y / (trackSize - thumbSize)); 
	}
	if ((state & TTK_STATE_PRESSED) ||
	    (state & TTK_STATE_HOVER) ) {
	    info.trackInfo.scrollbar.pressState = kThemeThumbPressed;
	} else {
	    info.trackInfo.scrollbar.pressState = 0;
	}
	if (orientation == TTK_ORIENT_HORIZONTAL) {
	    info.attributes |= kThemeTrackHorizontal;
	} else {
	    info.attributes &= ~kThemeTrackHorizontal;
	}
	BEGIN_DRAWING(d)
	    HIThemeDrawTrack (&info, 0, dc.context, kHIThemeOrientationNormal);
	END_DRAWING
	    }
}

static Ttk_ElementSpec ThumbElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(ScrollbarElement),
    ScrollbarElementOptions,
    ThumbElementSize,
................................................................................
    CGRect bounds = BoxToRect(d, b);
    const HIThemeSeparatorDrawInfo info = {
	.version = 0,
	/* Separator only supports kThemeStateActive, kThemeStateInactive */
	.state = Ttk_StateTableLookup(ThemeStateTable, state & TTK_STATE_BACKGROUND),
    };

    BEGIN_DRAWING(d)
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkSeparator(bounds, dc.context, tkwin);
    } else {
	ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation);
    }
#else
    ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation);
#endif
    END_DRAWING
}

static Ttk_ElementSpec SeparatorElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SeparatorElementSize,
................................................................................
	.state = Ttk_StateTableLookup(ThemeStateTable,
		state & TTK_STATE_BACKGROUND),
	.kind = kHIThemeGrowBoxKindNormal,
	.direction = sizegripGrowDirection,
	.size = kHIThemeGrowBoxSizeNormal,
    };

    BEGIN_DRAWING(d)
    ChkErr(HIThemeDrawGrowBox, &bounds.origin, &info, dc.context, HIOrientation);
    END_DRAWING
}

static Ttk_ElementSpec SizegripElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SizegripElementSize,
................................................................................
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *bgColor;
    CGFloat fill[4];

    BEGIN_DRAWING(d)
    GetBackgroundColor(dc.context, tkwin, 0, fill);
    bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill
				     count: 4];
    CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace);
    CGContextSetFillColorWithColor(dc.context, bgColor.CGColor);
    CGContextFillRect(dc.context, bounds);
    END_DRAWING
#else
    ThemeBrush brush = (state & TTK_STATE_BACKGROUND)
	    ? kThemeBrushModelessDialogBackgroundInactive
	    : kThemeBrushModelessDialogBackgroundActive;

    BEGIN_DRAWING(d)
    ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation);
    //QDSetPatternOrigin(PatternOrigin(tkwin, d));
    CGContextFillRect(dc.context, bounds);
    END_DRAWING
#endif
}

static void BackgroundElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, unsigned int state)
{
    FillElementDraw(clientData, elementRecord, tkwin, d, Ttk_WinBox(tkwin),
    		    state);
}

static Ttk_ElementSpec FillElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TtkNullElementSize,
................................................................................
    BackgroundElementDraw
};

/*----------------------------------------------------------------------
 * +++ ToolbarBackground element -- toolbar style for frames.
 *
 *    This is very similar to the normal background element, but uses a
 *    different ThemeBrush in order to get the lighter pinstripe effect
 *    used in toolbars. We use SetThemeBackground() rather than
 *    ApplyThemeBackground() in order to get the right style.
 *
 * <URL: http://developer.apple.com/documentation/Carbon/Reference/
 *    Appearance_Manager/appearance_manager/constant_7.html#/
 *    /apple_ref/doc/uid/TP30000243/C005321>
 *
 */

................................................................................
static void ToolbarBackgroundElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    ThemeBrush brush = kThemeBrushToolbarBackground;
    CGRect bounds = BoxToRect(d, Ttk_WinBox(tkwin));

    BEGIN_DRAWING(d)
    ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation);
    //QDSetPatternOrigin(PatternOrigin(tkwin, d));
    CGContextFillRect(dc.context, bounds);
    END_DRAWING
}

static Ttk_ElementSpec ToolbarBackgroundElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TtkNullElementSize,
................................................................................
	    TTK_STATE_SELECTED|TTK_TREEVIEW_STATE_SORTARROW},
    { kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_ALTERNATE},
    { kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_SELECTED},
    { kThemeAdornmentFocus, TTK_STATE_FOCUS},
    { kThemeAdornmentNone, 0}
};

static void TreeAreaElementSize (
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{ 
    /*
     * Padding is needed to get the heading text to align correctly, since the
     * widget expects the heading to be the same height as a row.
     */
................................................................................
	.version = 0,
	.state = Ttk_StateTableLookup(ThemeStateTable, state),
	.kind = params->kind,
	.value = Ttk_StateTableLookup(TreeHeaderValueTable, state),
	.adornment = Ttk_StateTableLookup(TreeHeaderAdornmentTable, state),
    };

    BEGIN_DRAWING(d)
    if ([NSApp macMinorVersion] > 8) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080

	/*
	 * Compensate for the padding added in TreeHeaderElementSize, so
	 * the larger heading will be drawn at the top of the widget.
	 */
	
	bounds.origin.y -= 4;
	if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	    DrawDarkListHeader(bounds, dc.context, tkwin, state);
#endif
................................................................................
	} else {
	    DrawListHeader(bounds, dc.context, tkwin, state);
	}
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */
    } else {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}

static Ttk_ElementSpec TreeHeaderElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TreeHeaderElementSize,
................................................................................
	    .version = 0,
	    .state = triangleState,
	    .kind = kThemeDisclosureTriangle,
	    .value = Ttk_StateTableLookup(DisclosureValueTable, state),
	    .adornment = kThemeAdornmentDrawIndicatorOnly,
	};

	BEGIN_DRAWING(d)
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
	END_DRAWING
    }
}

static Ttk_ElementSpec DisclosureElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
................................................................................

TTK_LAYOUT("Horizontal.TScrollbar",
    TTK_GROUP("Horizontal.Scrollbar.trough", TTK_FILL_X,
	TTK_NODE("Horizontal.Scrollbar.thumb", TTK_PACK_LEFT|TTK_EXPAND|TTK_FILL_BOTH)
	TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT)
	TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_RIGHT)))

TTK_END_LAYOUT_TABLE

/*----------------------------------------------------------------------
 * +++ Initialization.
 */



static int AquaTheme_Init(Tcl_Interp *interp)
{
    Ttk_Theme themePtr = Ttk_CreateTheme(interp, "aqua", NULL);

    if (!themePtr) {
	return TCL_ERROR;
    }

    /*
     * Elements:
     */

    Ttk_RegisterElementSpec(themePtr, "background", &BackgroundElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "fill", &FillElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "field", &FieldElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Toolbar.background",
	&ToolbarBackgroundElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "Button.button",
	&ButtonElementSpec, &PushButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Checkbutton.button",
	&ButtonElementSpec, &CheckBoxParams);
    Ttk_RegisterElementSpec(themePtr, "Radiobutton.button",
	&ButtonElementSpec, &RadioButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Toolbutton.border",
     	&ButtonElementSpec, &BevelButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Menubutton.button",
	&ButtonElementSpec, &PopupButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Spinbox.uparrow",
	&SpinButtonUpElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Spinbox.downarrow",
    	&SpinButtonDownElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Combobox.button",
	&ComboboxElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Treeitem.indicator",
	&DisclosureElementSpec, &DisclosureParams);
    Ttk_RegisterElementSpec(themePtr, "Treeheading.cell",
	&TreeHeaderElementSpec, &ListHeaderParams);

    Ttk_RegisterElementSpec(themePtr, "Treeview.treearea", &TreeAreaElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "Notebook.tab", &TabElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Notebook.client", &PaneElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "Labelframe.border", &GroupElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "Entry.field", &EntryElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Spinbox.field", &EntryElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "separator", &SeparatorElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "hseparator", &SeparatorElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "vseparator", &SeparatorElementSpec, 0);

................................................................................
     * pbar element.  But in our case the appearance manager draws both parts
     * of the progress bar, so we just have a single element called ".track".
     */

    Ttk_RegisterElementSpec(themePtr,"Progressbar.track", &PbarElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Scale.trough", &TrackElementSpec,
			    &ScaleData);
    Ttk_RegisterElementSpec(themePtr,"Scale.slider", &SliderElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough", &TroughElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb", &ThumbElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough", &TroughElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb", &ThumbElementSpec, 0);


    /*
     * If we are not in Snow Leopard or Lion the arrows won't actually be
     * displayed.
     */

    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow", &ArrowElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow", &ArrowElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow", &ArrowElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow", &ArrowElementSpec, 0);


    /*
     * Layouts:
     */

    Ttk_RegisterLayouts(themePtr, LayoutTable);








|
|

>
|
>
>
>







 







|
|
|
|









>
|
<
>







 







|
|










>




|










>







 







>







 







>







 







>




|



>
>












>




|



>
>







 







>







 







<










|










>







 







>





>

<

>
>







 







>







 







>







 







>








|

|







 







|
|







 







>







|







 







>







 







>
>


<



>
>


<








|
|











>







 







<

>
>




>







 







|

|







 







|









|



|
|












>



|



|
|









<







>
>
|







 







|
|










<






>







 







|
|







 







>







 







>
|
>
|
>
|
>







|
|
<







 







>
|
>
|
>
|
>







 







|
|
|
|













>
|
>
|
>
>
>
|






|







 







|







 







>
|
>
|
>
|
>

|

|
|
<
>
|
>
|
>
>
>
|











>
|









|







 







>


|


|


|
|
|
|
|
|
|
|
|
|
|

|







 







>
|
>
|
>





>
|
>
>
>
|



|


|


|
|
|
|
|
|

|







 







|

|







 







|


>







|







 







|










|







 







|






|
<


|


>





|







 







>






>







>
|








|







 







>





|









|






|
>

|







 







|







>









|







 







>







 







|







 







|







 







>









|









|







 







>







 







>
|
|
|
|


>

>

|







|
|
|







 







>







>







 







|









|
|
|
|







 







|









|







 







|

|







 







>
|






|




>
|



|








|







 







|
|
|







 







|



|







 







|







 







|


<

|
|







 







|







 







|

|







 







|





>
>
|










>




|


|

|

|

|

|

|

|

|

|

|

|
>



|
>







 







|


|
>
|
>
|
>
|
>






|
>
|
>
|
>
|
>







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
...
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
...
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
...
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
...
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
...
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
...
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
...
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
...
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
...
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
...
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
...
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
...
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
...
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
...
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
...
821
822
823
824
825
826
827

828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
...
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
...
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
....
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
....
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
....
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
....
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
....
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
....
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
....
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
....
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
....
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
....
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
....
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
....
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
....
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
....
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676

1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
....
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
....
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
....
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
....
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
....
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
....
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
....
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
....
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
....
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
....
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
....
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
....
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
....
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
....
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
....
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
....
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
....
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
....
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648

2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
....
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
....
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
....
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
....
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919

/*----------------------------------------------------------------------
 * +++ Utilities.
 */

/*
 * BoxToRect --
 *    Convert a Ttk_Box in Tk coordinates relative to the given Drawable to a
 *    native Rect relative to the containing port.
 */

static inline CGRect
BoxToRect(
    Drawable d,
    Ttk_Box b)
{
    MacDrawable *md = (MacDrawable*)d;
    CGRect rect;

    rect.origin.y	= b.y + md->yOff;
    rect.origin.x	= b.x + md->xOff;
    rect.size.height	= b.height;
................................................................................
};

/*
 * NormalizeButtonBounds --
 *
 * Apple's Human Interface Guidelines only allow three specific heights for
 * most buttons: Regular, small and mini. We always use the regular size.
 * However, Ttk may provide an arbitrary bounding rectangle. We always draw the
 * button centered vertically on the rectangle, and having the same width as
 * the rectangle. This function returns the actual bounding rectangle that will
 * be used in drawing the button.
 *
 * The BevelButton is allowed to have arbitrary size, and also has external
 * padding.  This is handled separately here.
 */

static CGRect NormalizeButtonBounds(
    SInt32 heightMetric,
    CGRect bounds)
{
    if (heightMetric != (SInt32) NoThemeMetric) {
	SInt32 height;


	ChkErr(GetThemeMetric, heightMetric, &height);
	bounds.origin.y += (bounds.size.height - height)/2;
	bounds.size.height = height;
    }
    return bounds;
}

................................................................................
/*----------------------------------------------------------------------
 * GetBackgroundColor --
 *
 *	Fills the array rgba with the color coordinates for a background color.
 *	Start with the background color of a window's geometry master, or the
 *	standard ttk window background if not. If the contrast parameter is
 *	nonzero modify this color to be darker, for the aqua appearance, or
 *	lighter for the DarkAqua appearance. This is primarily used by the Fill
 *	and Background elements.
 */

static void GetBackgroundColor(
    CGContextRef context,
    Tk_Window tkwin,
    int contrast,
    CGFloat *rgba)
{
    TkWindow *winPtr = (TkWindow *) tkwin;
    TkWindow *masterPtr = (TkWindow *) TkGetGeomMaster(tkwin);

    while (masterPtr != NULL) {
	if (masterPtr->privatePtr->flags & TTK_HAS_CONTRASTING_BG) {
	    break;
	}
	masterPtr = (TkWindow *) TkGetGeomMaster(masterPtr);
    }
    if (masterPtr) {
	for (int i = 0; i < 4; i++) {
	    rgba[i] = masterPtr->privatePtr->fillRGBA[i];
	}
    } else {
	if ([NSApp macMinorVersion] > 13) {
	    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	    NSColor *windowColor = [[NSColor windowBackgroundColor]
				       colorUsingColorSpace: deviceRGB];

	    [windowColor getComponents: rgba];
	} else {
	    for (int i = 0; i < 4; i++) {
		rgba[i] = windowBackground[i];
	    }
	}
    }
................................................................................
    Tk_Window tkwin)
{
    CGPathRef path;
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *borderColor, *bgColor;
    static CGFloat border[4] = {1.0, 1.0, 1.0, 0.25};
    CGFloat fill[4];

    GetBackgroundColor(context, tkwin, 1, fill);
    bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill
				     count: 4];
    CGContextSetFillColorSpace(context, deviceRGB.CGColorSpace);
    CGContextSetFillColorWithColor(context, bgColor.CGColor);
    path = CGPathCreateWithRoundedRect(bounds, 4, 4, NULL);
    CGContextClipToRect(context, bounds);
................................................................................
static void SolidFillRoundedRectangle(
    CGContextRef context,
    CGRect bounds,
    CGFloat radius,
    NSColor *color)
{
    CGPathRef path;

    CGContextSetFillColorWithColor(context, color.CGColor);
    path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL);
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextFillPath(context);
    CFRelease(path);
}
................................................................................
    CGContextRef context,
    CGRect bounds,
    CGFloat inset,
    CGFloat size,
    CGFloat *rgba)
{
    CGFloat x, y;

    CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]);
    CGContextSetLineWidth(context, 1.5);
    x = bounds.origin.x + inset;
    y = bounds.origin.y + trunc(bounds.size.height/2);

    CGPoint arrow[3] = {
	{x, y-size/4}, {x+size/2, y+size/4}, {x+size, y-size/4}
    };

    CGContextBeginPath(context);
    CGContextAddLines(context, arrow, 3);
    CGContextStrokePath(context);
}

static void DrawUpArrow(
    CGContextRef context,
    CGRect bounds,
    CGFloat inset,
    CGFloat size,
    CGFloat *rgba)
{
    CGFloat x, y;

    CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]);
    CGContextSetLineWidth(context, 1.5);
    x = bounds.origin.x + inset;
    y = bounds.origin.y + trunc(bounds.size.height/2);

    CGPoint arrow[3] = {
	{x, y+size/4}, {x+size/2, y-size/4}, {x+size, y+size/4}
    };

    CGContextBeginPath(context);
    CGContextAddLines(context, arrow, 3);
    CGContextStrokePath(context);
}

/*----------------------------------------------------------------------
 * DrawListHeader --
 *
................................................................................
    CGContextStrokePath(context);
    CGContextAddLines(context, bottom, 2);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);

    if (state & TTK_TREEVIEW_STATE_SORTARROW) {
	CGRect arrowBounds = bounds;

	arrowBounds.origin.x = bounds.origin.x + bounds.size.width - 16;
	arrowBounds.size.width = 16;
	if (state & TTK_STATE_ALTERNATE) {
	    DrawUpArrow(context, arrowBounds, 3, 8, blackRGBA);
	} else if (state & TTK_STATE_SELECTED) {
	    DrawDownArrow(context, arrowBounds, 3, 8, blackRGBA);
	}
................................................................................
static CGFloat darkBackgroundGradient[8] = {0.0, 0.0, 0.0, 0.1,
					    0.0, 0.0, 0.0, 0.25};
static CGFloat darkInactiveGradient[8] = {89.0/255, 90.0/255, 93.0/255, 1.0,
				       119.0/255, 120.0/255, 122.0/255, 1.0};
static CGFloat darkSelectedGradient[8] = {23.0/255, 111.0/255, 232.0/255, 1.0,
					  20.0/255, 94.0/255,  206.0/255, 1.0};


/*----------------------------------------------------------------------
 * GradientFillRoundedRectangle --
 *
 *	Fill a rounded rectangle with a specified gradient.
 */

static void GradientFillRoundedRectangle(
    CGContextRef context,
    CGRect bounds,
    CGFloat radius,
    CGFloat *colors,
    int numColors)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    CGPathRef path;
    CGPoint end = {
	bounds.origin.x,
	bounds.origin.y + bounds.size.height
    };
    CGGradientRef gradient = CGGradientCreateWithColorComponents(
	    deviceRGB.CGColorSpace, colors, NULL, numColors);

    path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL);
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, bounds.origin, end, 0);
    CFRelease(path);
    CFRelease(gradient);
................................................................................
    CGContextRef context,
    CGRect bounds,
    CGFloat inset,
    CGFloat size,
    CGFloat *rgba)
{
    CGFloat x, y;

    CGContextSetRGBStrokeColor(context, rgba[0], rgba[1], rgba[2], rgba[3]);
    CGContextSetLineWidth(context, 1.5);
    x = bounds.origin.x + inset;
    y = bounds.origin.y + trunc(bounds.size.height/2);
    CGContextBeginPath(context);

    CGPoint bottomArrow[3] = {{x, y+2}, {x+size/2, y+2+size/2}, {x+size, y+2}};

    CGPoint topArrow[3] = {{x, y-2}, {x+size/2, y-2-size/2}, {x+size, y-2}};

    CGContextAddLines(context, bottomArrow, 3);
    CGContextAddLines(context, topArrow, 3);
    CGContextStrokePath(context);
}

/*----------------------------------------------------------------------
 * FillButtonBackground --
 *
................................................................................
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents(
	    deviceRGB.CGColorSpace, darkBackgroundGradient, NULL, 2);
    CGPoint backgroundEnd = {
	bounds.origin.x,
	bounds.origin.y + bounds.size.height
    };

    CGContextBeginPath(context);
    path = CGPathCreateWithRoundedRect(bounds, radius, radius, NULL);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, backgroundGradient,
	    bounds.origin, backgroundEnd, 0);
    CFRelease(path);
................................................................................
    CGContextRef context,
    CGRect bounds)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    CGPoint topEnd = {bounds.origin.x, bounds.origin.y + 3};
    CGGradientRef topGradient = CGGradientCreateWithColorComponents(
	    deviceRGB.CGColorSpace, darkTopGradient, NULL, 2);

    CGContextSaveGState(context);
    CGContextBeginPath(context);
    CGContextAddArc(context, bounds.origin.x + 4, bounds.origin.y + 4,
	    4, PI, 3*PI/2, 0);
    CGContextAddArc(context, bounds.origin.x + bounds.size.width - 4,
	    bounds.origin.y + 4, 4, 3*PI/2, 0, 0);
    CGContextReplacePathWithStrokedPath(context);
................................................................................

    /*
     * If this is a popup, draw the arrow button.
     */

    if (kind == kThemePopupButton | kind == kThemeComboBox) {
	CGRect arrowBounds = bounds;

	arrowBounds.size.width = 16;
	arrowBounds.origin.x += bounds.size.width - 16;

	/*
	 * If the toplevel is front, paint the button blue.
	 */

	if (!(state & TTK_STATE_BACKGROUND) &&
		!(state & TTK_STATE_DISABLED)) {
	    GradientFillRoundedRectangle(context, arrowBounds, 4,
		    darkSelectedGradient, 2);
	}
	if (kind == kThemePopupButton) {
	    DrawUpDownArrows(context, arrowBounds, 3, 7, whiteRGBA);
	} else {
	    DrawDownArrow(context, arrowBounds, 4, 8, whiteRGBA);
	}
    }
................................................................................

    HighlightButtonBorder(context, bounds);
}

/*----------------------------------------------------------------------
 * DrawDarkIncDecButton --
 *
 *	This is a standalone drawing procedure which draws an IncDecButton (as
 *	used in a Spinbox) in the Dark Mode style.
 */

static void DrawDarkIncDecButton(
    CGRect bounds,
    ThemeDrawState drawState,
    Ttk_State state,
    CGContextRef context)
................................................................................

    /*
     * If pressed, paint the appropriate half blue.
     */
    
    if (state & TTK_STATE_PRESSED) {
	CGRect clip = bounds;

	clip.size.height /= 2;
	CGContextSaveGState(context);
	if (drawState == kThemeStatePressedDown) {
	    clip.origin.y += clip.size.height;
	}
	CGContextClipToRect(context, clip);
	GradientFillRoundedRectangle(context, bounds, 5,
		darkSelectedGradient, 2);
	CGContextRestoreGState(context);
    }
    DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA);
    HighlightButtonBorder(context, bounds);
}

/*----------------------------------------------------------------------
................................................................................
    Ttk_State state,
    CGContextRef context)
{
    CGRect checkbounds = {{0, bounds.size.height/2 - 8},{16, 16}};
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *stroke;
    CGFloat x, y;

    bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y);
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 4);
    bounds = CGRectInset(bounds, 1, 1);
................................................................................
	    stroke = [NSColor disabledControlTextColor];
	} else {
	    stroke = [NSColor controlTextColor];
	}
	CGContextSetStrokeColorWithColor(context, stroke.CGColor);
    }
    if (state & TTK_STATE_SELECTED) {
	CGPoint check[3] = {{x+4, y+8}, {x+7, y+11}, {x+11, y+4}};

	CGContextSetLineWidth(context, 1.5);
	CGContextBeginPath(context);

	CGContextAddLines(context, check, 3);
	CGContextStrokePath(context);
    } else if (state & TTK_STATE_ALTERNATE) {
	CGPoint bar[2] = {{x+4, y+8}, {x+12, y+8}};

	CGContextSetLineWidth(context, 2.0);
	CGContextBeginPath(context);

	CGContextAddLines(context, bar, 2);
	CGContextStrokePath(context);
    }
}

/*----------------------------------------------------------------------
 * DrawDarkRadioButton --
 *
 *    This is a standalone drawing procedure which draws RadioButtons in the
 *    Dark Mode style.
 */

static void DrawDarkRadioButton(
    CGRect bounds,
    Ttk_State state,
    CGContextRef context)
{
    CGRect checkbounds = {{0, bounds.size.height/2 - 9},{18, 18}};
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *fill;
    CGFloat x, y;

    bounds = CGRectOffset(checkbounds, bounds.origin.x, bounds.origin.y);
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 9);
    bounds = CGRectInset(bounds, 1, 1);
................................................................................
	    fill = [NSColor disabledControlTextColor];
	} else {
	    fill = [NSColor controlTextColor];
	}
	CGContextSetFillColorWithColor(context, fill.CGColor);
    }
    if (state & TTK_STATE_SELECTED) {

	CGRect dot = {{x + 6, y + 6}, {6, 6}};

	CGContextBeginPath(context);
	CGContextAddEllipseInRect(context, dot);
	CGContextFillPath(context);
    } else if (state & TTK_STATE_ALTERNATE) {
	CGRect bar = {{x + 5, y + 8}, {8, 2}};

	CGContextFillRect(context, bar);
    }
}

/*----------------------------------------------------------------------
 * DrawDarkTab --
 *
................................................................................
	    CGContextSetShouldAntialias(context, false);
	    stroke = [NSColor colorWithColorSpace: deviceRGB
				       components: darkTabSeparator
					    count: 4];
	    CGContextSetStrokeColorWithColor(context, stroke.CGColor);
	    CGContextBeginPath(context);
	    CGContextMoveToPoint(context, originalBounds.origin.x,
		    originalBounds.origin.y + 1);
	    CGContextAddLineToPoint(context, originalBounds.origin.x,
		    originalBounds.origin.y + originalBounds.size.height - 1);
	    CGContextStrokePath(context);
	    CGContextRestoreGState(context);
	}
    } else {
	/*
	 * This is the selected tab; paint it blue.  If it is first, cover up
	 * the separator line drawn by the second one.  (The selected tab is
................................................................................
	 */

	if ((state & TTK_STATE_FIRST_TAB) && !(state & TTK_STATE_LAST_TAB)) {
	    bounds.size.width += 1;
	}
	if (!(state & TTK_STATE_BACKGROUND)) {
	    GradientFillRoundedRectangle(context, bounds, 4,
		    darkSelectedGradient, 2);
	} else {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
				     components: darkInactiveSelectedTab
					  count: 4];
	    SolidFillRoundedRectangle(context, bounds, 4, faceColor);
	}
	HighlightButtonBorder(context, bounds);
    }
}
 
/*----------------------------------------------------------------------
 * DrawDarkSeparator --
 *
 *    This is a standalone drawing procedure which draws a separator widget in
 *    Dark Mode.
 */

static void DrawDarkSeparator(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin)
{
    static CGFloat fill[4] = {1.0, 1.0, 1.0, 0.3};
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *fillColor = [NSColor colorWithColorSpace: deviceRGB
					   components: fill
						count:4];

    CGContextSetFillColorWithColor(context, fillColor.CGColor);
    CGContextFillRect(context, bounds);
}
 
/*----------------------------------------------------------------------
 * DrawDarkFrame --
 *
 *    This is a standalone drawing procedure which draws various types of
 *    borders in Dark Mode.
 */

static void DrawDarkFrame(
    CGRect bounds,
    CGContextRef context,
    HIThemeFrameKind kind)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *stroke;

    CGFloat x = bounds.origin.x, y = bounds.origin.y;
    CGFloat w = bounds.size.width, h = bounds.size.height;
    CGPoint topPart[4] = {
	{x, y + h - 1}, {x, y}, {x + w, y}, {x + w, y + h - 1}
    };
    CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; 
    CGPoint accent[2] = {{x, y + 1}, {x + w, y + 1}};

    CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
    switch (kind) {
    case kHIThemeFrameTextFieldSquare:
	CGContextSaveGState(context);
	CGContextSetShouldAntialias(context, false);
	CGContextBeginPath(context);
	stroke = [NSColor colorWithColorSpace: deviceRGB
				       components: darkFrameTop
					    count: 4];
................................................................................
	break;
    }
}

/*----------------------------------------------------------------------
 * DrawListHeader --
 *
 *	This is a standalone drawing procedure which draws column headers for a
 *	Treeview in the Dark Mode.
 */

static void DrawDarkListHeader(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin,
    int state)
{
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *stroke;

    CGFloat x = bounds.origin.x, y = bounds.origin.y;
    CGFloat w = bounds.size.width, h = bounds.size.height;
    CGPoint top[2] = {{x, y}, {x + w, y}};
    CGPoint bottom[2] = {{x, y + h}, {x + w, y + h}}; 
    CGPoint separator[2] = {{x + w, y + 3}, {x + w, y + h - 3}};

    CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
    CGContextSaveGState(context);
    CGContextSetShouldAntialias(context, false);
    stroke = [NSColor colorWithColorSpace: deviceRGB
			       components: darkFrameBottom
				    count: 4];
    CGContextSetStrokeColorWithColor(context, stroke.CGColor);
    CGContextBeginPath(context);
................................................................................
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED >101300 */

/*----------------------------------------------------------------------
 * +++ Button element: Used for elements drawn with DrawThemeButton.
 */

/*
 * When Ttk draws the various types of buttons, a pointer to one of these is
 * passed as the clientData.
 */

typedef struct {
    ThemeButtonKind kind;
    ThemeMetric heightMetric;
} ThemeButtonParams;

................................................................................
{
    /*
     * See ButtonElementDraw for the explanation of why we always draw
     * PushButtons in the active state.
     */

    SInt32 HIThemeState;

    switch (params->kind) {
    case kThemePushButton:
	HIThemeState = kThemeStateActive;
	break;
    default:
	HIThemeState = Ttk_StateTableLookup(ThemeStateTable, state);
	break;
................................................................................
	.kind = params ? params->kind : 0,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state),
    };
    return info;
}

static void
ButtonElementMinSize(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    int *minWidth, int *minHeight,
    Ttk_Padding *paddingPtr)
{
    ThemeButtonParams *params = clientData;

    if (params->heightMetric != NoThemeMetric) {
	ChkErr(GetThemeMetric, params->heightMetric, minHeight);

	/*
	 * The theme height does not include the 1-pixel border around the
	 * button, although it does include the 1-pixel shadow at the bottom.

	 */

	*minHeight += 2;

	/*
	 * The minwidth must be 0 to force the generic ttk code to compute the
	 * correct text layout.  For example, a non-zero value will cause the
................................................................................
	 * the style.
	 */

	*minWidth = 0;
    }
}

static void
ButtonElementSize(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    int *minWidth, int *minHeight,
    Ttk_Padding *paddingPtr)
{
    ThemeButtonParams *params = clientData;
    const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin);
    static const CGRect scratchBounds = {{0, 0}, {100, 100}};
    CGRect contentBounds, backgroundBounds;
    int verticalPad;

................................................................................
     * enough to contain the image of the button in any state, which might
     * include highlight borders, shadows, etc.  The content rectangle is not
     * centered vertically within the background rectangle, presumably because
     * shadows only appear on the bottom.  Nonetheless, when HITools is asked
     * to draw a button with a certain bounding rectangle it draws the button
     * centered within the rectangle.
     *
     * To compute the effective padding around a button we request the content
     * and bounding rectangles for a 100x100 button and use the padding between
     * those. However, we symmetrize the padding on the top and bottom, because
     * that is how the button will be drawn.
     */

    ChkErr(HIThemeGetButtonContentBounds,
	    &scratchBounds, &info, &contentBounds);
    ChkErr(HIThemeGetButtonBackgroundBounds,
	    &scratchBounds, &info, &backgroundBounds);
    paddingPtr->left = contentBounds.origin.x - backgroundBounds.origin.x;
    paddingPtr->right =
	    CGRectGetMaxX(backgroundBounds) - CGRectGetMaxX(contentBounds);
    verticalPad = backgroundBounds.size.height - contentBounds.size.height;
    paddingPtr->top = paddingPtr->bottom = verticalPad / 2;
}

static void
ButtonElementDraw(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    Drawable d,
    Ttk_Box b,
    Ttk_State state)
{
    ThemeButtonParams *params = clientData;
    CGRect bounds = BoxToRect(d, b);
    HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, state, tkwin);
    bounds = NormalizeButtonBounds(params->heightMetric, bounds);
    
    BEGIN_DRAWING(d);
    if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	switch (info.kind) {
	case kThemePushButton:
	case kThemePopupButton:
	    DrawDarkButton(bounds, info.kind, state, dc.context);
	    break;
................................................................................
	    info.value == kThemeButtonMixed) {
	    info.value = kThemeButtonOff;
	    info.state = kThemeStateInactive;
	}
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation,
		NULL);
    }
    END_DRAWING;
}

static Ttk_ElementSpec ButtonElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    ButtonElementSize,
................................................................................
 * between the content in the tab view and the tab-view edges.
 *
 * <URL: http://developer.apple.com/documentation/userexperience/Conceptual/
 *       AppleHIGuidelines/XHIGControls/XHIGControls.html#//apple_ref/doc/uid/
 *       TP30000359-TPXREF116>
 */

static void
TabElementSize(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    int *minWidth, int *minHeight,
    Ttk_Padding *paddingPtr)
{
    GetThemeMetric(kThemeMetricLargeTabHeight, (SInt32 *) minHeight);
    *paddingPtr = Ttk_MakePadding(0, 0, 0, 2);
}


static void
TabElementDraw(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    Drawable d,
    Ttk_Box b,
    Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);
    HIThemeTabDrawInfo info = {
	.version = 1,
	.style = Ttk_StateTableLookup(TabStyleTable, state),
	.direction = kThemeTabNorth,
	.size = kHIThemeTabSizeNormal,
	.adornment = Ttk_StateTableLookup(TabAdornmentTable, state),
	.kind = kHIThemeTabKindNormal,
	.position = Ttk_StateTableLookup(TabPositionTable, state),
    };

    BEGIN_DRAWING(d);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkTab(bounds, state, dc.context);
    } else {
	ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL);
    }
#else
    ChkErr(HIThemeDrawTab, &bounds, &info, dc.context, HIOrientation, NULL);
#endif
    END_DRAWING;
}

static Ttk_ElementSpec TabElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TabElementSize,
................................................................................
}

static void PaneElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);

    bounds.origin.y -= kThemeMetricTabFrameOverlap;
    bounds.size.height += kThemeMetricTabFrameOverlap;
    BEGIN_DRAWING(d);
    if ([NSApp macMinorVersion] > 9) {
#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080
	DrawGroupBox(bounds, dc.context, tkwin);
#endif
    } else { 
	HIThemeTabPaneDrawInfo info = {
	    .version = 1,
	    .state = Ttk_StateTableLookup(ThemeStateTable, state),
	    .direction = kThemeTabNorth,
	    .size = kHIThemeTabSizeNormal,
	    .kind = kHIThemeTabKindNormal,
	    .adornment = kHIThemeTabPaneAdornmentNormal,
	};
	bounds.origin.y -= kThemeMetricTabFrameOverlap;
	bounds.size.height += kThemeMetricTabFrameOverlap;
	ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrientation);
    }
    END_DRAWING;
}

static Ttk_ElementSpec PaneElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    PaneElementSize,
................................................................................
 * a maximum of 2 pixels thick."
 *
 * "Maximum of 2 pixels thick" is apparently a lie; looks more like 4 to me
 * with shading.
 */

static void GroupElementSize(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    int *minWidth, int *minHeight,
    Ttk_Padding *paddingPtr)
{
    *paddingPtr = Ttk_UniformPadding(4);
}

static void GroupElementDraw(
    void *clientData,
    void *elementRecord,
    Tk_Window tkwin,
    Drawable d,
    Ttk_Box b,
    Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);

    BEGIN_DRAWING(d);
    if ([NSApp macMinorVersion] > 9) {
#if MAC_OS_X_VERSION_MAX_ALLOWED > 1080
	DrawGroupBox(bounds, dc.context, tkwin);
#endif
    } else { 
	const HIThemeGroupBoxDrawInfo info = {
	    .version = 0,
	    .state = Ttk_StateTableLookup(ThemeStateTable, state),
	    .kind = kHIThemeGroupBoxKindPrimaryOpaque,
	};
	ChkErr(HIThemeDrawGroupBox, &bounds, &info, dc.context, HIOrientation);
    }
    END_DRAWING;
}

static Ttk_ElementSpec GroupElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    GroupElementSize,
................................................................................
    Tcl_Obj	*fieldbackgroundObj;
} EntryElement;

#define ENTRY_DEFAULT_BACKGROUND "systemTextBackgroundColor"

static Ttk_ElementOptionSpec EntryElementOptions[] = {
    { "-background", TK_OPTION_BORDER,
	Tk_Offset(EntryElement,backgroundObj), ENTRY_DEFAULT_BACKGROUND },
    { "-fieldbackground", TK_OPTION_BORDER,
	Tk_Offset(EntryElement,fieldbackgroundObj), ENTRY_DEFAULT_BACKGROUND },
    {0}
};

static void EntryElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
................................................................................
    CGRect bounds = BoxToRect(d, inner);
    NSColor *background;
    Tk_3DBorder backgroundPtr = NULL;
    static const char *defaultBG = ENTRY_DEFAULT_BACKGROUND;

    if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	BEGIN_DRAWING(d);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	CGFloat fill[4];

	GetBackgroundColor(dc.context, tkwin, 1, fill);
	background = [NSColor colorWithColorSpace: deviceRGB
				       components: fill
					    count: 4];
	CGContextSetFillColorWithColor(dc.context, background.CGColor);
	CGContextFillRect(dc.context, bounds);
	DrawDarkFrame(bounds, dc.context, kHIThemeFrameTextFieldSquare);
	END_DRAWING;
#endif
    } else {
	const HIThemeFrameDrawInfo info = {
	    .version = 0,
	    .kind = kHIThemeFrameTextFieldSquare,
	    .state = Ttk_StateTableLookup(ThemeStateTable, state),
	    .isFocused = state & TTK_STATE_FOCUS,
................................................................................
	    backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->backgroundObj);
	}
	if (backgroundPtr != NULL) {
	    XFillRectangle(Tk_Display(tkwin), d,
		    Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC),
		    inner.x, inner.y, inner.width, inner.height);
	}
	BEGIN_DRAWING(d);
	if (backgroundPtr == NULL) {
	    background = [NSColor textBackgroundColor];
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	    CGContextSetFillColorWithColor(dc.context, background.CGColor);
#else
	    CGContextSetRGBFillColor(dc.context, 1.0, 1.0, 1.0, 1.0);
#endif
	    CGContextFillRect(dc.context, bounds);
	}
	ChkErr(HIThemeDrawFrame, &bounds, &info, dc.context, HIOrientation);
	END_DRAWING;
    }
    /*if (state & TTK_STATE_FOCUS) {
	ChkErr(DrawThemeFocusRect, &bounds, 1);
    }*/
}

static Ttk_ElementSpec EntryElementSpec = {
................................................................................
	.version = 0,
	.state = Ttk_StateTableLookup(ThemeStateTable, state),
	.kind = kThemeComboBox,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = Ttk_StateTableLookup(ButtonAdornmentTable, state),
    };

    BEGIN_DRAWING(d);
    bounds.origin.y += 1;
    if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	bounds.size.height += 1;
	DrawDarkButton(bounds, info.kind, state, dc.context);
#endif
    } else {

#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	if ((state & TTK_STATE_BACKGROUND) &&
		!(state & TTK_STATE_DISABLED)) {
	    NSColor *background = [NSColor textBackgroundColor];
	    CGRect innerBounds = CGRectInset(bounds, 1, 2);

	    SolidFillRoundedRectangle(dc.context, innerBounds, 4, background);
	}
#endif
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING;
}

static Ttk_ElementSpec ComboboxElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    ComboboxElementSize,
................................................................................

static void SpinButtonUpElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins));
    int infoState;

    bounds.size.height *= 2;
    if (state & TTK_STATE_PRESSED) {
	infoState = kThemeStatePressedUp;
    } else {
	infoState = Ttk_StateTableLookup(ThemeStateTable, state);
    }

    const HIThemeButtonDrawInfo info = {
	.version = 0,
	.state = infoState,
	.kind = kThemeIncDecButton,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = kThemeAdornmentNone,
    };

    BEGIN_DRAWING(d);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkIncDecButton(bounds, infoState, state, dc.context);
    } else
#endif
    {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING;
}

static Ttk_ElementSpec SpinButtonUpElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SpinButtonUpElementSize,
................................................................................

static void SpinButtonDownElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, Ttk_PadBox(b, SpinbuttonMargins));
    int infoState = 0;

    bounds.origin.y -= bounds.size.height;
    bounds.size.height *= 2;
    if (state & TTK_STATE_PRESSED) {
	infoState = kThemeStatePressedDown;
    } else {
	return;		// ???
    }
    const HIThemeButtonDrawInfo info = {
	.version = 0,
	.state = infoState,
	.kind = kThemeIncDecButton,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = kThemeAdornmentNone,
    };

    BEGIN_DRAWING(d);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkIncDecButton(bounds, infoState, state, dc.context);
    } else
#endif
    {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation,
		NULL);
    }
    END_DRAWING;
}

static Ttk_ElementSpec SpinButtonDownElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SpinButtonDownElementSize,
................................................................................
		kThemeThumbPressed : 0;
	if (state & TTK_STATE_ALTERNATE) {
	    info.trackInfo.slider.thumbDir = kThemeThumbDownward;
	} else {
	    info.trackInfo.slider.thumbDir = kThemeThumbPlain;
	}
    }
    BEGIN_DRAWING(d);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	CGRect bounds = BoxToRect(d, b);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB
	 					components: darkTrack
	 					     count: 4];

	if (orientation == TTK_ORIENT_HORIZONTAL) {
	    bounds = CGRectInset(bounds, 1, bounds.size.height/2 - 2);
	} else {
	    bounds = CGRectInset(bounds, bounds.size.width/2 - 3, 2);
	}
	SolidFillRoundedRectangle(dc.context, bounds, 2, trackColor);
    }
#endif
    ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation);
    END_DRAWING;
}

static Ttk_ElementSpec TrackElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(TrackElement),
    TrackElementOptions,
    TrackElementSize,
................................................................................
 * Has geometry only. The Scale widget adjusts the position of this element,
 * and uses it for hit detection. In the Aqua theme, the slider is actually
 * drawn as part of the trough element.
 *
 * Also buggy: The geometry here is a Wild-Assed-Guess; I can't figure out how
 * to get the Appearance Manager to tell me the slider size.
 */

static void SliderElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
    *minWidth = *minHeight = 24;
}

................................................................................
	.attributes = kThemeTrackShowThumb |
		(orientation == TTK_ORIENT_HORIZONTAL ?
		kThemeTrackHorizontal : 0),
	.enableState = Ttk_StateTableLookup(ThemeTrackEnableTable, state),
	.trackInfo.progress.phase = phase,
    };

    BEGIN_DRAWING(d);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	CGRect bounds = BoxToRect(d, b);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	NSColor *trackColor = [NSColor colorWithColorSpace: deviceRGB
	 					components: darkTrack
	 					     count: 4];
................................................................................
	} else {
	    bounds = CGRectInset(bounds, bounds.size.width/2 - 3, 1);
	}
	SolidFillRoundedRectangle(dc.context, bounds, 3, trackColor);
    }
#endif
    ChkErr(HIThemeDrawTrack, &info, NULL, dc.context, HIOrientation);
    END_DRAWING;
}

static Ttk_ElementSpec PbarElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(PbarElement),
    PbarElementOptions,
    PbarElementSize,
................................................................................
{
    ScrollbarElement *scrollbar = elementRecord;
    int orientation = TTK_ORIENT_HORIZONTAL;
    CGRect bounds = BoxToRect(d, b);
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *troughColor;
    CGFloat *rgba = TkMacOSXInDarkMode(tkwin) ? darkTrough : lightTrough;

    Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation);
    if (orientation == TTK_ORIENT_HORIZONTAL) {
	bounds = CGRectInset(bounds, 0, 1);
    } else {
	bounds = CGRectInset(bounds, 1, 0);
    }
    troughColor = [NSColor colorWithColorSpace: deviceRGB
				    components: rgba
					 count: 4];
    BEGIN_DRAWING(d);
    if ([NSApp macMinorVersion] > 8) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	CGContextSetFillColorWithColor(dc.context, troughColor.CGColor);
#endif
    } else {
	ChkErr(HIThemeSetFill, kThemeBrushDocumentWindowBackground, NULL,
	       dc.context, HIOrientation);
    }
    CGContextFillRect(dc.context, bounds);
    END_DRAWING;
}

static Ttk_ElementSpec TroughElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(ScrollbarElement),
    ScrollbarElementOptions,
    TroughElementSize,
................................................................................

static void ThumbElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    ScrollbarElement *scrollbar = elementRecord;
    int orientation = TTK_ORIENT_HORIZONTAL;

    Ttk_GetOrientFromObj(NULL, scrollbar->orientObj, &orientation);

    /*
     * In order to make ttk scrollbars work correctly it is necessary to be
     * able to display the thumb element at the size and location which the ttk
     * scrollbar widget requests.  The algorithm that HIToolbox uses to
     * determine the thumb geometry from the input values of min, max, value
................................................................................

    if ([NSApp macMinorVersion] > 8) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	CGRect thumbBounds = BoxToRect(d, b);
	NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
	NSColor *thumbColor;
	CGFloat *rgba;

	if ((orientation == TTK_ORIENT_HORIZONTAL
		&& thumbBounds.size.width >= Tk_Width(tkwin) - 8)
		|| (orientation == TTK_ORIENT_VERTICAL
		&& thumbBounds.size.height >= Tk_Height(tkwin) - 8)) {
	    return;
	}

	int isDark = TkMacOSXInDarkMode(tkwin);

	if ((state & TTK_STATE_PRESSED) ||
		(state & TTK_STATE_HOVER)) {
	    rgba = isDark ? darkActiveThumb : lightActiveThumb;
	} else {
	    rgba = isDark ? darkInactiveThumb : lightInactiveThumb;
	}
	thumbColor = [NSColor colorWithColorSpace: deviceRGB
				       components: rgba
					    count: 4];
	BEGIN_DRAWING(d);
	SolidFillRoundedRectangle(dc.context, thumbBounds, 4, thumbColor);
	END_DRAWING;
#endif
    } else {
	double thumbSize, trackSize, visibleSize, viewSize;
	MacDrawable *macWin = (MacDrawable *) Tk_WindowId(tkwin);
	CGRect troughBounds = {{macWin->xOff, macWin->yOff},
			       {Tk_Width(tkwin), Tk_Height(tkwin)}};

................................................................................
	 * floats in the drawing routine.  All of values provided in the info
	 * struct, namely min, max, value, and viewSize are only defined up to
	 * an arbitrary scale factor.  To avoid roundoff error we scale so that
	 * the viewSize is a large float which is smaller than the largest int.
	 */
    
	viewSize = RangeToFactor(100.0);

	HIThemeTrackDrawInfo info = {
	    .version = 0,
	    .bounds = troughBounds,
	    .min = 0,
	    .attributes = kThemeTrackShowThumb | kThemeTrackThumbRgnIsNotGhost,
	    .enableState = kThemeTrackActive
	};

	info.trackInfo.scrollbar.viewsize = viewSize*.8; 
	if (orientation == TTK_ORIENT_HORIZONTAL) {
	    trackSize = troughBounds.size.width;
	    thumbSize = b.width;
	    visibleSize = (thumbSize / trackSize) * viewSize;
	    info.max = viewSize - visibleSize;
	    info.value = info.max * (b.x / (trackSize - thumbSize)); 
................................................................................
	    thumbSize = b.height;
	    trackSize = troughBounds.size.height;
	    visibleSize = (thumbSize / trackSize) * viewSize;
	    info.max = viewSize - visibleSize;
	    info.value = info.max * (b.y / (trackSize - thumbSize)); 
	}
	if ((state & TTK_STATE_PRESSED) ||
		(state & TTK_STATE_HOVER)) {
	    info.trackInfo.scrollbar.pressState = kThemeThumbPressed;
	} else {
	    info.trackInfo.scrollbar.pressState = 0;
	}
	if (orientation == TTK_ORIENT_HORIZONTAL) {
	    info.attributes |= kThemeTrackHorizontal;
	} else {
	    info.attributes &= ~kThemeTrackHorizontal;
	}
	BEGIN_DRAWING(d);
	HIThemeDrawTrack(&info, 0, dc.context, kHIThemeOrientationNormal);
	END_DRAWING;
    }
}

static Ttk_ElementSpec ThumbElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(ScrollbarElement),
    ScrollbarElementOptions,
    ThumbElementSize,
................................................................................
    CGRect bounds = BoxToRect(d, b);
    const HIThemeSeparatorDrawInfo info = {
	.version = 0,
	/* Separator only supports kThemeStateActive, kThemeStateInactive */
	.state = Ttk_StateTableLookup(ThemeStateTable, state & TTK_STATE_BACKGROUND),
    };

    BEGIN_DRAWING(d);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkSeparator(bounds, dc.context, tkwin);
    } else {
	ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation);
    }
#else
    ChkErr(HIThemeDrawSeparator, &bounds, &info, dc.context, HIOrientation);
#endif
    END_DRAWING;
}

static Ttk_ElementSpec SeparatorElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SeparatorElementSize,
................................................................................
	.state = Ttk_StateTableLookup(ThemeStateTable,
		state & TTK_STATE_BACKGROUND),
	.kind = kHIThemeGrowBoxKindNormal,
	.direction = sizegripGrowDirection,
	.size = kHIThemeGrowBoxSizeNormal,
    };

    BEGIN_DRAWING(d);
    ChkErr(HIThemeDrawGrowBox, &bounds.origin, &info, dc.context, HIOrientation);
    END_DRAWING;
}

static Ttk_ElementSpec SizegripElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    SizegripElementSize,
................................................................................
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
    NSColorSpace *deviceRGB = [NSColorSpace deviceRGBColorSpace];
    NSColor *bgColor;
    CGFloat fill[4];

    BEGIN_DRAWING(d);
    GetBackgroundColor(dc.context, tkwin, 0, fill);
    bgColor = [NSColor colorWithColorSpace: deviceRGB components: fill
				     count: 4];
    CGContextSetFillColorSpace(dc.context, deviceRGB.CGColorSpace);
    CGContextSetFillColorWithColor(dc.context, bgColor.CGColor);
    CGContextFillRect(dc.context, bounds);
    END_DRAWING;
#else
    ThemeBrush brush = (state & TTK_STATE_BACKGROUND)
	    ? kThemeBrushModelessDialogBackgroundInactive
	    : kThemeBrushModelessDialogBackgroundActive;

    BEGIN_DRAWING(d);
    ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation);
    //QDSetPatternOrigin(PatternOrigin(tkwin, d));
    CGContextFillRect(dc.context, bounds);
    END_DRAWING;
#endif
}

static void BackgroundElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, unsigned int state)
{
    FillElementDraw(clientData, elementRecord, tkwin, d, Ttk_WinBox(tkwin),
	    state);
}

static Ttk_ElementSpec FillElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TtkNullElementSize,
................................................................................
    BackgroundElementDraw
};

/*----------------------------------------------------------------------
 * +++ ToolbarBackground element -- toolbar style for frames.
 *
 *    This is very similar to the normal background element, but uses a
 *    different ThemeBrush in order to get the lighter pinstripe effect used in
 *    toolbars. We use SetThemeBackground() rather than ApplyThemeBackground()
 *    in order to get the right style.
 *
 * <URL: http://developer.apple.com/documentation/Carbon/Reference/
 *    Appearance_Manager/appearance_manager/constant_7.html#/
 *    /apple_ref/doc/uid/TP30000243/C005321>
 *
 */

................................................................................
static void ToolbarBackgroundElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    ThemeBrush brush = kThemeBrushToolbarBackground;
    CGRect bounds = BoxToRect(d, Ttk_WinBox(tkwin));

    BEGIN_DRAWING(d);
    ChkErr(HIThemeSetFill, brush, NULL, dc.context, HIOrientation);
    //QDSetPatternOrigin(PatternOrigin(tkwin, d));
    CGContextFillRect(dc.context, bounds);
    END_DRAWING;
}

static Ttk_ElementSpec ToolbarBackgroundElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TtkNullElementSize,
................................................................................
	    TTK_STATE_SELECTED|TTK_TREEVIEW_STATE_SORTARROW},
    { kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_ALTERNATE},
    { kThemeAdornmentHeaderButtonNoSortArrow, TTK_STATE_SELECTED},
    { kThemeAdornmentFocus, TTK_STATE_FOCUS},
    { kThemeAdornmentNone, 0}
};

static void TreeAreaElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{ 
    /*
     * Padding is needed to get the heading text to align correctly, since the
     * widget expects the heading to be the same height as a row.
     */
................................................................................
	.version = 0,
	.state = Ttk_StateTableLookup(ThemeStateTable, state),
	.kind = params->kind,
	.value = Ttk_StateTableLookup(TreeHeaderValueTable, state),
	.adornment = Ttk_StateTableLookup(TreeHeaderAdornmentTable, state),
    };

    BEGIN_DRAWING(d);
    if ([NSApp macMinorVersion] > 8) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080

	/*
	 * Compensate for the padding added in TreeHeaderElementSize, so the
	 * larger heading will be drawn at the top of the widget.
	 */
	
	bounds.origin.y -= 4;
	if (TkMacOSXInDarkMode(tkwin)) {
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	    DrawDarkListHeader(bounds, dc.context, tkwin, state);
#endif
................................................................................
	} else {
	    DrawListHeader(bounds, dc.context, tkwin, state);
	}
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */
    } else {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING;
}

static Ttk_ElementSpec TreeHeaderElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    TreeHeaderElementSize,
................................................................................
	    .version = 0,
	    .state = triangleState,
	    .kind = kThemeDisclosureTriangle,
	    .value = Ttk_StateTableLookup(DisclosureValueTable, state),
	    .adornment = kThemeAdornmentDrawIndicatorOnly,
	};

	BEGIN_DRAWING(d);
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
	END_DRAWING;
    }
}

static Ttk_ElementSpec DisclosureElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
................................................................................

TTK_LAYOUT("Horizontal.TScrollbar",
    TTK_GROUP("Horizontal.Scrollbar.trough", TTK_FILL_X,
	TTK_NODE("Horizontal.Scrollbar.thumb", TTK_PACK_LEFT|TTK_EXPAND|TTK_FILL_BOTH)
	TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT)
	TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_RIGHT)))

TTK_END_LAYOUT_TABLE;

/*----------------------------------------------------------------------
 * +++ Initialization.
 */

static int
AquaTheme_Init(
    Tcl_Interp *interp)
{
    Ttk_Theme themePtr = Ttk_CreateTheme(interp, "aqua", NULL);

    if (!themePtr) {
	return TCL_ERROR;
    }

    /*
     * Elements:
     */

    Ttk_RegisterElementSpec(themePtr, "background", &BackgroundElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "fill", &FillElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "field", &FieldElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Toolbar.background",
	    &ToolbarBackgroundElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "Button.button",
	    &ButtonElementSpec, &PushButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Checkbutton.button",
	    &ButtonElementSpec, &CheckBoxParams);
    Ttk_RegisterElementSpec(themePtr, "Radiobutton.button",
	    &ButtonElementSpec, &RadioButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Toolbutton.border",
     	    &ButtonElementSpec, &BevelButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Menubutton.button",
	    &ButtonElementSpec, &PopupButtonParams);
    Ttk_RegisterElementSpec(themePtr, "Spinbox.uparrow",
	    &SpinButtonUpElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Spinbox.downarrow",
    	    &SpinButtonDownElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Combobox.button",
	    &ComboboxElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Treeitem.indicator",
	    &DisclosureElementSpec, &DisclosureParams);
    Ttk_RegisterElementSpec(themePtr, "Treeheading.cell",
	    &TreeHeaderElementSpec, &ListHeaderParams);

    Ttk_RegisterElementSpec(themePtr, "Treeview.treearea",
	    &TreeAreaElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Notebook.tab", &TabElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Notebook.client", &PaneElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "Labelframe.border",
	    &GroupElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Entry.field", &EntryElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "Spinbox.field", &EntryElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr, "separator", &SeparatorElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "hseparator", &SeparatorElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr, "vseparator", &SeparatorElementSpec, 0);

................................................................................
     * pbar element.  But in our case the appearance manager draws both parts
     * of the progress bar, so we just have a single element called ".track".
     */

    Ttk_RegisterElementSpec(themePtr,"Progressbar.track", &PbarElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Scale.trough", &TrackElementSpec,
	    &ScaleData);
    Ttk_RegisterElementSpec(themePtr,"Scale.slider", &SliderElementSpec, 0);

    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.trough",
	    &TroughElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.thumb",
	    &ThumbElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.trough",
	    &TroughElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.thumb",
	    &ThumbElementSpec, 0);

    /*
     * If we are not in Snow Leopard or Lion the arrows won't actually be
     * displayed.
     */

    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.uparrow",
	    &ArrowElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr,"Vertical.Scrollbar.downarrow",
	    &ArrowElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.leftarrow",
	    &ArrowElementSpec, 0);
    Ttk_RegisterElementSpec(themePtr,"Horizontal.Scrollbar.rightarrow",
	    &ArrowElementSpec, 0);

    /*
     * Layouts:
     */

    Ttk_RegisterLayouts(themePtr, LayoutTable);