Check-in [9995508acd]
Not logged in

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

Overview
Comment:add tk upstream changes
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 9995508acdfb4f839e53634dd5b01660fce4f79c
User & Date: chw 2019-04-12 04:58:15
Context
2019-04-12
21:10
handle auto_path setup proper when info nameofexecutable is empty check-in: 3f0769cc0a user: chw tags: trunk
04:59
merge with trunk check-in: f9d93e8f51 user: chw tags: wtf-8-experiment
04:58
add tk upstream changes check-in: 9995508acd user: chw tags: trunk
04:57
add tcl upstream changes check-in: 1ce9b0599a user: chw tags: trunk
Changes

Changes to jni/sdl2tk/macosx/tkMacOSXMouseEvent.c.

20
21
22
23
24
25
26
27

28
29
30
31
32
33
34
35
36
37
38
..
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

59
60
61
62
63
64
65
..
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
...
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
...
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
...
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
...
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
...
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
...
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
typedef struct {
    unsigned int state;
    long delta;
    Window window;
    Point global;
    Point local;
} MouseEventData;
static Tk_Window captureWinPtr = NULL; /* Current capture window; may be NULL. */


static int		GenerateButtonEvent(MouseEventData *medPtr);
static unsigned int	ButtonModifiers2State(UInt32 buttonState,
					      UInt32 keyModifiers);

#pragma mark TKApplication(TKMouseEvent)

enum {
    NSWindowWillMoveEventType = 20
};
/*
................................................................................
 * window that it received in a mouse event. If it receives an NSEvent with a
 * Nil window attribute then the saved window is used.
 */

@implementation TKApplication(TKMouseEvent)
- (NSEvent *) tkProcessMouseEvent: (NSEvent *) theEvent
{
    NSWindow*    eventWindow = [theEvent window];
    NSEventType	 eventType = [theEvent type];
    TkWindow *winPtr, *grabWinPtr;
    Tk_Window tkwin;
#if 0
    NSTrackingArea  *trackingArea = nil;
    NSInteger eventNumber, clickCount, buttonNumber;
#endif

#ifdef TK_MAC_DEBUG_EVENTS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, theEvent);
#endif
    switch (eventType) {
    case NSMouseEntered:
    case NSMouseExited:
    case NSCursorUpdate:
................................................................................
    case NSLeftMouseDragged:
    case NSRightMouseDragged:
    case NSOtherMouseDragged:
    case NSMouseMoved:
    case NSTabletPoint:
    case NSTabletProximity:
    case NSScrollWheel:
        break;
    default: /* Unrecognized mouse event. */
	return theEvent;
    }


    /* Remember the window in case we need it next time. */


    if (eventWindow && eventWindow != _windowWithMouse) {
	if (_windowWithMouse) {
	    [_windowWithMouse release];
	}
	_windowWithMouse = eventWindow;
	[_windowWithMouse retain];
    }

    /*
     * Compute the mouse position in Tk screen coordinates (global) and in
     * the Tk coordinates of its containing Tk Window.
     */

    NSPoint global, local = [theEvent locationInWindow];

    /*
     * If the event has no NSWindow, try using the cached NSWindow from the
     * last mouse event.
     */

    if (eventWindow == NULL) {
	eventWindow = _windowWithMouse;
    }
    if (eventWindow) {

	/*
	 * Set the local mouse position to its NSWindow flipped coordinates,
	 * with the origin at top left, and the global mouse position to the
	 * flipped screen coordinates.
	 */

	global = [eventWindow tkConvertPointToScreen: local];
	local.y = [eventWindow frame].size.height - local.y;
	global.y = tkMacOSXZeroScreenHeight - global.y;

    } else {

	/*
	 * As a last resort, with no NSWindow to work with, set both local and
	 * global to the screen coordinates.
	 */

	local.y = tkMacOSXZeroScreenHeight - local.y;
	global = local;
................................................................................
    /*
     * Find the toplevel which corresponds to the event NSWindow.
     */

    winPtr = TkMacOSXGetTkWindow(eventWindow);
    if (winPtr == NULL) {
	tkwin = TkMacOSXGetCapture();
	winPtr = (TkWindow *)tkwin;
    } else {
	tkwin = (Tk_Window) winPtr;
    }
    if (!tkwin) {

	TkMacOSXDbgMsg("tkwin == NULL");

	return theEvent; /* Give up.  No window for this event. */
    }

    /*
     * If another toplevel has a grab, we ignore the event.
     */

    grabWinPtr = winPtr->dispPtr->grabWinPtr;
    if (grabWinPtr &&
	grabWinPtr != winPtr &&
	!winPtr->dispPtr->grabFlags && /* this means the grab is local. */
	grabWinPtr->mainPtr == winPtr->mainPtr) {
	return theEvent;
    }

    /*
     * Convert local from NSWindow flipped coordinates to the toplevel's
     * coordinates.
     */
................................................................................
     */

    unsigned int state = 0;
    NSInteger button = [theEvent buttonNumber];
    EventRef eventRef = (EventRef)[theEvent eventRef];
    UInt32 buttons;
    OSStatus err = GetEventParameter(eventRef, kEventParamMouseChord,
				     typeUInt32, NULL, sizeof(UInt32), NULL, &buttons);

    if (err == noErr) {
    	state |= (buttons & ((1<<5) - 1)) << 8;
    } else if (button < 5) {
	switch (eventType) {
	case NSLeftMouseDown:
	case NSRightMouseDown:
................................................................................
	state |= Mod3Mask;
    }
    if (modifiers & NSFunctionKeyMask) {
	state |= Mod4Mask;
    }

    if (eventType != NSScrollWheel) {

	/*
	 * For normal mouse events, Tk_UpdatePointer will send the XEvent.
	 */

#ifdef TK_MAC_DEBUG_EVENTS
	TKLog(@"UpdatePointer %p x %f.0 y %f.0 %d", tkwin, global.x, global.y, state);

#endif
	Tk_UpdatePointer(tkwin, global.x, global.y, state);
    } else {

	/*
	 * For scroll wheel events we need to send the XEvent here.
	 */
	
	CGFloat delta;
	int coarseDelta;
	XEvent xEvent;
................................................................................
	xEvent.xany.send_event = false;
	xEvent.xany.display = Tk_Display(tkwin);
	xEvent.xany.window = Tk_WindowId(tkwin);

	delta = [theEvent deltaY];
	if (delta != 0.0) {
	    coarseDelta = (delta > -1.0 && delta < 1.0) ?
		(signbit(delta) ? -1 : 1) : lround(delta);
	    xEvent.xbutton.state = state;
	    xEvent.xkey.keycode = coarseDelta;
	    xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
	    Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
	}
	delta = [theEvent deltaX];
	if (delta != 0.0) {
	    coarseDelta = (delta > -1.0 && delta < 1.0) ?
		(signbit(delta) ? -1 : 1) : lround(delta);
	    xEvent.xbutton.state = state | ShiftMask;
	    xEvent.xkey.keycode = coarseDelta;
	    xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
	    Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
	}
    }
    return theEvent;
................................................................................

    /*
     * Tell the OSX core to generate the events to make it happen.
     */

    buttonState = [NSEvent pressedMouseButtons];
    CGEventType type = kCGEventMouseMoved;
    CGEventRef theEvent = CGEventCreateMouseEvent(NULL,
						  type,
						  pt,
						  buttonState);
    CGWarpMouseCursorPosition(pt);
    CGEventPost(kCGHIDEventTap, theEvent);
    CFRelease(theEvent);
}
 
/*
 *----------------------------------------------------------------------
................................................................................

Tk_Window
TkMacOSXGetCapture(void)
{
    return captureWinPtr;
}
 


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







|
>



|







 







|
|



|


>







 







|




>
|
>
>









|
|













<









<

<







 







|




>

>
|








|
|
|







 







|







 







<





|
>



<







 







|








|







 







|
<
<
|







 







<









20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
..
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
..
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
...
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
...
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
...
227
228
229
230
231
232
233

234
235
236
237
238
239
240
241
242
243

244
245
246
247
248
249
250
...
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
...
626
627
628
629
630
631
632
633


634
635
636
637
638
639
640
641
...
681
682
683
684
685
686
687

688
689
690
691
692
693
694
695
696
typedef struct {
    unsigned int state;
    long delta;
    Window window;
    Point global;
    Point local;
} MouseEventData;
static Tk_Window captureWinPtr = NULL;	/* Current capture window; may be
					 * NULL. */

static int		GenerateButtonEvent(MouseEventData *medPtr);
static unsigned int	ButtonModifiers2State(UInt32 buttonState,
			    UInt32 keyModifiers);

#pragma mark TKApplication(TKMouseEvent)

enum {
    NSWindowWillMoveEventType = 20
};
/*
................................................................................
 * window that it received in a mouse event. If it receives an NSEvent with a
 * Nil window attribute then the saved window is used.
 */

@implementation TKApplication(TKMouseEvent)
- (NSEvent *) tkProcessMouseEvent: (NSEvent *) theEvent
{
    NSWindow *eventWindow = [theEvent window];
    NSEventType eventType = [theEvent type];
    TkWindow *winPtr, *grabWinPtr;
    Tk_Window tkwin;
#if 0
    NSTrackingArea *trackingArea = nil;
    NSInteger eventNumber, clickCount, buttonNumber;
#endif

#ifdef TK_MAC_DEBUG_EVENTS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, theEvent);
#endif
    switch (eventType) {
    case NSMouseEntered:
    case NSMouseExited:
    case NSCursorUpdate:
................................................................................
    case NSLeftMouseDragged:
    case NSRightMouseDragged:
    case NSOtherMouseDragged:
    case NSMouseMoved:
    case NSTabletPoint:
    case NSTabletProximity:
    case NSScrollWheel:
	break;
    default: /* Unrecognized mouse event. */
	return theEvent;
    }

    /*
     * Remember the window in case we need it next time.
     */

    if (eventWindow && eventWindow != _windowWithMouse) {
	if (_windowWithMouse) {
	    [_windowWithMouse release];
	}
	_windowWithMouse = eventWindow;
	[_windowWithMouse retain];
    }

    /*
     * Compute the mouse position in Tk screen coordinates (global) and in the
     * Tk coordinates of its containing Tk Window.
     */

    NSPoint global, local = [theEvent locationInWindow];

    /*
     * If the event has no NSWindow, try using the cached NSWindow from the
     * last mouse event.
     */

    if (eventWindow == NULL) {
	eventWindow = _windowWithMouse;
    }
    if (eventWindow) {

	/*
	 * Set the local mouse position to its NSWindow flipped coordinates,
	 * with the origin at top left, and the global mouse position to the
	 * flipped screen coordinates.
	 */

	global = [eventWindow tkConvertPointToScreen: local];
	local.y = [eventWindow frame].size.height - local.y;
	global.y = tkMacOSXZeroScreenHeight - global.y;

    } else {

	/*
	 * As a last resort, with no NSWindow to work with, set both local and
	 * global to the screen coordinates.
	 */

	local.y = tkMacOSXZeroScreenHeight - local.y;
	global = local;
................................................................................
    /*
     * Find the toplevel which corresponds to the event NSWindow.
     */

    winPtr = TkMacOSXGetTkWindow(eventWindow);
    if (winPtr == NULL) {
	tkwin = TkMacOSXGetCapture();
	winPtr = (TkWindow *) tkwin;
    } else {
	tkwin = (Tk_Window) winPtr;
    }
    if (!tkwin) {
#ifdef TK_MAC_DEBUG_EVENTS
	TkMacOSXDbgMsg("tkwin == NULL");
#endif
	return theEvent;	/* Give up.  No window for this event. */
    }

    /*
     * If another toplevel has a grab, we ignore the event.
     */

    grabWinPtr = winPtr->dispPtr->grabWinPtr;
    if (grabWinPtr &&
	    grabWinPtr != winPtr &&
	    !winPtr->dispPtr->grabFlags && /* this means the grab is local. */
	    grabWinPtr->mainPtr == winPtr->mainPtr) {
	return theEvent;
    }

    /*
     * Convert local from NSWindow flipped coordinates to the toplevel's
     * coordinates.
     */
................................................................................
     */

    unsigned int state = 0;
    NSInteger button = [theEvent buttonNumber];
    EventRef eventRef = (EventRef)[theEvent eventRef];
    UInt32 buttons;
    OSStatus err = GetEventParameter(eventRef, kEventParamMouseChord,
	    typeUInt32, NULL, sizeof(UInt32), NULL, &buttons);

    if (err == noErr) {
    	state |= (buttons & ((1<<5) - 1)) << 8;
    } else if (button < 5) {
	switch (eventType) {
	case NSLeftMouseDown:
	case NSRightMouseDown:
................................................................................
	state |= Mod3Mask;
    }
    if (modifiers & NSFunctionKeyMask) {
	state |= Mod4Mask;
    }

    if (eventType != NSScrollWheel) {

	/*
	 * For normal mouse events, Tk_UpdatePointer will send the XEvent.
	 */

#ifdef TK_MAC_DEBUG_EVENTS
	TKLog(@"UpdatePointer %p x %f.0 y %f.0 %d",
		tkwin, global.x, global.y, state);
#endif
	Tk_UpdatePointer(tkwin, global.x, global.y, state);
    } else {

	/*
	 * For scroll wheel events we need to send the XEvent here.
	 */
	
	CGFloat delta;
	int coarseDelta;
	XEvent xEvent;
................................................................................
	xEvent.xany.send_event = false;
	xEvent.xany.display = Tk_Display(tkwin);
	xEvent.xany.window = Tk_WindowId(tkwin);

	delta = [theEvent deltaY];
	if (delta != 0.0) {
	    coarseDelta = (delta > -1.0 && delta < 1.0) ?
		    (signbit(delta) ? -1 : 1) : lround(delta);
	    xEvent.xbutton.state = state;
	    xEvent.xkey.keycode = coarseDelta;
	    xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
	    Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
	}
	delta = [theEvent deltaX];
	if (delta != 0.0) {
	    coarseDelta = (delta > -1.0 && delta < 1.0) ?
		    (signbit(delta) ? -1 : 1) : lround(delta);
	    xEvent.xbutton.state = state | ShiftMask;
	    xEvent.xkey.keycode = coarseDelta;
	    xEvent.xany.serial = LastKnownRequestProcessed(Tk_Display(tkwin));
	    Tk_QueueWindowEvent(&xEvent, TCL_QUEUE_TAIL);
	}
    }
    return theEvent;
................................................................................

    /*
     * Tell the OSX core to generate the events to make it happen.
     */

    buttonState = [NSEvent pressedMouseButtons];
    CGEventType type = kCGEventMouseMoved;
    CGEventRef theEvent = CGEventCreateMouseEvent(NULL, type, pt,


	    buttonState);
    CGWarpMouseCursorPosition(pt);
    CGEventPost(kCGHIDEventTap, theEvent);
    CFRelease(theEvent);
}
 
/*
 *----------------------------------------------------------------------
................................................................................

Tk_Window
TkMacOSXGetCapture(void)
{
    return captureWinPtr;
}
 


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

Changes to jni/sdl2tk/macosx/tkMacOSXWm.c.

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
...
394
395
396
397
398
399
400

401

402
403
404
405
406
407
408
...
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
...
621
622
623
624
625
626
627

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
...
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
...
988
989
990
991
992
993
994

995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
....
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
....
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826

1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
....
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
....
2518
2519
2520
2521
2522
2523
2524

2525


2526
2527
2528
2529
2530
2531
2532
2533
2534

2535
2536


2537
2538
2539
2540
2541
2542
2543

2544


2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556

2557
2558
2559
2560
2561
2562
2563
....
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
....
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
....
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
....
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
....
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777

3778
3779
3780
3781
3782
3783
3784
3785
3786
....
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
....
4942
4943
4944
4945
4946
4947
4948

4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962

4963
4964
4965
4966
4967
4968
4969
4970
4971
4972


4973
4974
4975
4976
4977

4978
4979
4980
4981
4982
4983

4984
4985
4986
4987
4988
4989
4990
....
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
....
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
....
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
....
5555
5556
5557
5558
5559
5560
5561

5562
5563
5564
5565
5566
5567

5568
5569
5570
5571
5572
5573
5574
....
5761
5762
5763
5764
5765
5766
5767
5768

5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
....
5813
5814
5815
5816
5817
5818
5819
5820




5821
5822
5823
5824
5825
5826
5827
....
5829
5830
5831
5832
5833
5834
5835
5836
5837

5838

5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
....
5867
5868
5869
5870
5871
5872
5873

5874



5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
....
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
....
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
....
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097

6098
6099
6100
6101
6102
6103
6104
....
6120
6121
6122
6123
6124
6125
6126

6127
6128
6129
6130
6131
6132
6133
....
6514
6515
6516
6517
6518
6519
6520
6521
6522

6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
....
6679
6680
6681
6682
6683
6684
6685

6686
6687
6688
6689
6690
6691
6692
....
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729

6730
6731
6732
6733
6734
6735
6736

6737
6738
6739
6740
6741
6742
6743
....
6766
6767
6768
6769
6770
6771
6772

6773
6774
6775
6776
6777
6778
6779
....
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831

6832
6833
6834
6835

6836
6837
6838
6839
6840
6841
6842
....
6861
6862
6863
6864
6865
6866
6867

6868
6869
6870
6871
6872
6873
6874
....
6960
6961
6962
6963
6964
6965
6966

6967
6968
6969
6970
6971
6972
6973
6974
6975
6976

6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
....
7208
7209
7210
7211
7212
7213
7214

7215


7216
7217
7218
7219
7220
7221
7222
	| kWindowHideOnFullScreenAttribute  | kWindowNoConstrainAttribute \
	| kWindowNoShadowAttribute	    | kWindowLiveResizeAttribute \
	| kWindowOpaqueForEventsAttribute   | kWindowIgnoreClicksAttribute \
	| kWindowDoesNotCycleAttribute	    | tkWindowDoesNotHideAttribute \
	| tkCanJoinAllSpacesAttribute	    | tkMoveToActiveSpaceAttribute \
	| tkNonactivatingPanelAttribute	    | tkHUDWindowAttribute)


static const struct {
    const UInt64 validAttrs, defaultAttrs, forceOnAttrs, forceOffAttrs;
    int flags; NSUInteger styleMask;
} macClassAttrs[] = {
    [kAlertWindowClass] = {
	.defaultAttrs = kWindowDoesNotCycleAttribute, },
    [kMovableAlertWindowClass] = {
................................................................................

	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;
	wmPtr->yInParent = frameRect.origin.y + frameRect.size.height;
	wmPtr->parentWidth = winPtr->changes.width + frameRect.size.width;
	wmPtr->parentHeight = winPtr->changes.height + frameRect.size.height;
    }
}

................................................................................
    }
    if (DEBUG_ZOMBIES > 0){
	fprintf(stderr, ">>>> Freeing <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    [super dealloc];
}


#endif
@end

#pragma mark -
 
/*
................................................................................

    for (NSWindow *w in windows) {
	winPtr = TkMacOSXGetTkWindow(w);
	if (winPtr) {
	    WmInfo *wmPtr = winPtr->wmInfoPtr;
	    NSRect windowFrame = [w frame];
	    NSRect contentFrame = [w frame];

	    contentFrame.size.height  = [[w contentView] frame].size.height;
	    /*
	     * For consistency with other platforms, points in the
	     * title bar are not considered to be contained in the
	     * window.
	     */

	    if ((wmPtr->hints.initial_state == NormalState ||
		 wmPtr->hints.initial_state == ZoomState)) {
		if (NSMouseInRect(p, contentFrame, NO)) {
		    return winPtr;
		} else if (NSMouseInRect(p, windowFrame, NO)) {
		    return NULL;
		}
	    }
	}
................................................................................

    /*
     * If the dead window has a transient, remove references to it from
     * the transient.
     */

    for (Transient *transientPtr = wmPtr->transientPtr;
    	 transientPtr != NULL; transientPtr = transientPtr->nextPtr) {
    	TkWindow *winPtr2 = transientPtr->winPtr;
    	TkWindow *masterPtr = (TkWindow *)TkGetTransientMaster(winPtr2);

    	if (masterPtr == winPtr) {
    	    wmPtr2 = winPtr2->wmInfoPtr;
    	    wmPtr2->master = NULL;
    	}
    }

    while (wmPtr->transientPtr != NULL) {
	Transient *transientPtr = wmPtr->transientPtr;

	wmPtr->transientPtr = transientPtr->nextPtr;
	ckfree(transientPtr);
    }

    /*
     * Delete the Mac window and remove it from the windowTable. The window
     * could be nil if the window was never mapped. However, we don't do this
     * for embedded windows, they don't go in the window list, and they do not
     * own their portPtr's.
     */

    NSWindow *window = wmPtr->window;

    if (window && !Tk_IsEmbedded(winPtr) ) {
	NSWindow *parent = [window parentWindow];

	if (parent) {
	    [parent removeChildWindow:window];
	}
#if DEBUG_ZOMBIES > 0
	{
	    const char *title = [[window title] UTF8String];
	    if (title == nil) {
................................................................................
	wmPtr->window = NULL;
        [window release];

	/* 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;
		}
	    }
	}
................................................................................
	for (attribute = 0; attribute < _WMATT_LAST_ATTRIBUTE; ++attribute) {
	    Tcl_ListObjAppendElement(NULL, result,
		    Tcl_NewStringObj(WmAttributeNames[attribute], -1));
	    Tcl_ListObjAppendElement(NULL, result,
		    WmGetAttribute(winPtr, macWindow, attribute));
	}
	Tcl_SetObjResult(interp, result);
    } else if (objc == 4)  {	/* wm attributes $win -attribute */
	if (Tcl_GetIndexFromObjStruct(interp, objv[3], WmAttributeNames,
		sizeof(char *), "attribute", 0, &attribute) != TCL_OK) {
	    return TCL_ERROR;
	}
	Tcl_SetObjResult(interp, WmGetAttribute(winPtr, macWindow, attribute));
    } else if ((objc - 3) % 2 == 0) {	/* wm attributes $win -att value... */
	int i;
................................................................................

    /*
     * If this window has a transient, the transient must also be deiconified if
     * it was withdrawn by the master.
     */

    for (Transient *transientPtr = wmPtr->transientPtr;
	 transientPtr != NULL; transientPtr = transientPtr->nextPtr) {
	TkWindow *winPtr2 = transientPtr->winPtr;
	WmInfo *wmPtr2 = winPtr2->wmInfoPtr;
	TkWindow *masterPtr = (TkWindow *)TkGetTransientMaster(winPtr2);

    	if (masterPtr == winPtr) {
	    if ((wmPtr2->hints.initial_state == WithdrawnState &&
		 (transientPtr->flags & WITHDRAWN_BY_MASTER) != 0)) {
		TkpWmSetState(winPtr2, NormalState);
		transientPtr->flags &= ~WITHDRAWN_BY_MASTER;
	    }
	}
    }

    return TCL_OK;
................................................................................

    /*
     * If this window has a transient the transient must be withdrawn when
     * the master is iconified.
     */

    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;
}
................................................................................

    if (objc < 4) {
	Tcl_WrongNumArgs(interp, 2, objv,
			 "window ?-default? image1 ?image2 ...?");
	return TCL_ERROR;
    }


    /*Parse args.*/


    if (strcmp(Tcl_GetString(objv[3]), "-default") == 0) {
	isDefault = 1;
	if (objc == 4) {
	    Tcl_WrongNumArgs(interp, 2, objv,
			     "window ?-default? image1 ?image2 ...?");
	    return TCL_ERROR;
	}
    }


    /*Get icon name. We only use the first icon name because macOS does not
      support multiple images in Tk photos.*/


    char *icon;
    if (strcmp(Tcl_GetString(objv[3]), "-default") == 0) {
	icon = Tcl_GetString(objv[4]);
    }	else {
	icon = Tcl_GetString(objv[3]);
    }


    /*Get image and convert to NSImage that can be displayed as icon.*/


    tk_icon = Tk_GetImage(interp, tkwin, icon, NULL, NULL);
    if (tk_icon == NULL) {
    	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
	      "can't use \"%s\" as iconphoto: not a photo image",
	      icon));
	Tcl_SetErrorCode(interp, "TK", "WM", "ICONPHOTO", "PHOTO", NULL);
	return TCL_ERROR;
    }

    NSImage *newIcon;
    Tk_SizeOfImage(tk_icon, &width, &height);
    newIcon = TkMacOSXGetNSImageWithTkImage(winPtr->display, tk_icon, width, height);

    Tk_FreeImage(tk_icon);
    if (newIcon == NULL) {
	return TCL_ERROR;
    }
    [NSApp setApplicationIconImage: newIcon];
    return TCL_OK;
}
................................................................................
	}
	Tk_MakeWindowExist(tkwin2);
	wmPtr->hints.icon_window = Tk_WindowId(tkwin2);
	wmPtr->hints.flags |= IconWindowHint;
	wmPtr->icon = tkwin2;
	wmPtr2->iconFor = (Tk_Window) winPtr;
	if (!(wmPtr2->flags & WM_NEVER_MAPPED)) {

	    /*
	     * If the window is in normal or zoomed state, the icon should be
	     * unmapped.
	     */

	    if (wmPtr->hints.initial_state == NormalState ||
		wmPtr->hints.initial_state == ZoomState) {
		Tk_UnmapWindow(tkwin2);
	    }
	}
    }
    return TCL_OK;
}
 
................................................................................

    /*
     * Delete any current protocol handler, then create a new one with the
     * specified command, unless the command is empty.
     */

    for (protPtr = wmPtr->protPtr, prevPtr = NULL; protPtr != NULL;
	prevPtr = protPtr, protPtr = protPtr->nextPtr) {
	if (protPtr->protocol == protocol) {
	    if (prevPtr == NULL) {
		wmPtr->protPtr = protPtr->nextPtr;
	    } else {
		prevPtr->nextPtr = protPtr->nextPtr;
	    }
	    if (protPtr->command)
................................................................................
		    "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;
	}

	for (w = masterPtr; w != NULL && w->wmInfoPtr != NULL;
	     w = (TkWindow *)w->wmInfoPtr->master) {
	    if (w == winPtr) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "setting \"%s\" as master creates a transient/master cycle",
		    Tk_PathName(masterPtr)));
		Tcl_SetErrorCode(interp, "TK", "WM", "TRANSIENT", "SELF", NULL);
		return TCL_ERROR;
	    }
	}

	/*
	 * Add the transient to the master's list, if it not already there.
	 */
	
	for (transient = wmPtr2->transientPtr;
	     transient != NULL && transient->winPtr != winPtr;
	     transient = transient->nextPtr) {}
	if (transient == NULL) {
	    transient = ckalloc(sizeof(Transient));
	    transient->winPtr = winPtr;
	    transient->flags = 0;
................................................................................
	}

	/*
	 * If the master is withdrawn or iconic then withdraw the transient.
	 */

	if ((wmPtr2->hints.initial_state == WithdrawnState ||
	     wmPtr2->hints.initial_state == IconicState) &&
	    wmPtr->hints.initial_state != WithdrawnState){
	    TkpWmSetState(winPtr, WithdrawnState);
	    transient->flags |= WITHDRAWN_BY_MASTER;
	}

	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.
 *
 * Results:
 *	None
 *
 * Side effects:
 *      References to a master are removed from the transient's wmInfo
 *	structure and references to the transient are removed from its
 *      master's wmInfo.
 *
 *----------------------------------------------------------------------
 */

static void
RemoveTransient(
    TkWindow *winPtr)
{
    WmInfo *wmPtr = winPtr->wmInfoPtr, *wmPtr2;
    TkWindow *masterPtr;
    Transient *T, *temp;
    
    if (wmPtr == NULL || wmPtr->master == NULL) {
	return;
    }
    masterPtr = (TkWindow*)wmPtr->master;
    wmPtr2 = masterPtr->wmInfoPtr;
    if (wmPtr2 == NULL) {
	return;
    }
    wmPtr->master = NULL;
    T = wmPtr2->transientPtr;
    while (T != NULL) {
	if (T->winPtr != winPtr) {
	    break;
	}
	temp = T->nextPtr;
	ckfree(T);
	T = temp;
    }
    wmPtr2->transientPtr = T;
    while (T != NULL) {
	if (T->nextPtr && T->nextPtr->winPtr == winPtr) {
	    temp = T->nextPtr;
	    T->nextPtr = temp->nextPtr;
	    ckfree(temp);
	} else {
	    T = T->nextPtr;
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
    [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;
}
................................................................................
	    && ((wmPtr->sizeHintsFlags & (PBaseSize|PResizeInc))
		    == (PBaseSize|PResizeInc))) {
	return;
    }

    /*
     * If gridding was previously off, then forget about any window size
     * requests made by the user or via "wm geometry": these are in pixel
     * units and there's no easy way to translate them to grid units since the
     * new requested size of the top-level window in pixels may not yet have
     * been registered yet (it may filter up the hierarchy in DoWhenIdle
     * handlers). However, if the window has never been mapped yet then just
     * leave the window size alone: assume that it is intended to be in grid
     * units but just happened to have been specified before this procedure
     * was called.
     */

    if ((wmPtr->gridWin == NULL) && !(wmPtr->flags & WM_NEVER_MAPPED)) {
	wmPtr->width = -1;
	wmPtr->height = -1;
    }

................................................................................
    WmInfo *wmPtr = winPtr->wmInfoPtr;
    int macAboveBelow = (aboveBelow == Above ? NSWindowAbove : NSWindowBelow);
    int otherNumber = 0; /* 0 will be used when otherPtr is NULL. */

    /*
     * If the Tk windows has no drawable, or is withdrawn do nothing.
     */

    if (winPtr->window == None ||
	wmPtr == NULL          ||
	wmPtr->hints.initial_state == WithdrawnState) {
	return;
    }
    macWindow = TkMacOSXDrawableWindow(winPtr->window);
    if (macWindow == nil) {
	return;
    }
    if (otherPtr) {
	/*
	 * When otherPtr is non-NULL, if the other window has no
	 * drawable or is withdrawn, do nothing.
	 */

	WmInfo *otherWmPtr = otherPtr->wmInfoPtr;
	if (winPtr->window == None ||
	    otherWmPtr == NULL     ||
	    otherWmPtr->hints.initial_state == WithdrawnState) {
	return;
	}
	otherMacWindow = TkMacOSXDrawableWindow(otherPtr->window);
	if (otherMacWindow == nil) {
	    return;
	} else {


	    /*
	     * If the other window is OK, get its number.
	     */
	    otherNumber = [otherMacWindow windowNumber];
	}

    }

    /*
     * Just let the Mac window manager deal with all the subtleties
     * of keeping track of off-screen windows, etc.
     */

    [macWindow orderWindow:macAboveBelow relativeTo:otherNumber];
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkWmAddToColormapWindows --
................................................................................
/*
 *----------------------------------------------------------------------
 *
 * InitialWindowBounds --
 *
 *	This function calculates the initial bounds for a new Mac toplevel
 *	window. Unless the geometry is specified by the user this code will
 *	auto place the windows in a cascade diagonially across the main
 *	monitor of the Mac.
 *
 * Results:
 *	Window bounds.
 *
 * Side effects:
 *	None.
 *
................................................................................
MODULE_SCOPE int
TkMacOSXIsWindowZoomed(
    TkWindow *winPtr)
{
    NSWindow *macWindow = TkMacOSXDrawableWindow(winPtr->window);
    return [macWindow isZoomed];
}

 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXZoomToplevel --
 *
 *	The function is invoked when the user clicks in the zoom region of a
................................................................................
    int index;

    if (objc < 3) {
	Tcl_WrongNumArgs(interp, 1, objv, "option window ?arg ...?");
	return TCL_ERROR;
    }


    winPtr = (TkWindow *)
	    Tk_NameToWindow(interp, Tcl_GetString(objv[2]), tkwin);
    if (winPtr == NULL) {
	return TCL_ERROR;
    }
    if (!(winPtr->flags & TK_TOP_LEVEL)) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
................................................................................
	if ([NSApp macMinorVersion] < 9) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                "Window appearances did not exist until OSX 10.9.", -1));
	    Tcl_SetErrorCode(interp, "TK", "WINDOWSTYLE", "APPEARANCE", NULL);
	    return TCL_ERROR;
	}
	if ((objc < 3) || (objc > 4)) {

	    Tcl_WrongNumArgs(interp, 2, objv, "appearance window ?appearancename?");
	    return TCL_ERROR;
	}
	if (objc == 4 && [NSApp macMinorVersion] < 14) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                "Window appearances cannot be changed before OSX 10.14.", -1));

	    Tcl_SetErrorCode(interp, "TK", "WINDOWSTYLE", "APPEARANCE", NULL);
	    return TCL_ERROR;
	}
	return WmWinAppearance(interp, winPtr, objc, objv);
    default:
	return TCL_ERROR;
    }
................................................................................
 *----------------------------------------------------------------------
 *
 * WmWinTabbingId --
 *
 *	This procedure is invoked to process the
 *	"::tk::unsupported::MacWindowStyle tabbingid" subcommand. The command
 *	allows you to get or set the tabbingIdentifier for the NSWindow
 *      associated with a Tk Window.  The syntax is:

 *      tk::unsupported::MacWindowStyle tabbingid window ?newId?
 *
 * Results:
 *	Returns the tabbingIdentifier of the window prior to calling this
 *      function.  If the optional newId argument is omitted, the window's
 *      tabbingIdentifier is not changed.
 *
 * Side effects:
 *	Windows may only be grouped together as tabs if they all have the same
 *      tabbingIdentifier.  In particular, by giving a window a unique
 *      tabbingIdentifier one can prevent it from becoming a tab in any other
 *      window.  Note, however, that changing the tabbingIdentifier of a window
 *      which is already a tab does not cause it to become a separate window.
 *
 *
 *----------------------------------------------------------------------
 */

static int
WmWinTabbingId(
    Tcl_Interp *interp,		/* Current interpreter. */
................................................................................

	/*
	 * If the tabbingIdentifier of a tab is changed we also turn it into a
	 * separate window so we don't violate the rule that all tabs in the
	 * same frame must have the same tabbingIdentifier.
	 */

	if ([idString compare:newIdString] != NSOrderedSame && [win tab]) {




	    [win moveTabToNewWindow:nil];
	}
	return TCL_OK;
    }
#endif
    return TCL_ERROR;
}
................................................................................
/*
 *----------------------------------------------------------------------
 *
 * WmWinAppearance --
 *
 *	This procedure is invoked to process the
 *	"::tk::unsupported::MacWindowStyle appearance" subcommand. The command
 *	allows you to get or set the appearance for the NSWindow
 *      associated with a Tk Window.  The syntax is:

 *      tk::unsupported::MacWindowStyle tabbingid window ?newAppearance?

 *      Allowed appearance names are "aqua", "darkaqua", and "auto".
 *
 * Results:
 *      Returns the appearance setting of the window prior to calling this
 *	function.
 *
 * Side effects:
 *      The underlying NSWindow's appearance property is set to the specified
 *      value if the optional newAppearance argument is supplied. Otherwise
 *      the window's appearance property is not changed.  If the appearance is
 *      set to aqua or darkaqua then the window will use the associated
 *      NSAppearance even if the user has selected a different appearance with
 *      the system preferences.  If it is set to auto then the appearance
 *      property is set to nil, meaning that the preferences will determine the
 *      appearance.
 *
 *
 *----------------------------------------------------------------------
 */

static int
WmWinAppearance(
    Tcl_Interp *interp,		/* Current interpreter. */
................................................................................
    static const char *const appearanceStrings[] = {
	"aqua", "darkaqua", "auto", NULL
    };
    enum appearances {
	APPEARANCE_AQUA, APPEARANCE_DARKAQUA, APPEARANCE_AUTO
    };
    Tcl_Obj *result = NULL;

    NSAppearanceName appearance;



    const char *resultString;
    NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);
    if (win) {
	appearance = win.appearance.name;
	if (appearance == nil) {
	    resultString = appearanceStrings[APPEARANCE_AUTO];
	} else if (appearance == NSAppearanceNameAqua) {
	    resultString = appearanceStrings[APPEARANCE_AQUA];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400
	} else if (appearance == NSAppearanceNameDarkAqua) {
	    resultString = appearanceStrings[APPEARANCE_DARKAQUA];
#endif	    
	} else {
	    resultString = "unrecognized";
	}
	result = Tcl_NewStringObj(resultString, strlen(resultString));
    }
    if (result == NULL) {
	Tcl_Panic("Failed to read appearance name.");
................................................................................
    if (TkMacOSXHostToplevelExists(winPtr)) {
	return;
    }

    macWin = (MacDrawable *) winPtr->window;

    /*
     * If this is embedded, make sure its container's toplevel exists,
     * then return...
     */

    if (Tk_IsEmbedded(winPtr)) {
	TkWindow *contWinPtr = TkpGetOtherWindow(winPtr);

	if (contWinPtr != NULL) {
	    TkMacOSXMakeRealWindowExist(
................................................................................

	/*
	 * TODO: Here we should handle out of process embedding.
	 */
    }

    /*
     * If this is an override-redirect window, the NSWindow is created
     * first as a document window then converted to a simple window.
     */

    if (overrideRedirect) {
	wmPtr->macClass = kDocumentWindowClass;
    }
    macClass = wmPtr->macClass;
    wmPtr->attributes &= (tkAlwaysValidAttributes |
................................................................................
    [window setReleasedWhenClosed:NO];
    if (styleMask & NSUtilityWindowMask) {
	[(NSPanel*)window setFloatingPanel:YES];
    }
    if ((styleMask & (NSTexturedBackgroundWindowMask|NSHUDWindowMask)) &&
	    !(styleMask & NSDocModalWindowMask)) {
        /*
	 * Workaround for [Bug 2824538]: Textured windows are draggable
	 *                               from opaque content.
	 */
	[window setMovableByWindowBackground:NO];
    }
    [window setDocumentEdited:NO];
    wmPtr->window = window;
    macWin->view = window.contentView;
    TkMacOSXApplyWindowAttributes(winPtr, window);
    NSRect geometry = InitialWindowBounds(winPtr, window);
    geometry.size.width +=  structureRect.size.width;
    geometry.size.height += structureRect.size.height;
    geometry.origin.y = tkMacOSXZeroScreenHeight - (geometry.origin.y +
	    geometry.size.height);
    [window setFrame:geometry display:YES];
    TkMacOSXRegisterOffScreenWindow((Window) macWin, window);

    macWin->flags |= TK_HOST_EXISTS;
    if (overrideRedirect) {
    	XSetWindowAttributes atts;

    	atts.override_redirect = True;
    	Tk_ChangeWindowAttributes((Tk_Window) winPtr, CWOverrideRedirect, &atts);
    	ApplyMasterOverrideChanges(winPtr, NULL);
    }
}
 
/*
................................................................................
 */

MODULE_SCOPE void
TkpDisplayWindow(Tk_Window tkwin) {
    if (![NSApp isDrawing]) {
    	TkWindow *winPtr = (TkWindow*)tkwin;
    	NSWindow *w = TkMacOSXDrawableWindow(winPtr->window);

    	[[w contentView] setNeedsDisplay: YES];
    }
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
				 * didn't originally belong to topLevelPtr's
				 * application. */
{
    if (winPtr->atts.override_redirect) {
	return 0;
    }

    if (Tk_IsTopLevel(winPtr) && !Tk_IsEmbedded(winPtr) ){
    	NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);

    	TkWmRestackToplevel(winPtr, Above, NULL);
    	if (force ) {
    	    [NSApp activateIgnoringOtherApps:YES];
    	}
	if ( win && [win canBecomeKeyWindow] ) {
	    [win makeKeyAndOrderFront:NSApp];
	}
    }

    /*
     * Remember the current serial number for the X server and issue a dummy
     * server request. This marks the position at which we changed the focus,
................................................................................

void
TkMacOSXApplyWindowAttributes(
    TkWindow *winPtr,
    NSWindow *macWindow)
{
    WmInfo *wmPtr = winPtr->wmInfoPtr;

    ApplyWindowAttributeFlagChanges(winPtr, macWindow, 0, 0, 0, 1);
    if (wmPtr->master != NULL || winPtr->atts.override_redirect) {
	ApplyMasterOverrideChanges(winPtr, macWindow);
    }
}
 
/*
................................................................................
    UInt64 newAttributes = ForceAttributes(wmPtr->attributes, wmPtr->macClass);
    UInt64 changedAttributes = newAttributes ^ ForceAttributes(oldAttributes,
	    wmPtr->macClass);

    if (changedAttributes || wmPtr->flags != oldFlags || initial) {
	if (!macWindow) {
	    if (winPtr->window == None) {
		if (create) {
		    Tk_MakeWindowExist((Tk_Window) winPtr);
		} else {
		    return;
		}

	    }
	    if (!TkMacOSXHostToplevelExists(winPtr)) {
		if (create) {
		    TkMacOSXMakeRealWindowExist(winPtr);
		} else {
		    return;
		}

	    }
	    macWindow = TkMacOSXDrawableWindow(winPtr->window);
	}
	if ((changedAttributes & kWindowCloseBoxAttribute) || initial) {
	    [[macWindow standardWindowButton:NSWindowCloseButton]
		    setEnabled:!!(newAttributes & kWindowCloseBoxAttribute)];
	}
................................................................................
	}
	if ((changedAttributes & kWindowToolbarButtonAttribute) || initial) {
	    [macWindow setShowsToolbarButton:
		    !!(newAttributes & kWindowToolbarButtonAttribute)];
	    if ((newAttributes & kWindowToolbarButtonAttribute) &&
		    ![macWindow toolbar]) {
		NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@""];

		[toolbar setVisible:NO];
		[macWindow setToolbar:toolbar];
		[toolbar release];
		NSCell *toolbarButtonCell = [[macWindow standardWindowButton:
			NSWindowToolbarButton] cell];
		[toolbarButtonCell setTarget:[macWindow contentView]];
		[toolbarButtonCell setAction:@selector(tkToolbarButton:)];
................................................................................
	     * full screen, was included in the default as of OSX 10.13.  For
	     * uniformity we use the new default in all versions of the OS
	     * after 10.10.
	     */

#if !(MAC_OS_X_VERSION_MAX_ALLOWED < 101000)
	    if (!(macWindow.styleMask & NSUtilityWindowMask)) {

		/*
		 * Exclude overrideredirect, transient, and "help"-styled
		 * windows from moving into their own fullscreen space.
		 *
		 */

		if ((winPtr->atts.override_redirect) ||
		    (wmPtr->master != NULL) ||
		    (winPtr->wmInfoPtr->macClass == kHelpWindowClass)) {
		    b |= (NSWindowCollectionBehaviorCanJoinAllSpaces |
			  NSWindowCollectionBehaviorFullScreenAuxiliary);
		} else {
		    NSSize screenSize = [[macWindow screen]frame].size;
		    b |= NSWindowCollectionBehaviorFullScreenPrimary;


		    /* The default max size has height less than the screen height.
		     * This causes the window manager to refuse to allow the window
		     * to be resized when it is a split window.  To work around
		     * this we make the max size equal to the screen size.

		     */

		    [macWindow setMaxFullScreenContentSize:screenSize];
		}
	    }
#endif

................................................................................

	/*
	 * The change of window class/attributes might have changed the window
	 * frame geometry:
	 */

	NSRect structureRect = [macWindow frameRectForContentRect:NSZeroRect];

	wmPtr->xInParent = -structureRect.origin.x;
	wmPtr->yInParent = structureRect.origin.y + structureRect.size.height;
	wmPtr->parentWidth = winPtr->changes.width + structureRect.size.width;
	wmPtr->parentHeight = winPtr->changes.height + structureRect.size.height;
    }
}
 
................................................................................
	    if (wmPtr->master != NULL) {
		wmPtr->flags |= WM_TOPMOST;
	    } else {
		wmPtr->flags &= ~WM_TOPMOST;
	    }
	} else {
	    const char *title = winPtr->wmInfoPtr->titleUid;

	    if (!title) {
		title = winPtr->nameUid;
	    }
	    [macWindow setStyleMask:styleMask];
	    [macWindow setTitle:[NSString stringWithUTF8String:title]];
	    [macWindow setExcludedFromWindowsMenu:NO];
	    wmPtr->flags &= ~WM_TOPMOST;
	}
	if (wmPtr->master != None) {
	    TkWindow *masterWinPtr = (TkWindow *)wmPtr->master;

	    if (masterWinPtr && masterWinPtr->window != None &&
		    TkMacOSXHostToplevelExists(masterWinPtr)) {
		NSWindow *masterMacWin = TkMacOSXDrawableWindow(
					     masterWinPtr->window);

		/*
		 * Try to add the transient window as a child window of the
		 * master. A child NSWindow retains its relative position with
		 * respect to the parent when the parent is moved.  This is
		 * pointless if the parent is offscreen, and adding a child to
		 * an offscreen window causes the parent to be displayed as a
		 * zombie.  So we only do this if the parent is visible.
		 */

		if (masterMacWin &&
		    [masterMacWin isVisible] &&
		    (winPtr->flags & TK_MAPPED)) {

		    /*
		     * If the transient is already a child of some other window,
		     * remove it.
		     */

		    parentWindow = [macWindow parentWindow];
		    if (parentWindow && parentWindow != masterMacWin) {
			[parentWindow removeChildWindow:macWindow];
		    }

		    [masterMacWin addChildWindow:macWindow
					     ordered:NSWindowAbove];
		    }
	    }
	} else {
	    parentWindow = [macWindow parentWindow];
	    if (parentWindow) {
		[parentWindow removeChildWindow:macWindow];
	    }
	}
................................................................................
	macWin->toplevel->referenceCount++;
	winPtr->flags &= ~TK_MAPPED;
#ifdef TK_REBUILD_TOPLEVEL
	winPtr->flags |= TK_REBUILD_TOPLEVEL;
#endif
    }


    /* Repeat for all the children */


    for (childPtr = winPtr->childList; childPtr != NULL;
	    childPtr = childPtr->nextPtr) {
	RemapWindows(childPtr, (MacDrawable *) winPtr->window);
    }
}
 
/*







<







 







>

>







 







<







 







>
|







|







 







|

|
>








>













|

>







 







>





|
|
|
|







 







|







 







|


|
>

|
|







 







|

|

|







 







>
|
>
>









>
|
|
>
>



|



>
|
>
>











|
>







 







<






|







 







|







 







|









|












|







 







|
|




|










|
|






|
|










|
|









|
|
|


|
|
|

|
|
|
|
|


|







 







|

|
>

|







 







|
|
|
|
|
|
|
<







 







>

|
|








|
|

>


|
|
|




<
>
>
|
|
|
<
|
>



|
|

>







 







|
|







 







<







 







<







 







>
|




|
>







 







|
>
|












<







 







|
>
>
>
>







 







|
|
>
|
>








|
|
|




<







 







>

>
>
>











|







 







|
|







 







|
|







 







|
|








|









>







 







>







 







|

>

|


|







 







>







 







|
<
<


>


|
<
<


>







 







>







 







<



<



|
|

|

|


>
|
|
|
|
>







 







>







 







>









|
>
|
|

|










<
|
|
<











|
|







 







>
|
>
>







52
53
54
55
56
57
58

59
60
61
62
63
64
65
...
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
...
495
496
497
498
499
500
501

502
503
504
505
506
507
508
...
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
...
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
...
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
....
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
....
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
....
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
....
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
....
2721
2722
2723
2724
2725
2726
2727

2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
....
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
....
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
....
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
....
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
....
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899

3900
3901
3902
3903
3904
3905
3906
....
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988

4989
4990
4991
4992
4993

4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
....
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
....
5436
5437
5438
5439
5440
5441
5442

5443
5444
5445
5446
5447
5448
5449
....
5529
5530
5531
5532
5533
5534
5535

5536
5537
5538
5539
5540
5541
5542
....
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
....
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801

5802
5803
5804
5805
5806
5807
5808
....
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
....
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878

5879
5880
5881
5882
5883
5884
5885
....
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
....
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
....
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
....
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
....
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
....
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
....
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
....
6750
6751
6752
6753
6754
6755
6756
6757


6758
6759
6760
6761
6762
6763


6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
....
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
....
6840
6841
6842
6843
6844
6845
6846

6847
6848
6849

6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
....
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
....
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024

7025
7026

7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
....
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
	| kWindowHideOnFullScreenAttribute  | kWindowNoConstrainAttribute \
	| kWindowNoShadowAttribute	    | kWindowLiveResizeAttribute \
	| kWindowOpaqueForEventsAttribute   | kWindowIgnoreClicksAttribute \
	| kWindowDoesNotCycleAttribute	    | tkWindowDoesNotHideAttribute \
	| tkCanJoinAllSpacesAttribute	    | tkMoveToActiveSpaceAttribute \
	| tkNonactivatingPanelAttribute	    | tkHUDWindowAttribute)


static const struct {
    const UInt64 validAttrs, defaultAttrs, forceOnAttrs, forceOffAttrs;
    int flags; NSUInteger styleMask;
} macClassAttrs[] = {
    [kAlertWindowClass] = {
	.defaultAttrs = kWindowDoesNotCycleAttribute, },
    [kMovableAlertWindowClass] = {
................................................................................

	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;
	wmPtr->yInParent = frameRect.origin.y + frameRect.size.height;
	wmPtr->parentWidth = winPtr->changes.width + frameRect.size.width;
	wmPtr->parentHeight = winPtr->changes.height + frameRect.size.height;
    }
}

................................................................................
    }
    if (DEBUG_ZOMBIES > 0){
	fprintf(stderr, ">>>> Freeing <%s>. Count is %lu\n",
		title, [self retainCount]);
    }
    [super dealloc];
}


#endif
@end

#pragma mark -
 
/*
................................................................................

    for (NSWindow *w in windows) {
	winPtr = TkMacOSXGetTkWindow(w);
	if (winPtr) {
	    WmInfo *wmPtr = winPtr->wmInfoPtr;
	    NSRect windowFrame = [w frame];
	    NSRect contentFrame = [w frame];

	    contentFrame.size.height = [[w contentView] frame].size.height;
	    /*
	     * For consistency with other platforms, points in the
	     * title bar are not considered to be contained in the
	     * window.
	     */

	    if ((wmPtr->hints.initial_state == NormalState ||
		    wmPtr->hints.initial_state == ZoomState)) {
		if (NSMouseInRect(p, contentFrame, NO)) {
		    return winPtr;
		} else if (NSMouseInRect(p, windowFrame, NO)) {
		    return NULL;
		}
	    }
	}
................................................................................

    /*
     * If the dead window has a transient, remove references to it from
     * the transient.
     */

    for (Transient *transientPtr = wmPtr->transientPtr;
	    transientPtr != NULL; transientPtr = transientPtr->nextPtr) {
    	TkWindow *winPtr2 = transientPtr->winPtr;
    	TkWindow *masterPtr = (TkWindow *) TkGetTransientMaster(winPtr2);

    	if (masterPtr == winPtr) {
    	    wmPtr2 = winPtr2->wmInfoPtr;
    	    wmPtr2->master = NULL;
    	}
    }

    while (wmPtr->transientPtr != NULL) {
	Transient *transientPtr = wmPtr->transientPtr;

	wmPtr->transientPtr = transientPtr->nextPtr;
	ckfree(transientPtr);
    }

    /*
     * Delete the Mac window and remove it from the windowTable. The window
     * could be nil if the window was never mapped. However, we don't do this
     * for embedded windows, they don't go in the window list, and they do not
     * own their portPtr's.
     */

    NSWindow *window = wmPtr->window;

    if (window && !Tk_IsEmbedded(winPtr)) {
	NSWindow *parent = [window parentWindow];

	if (parent) {
	    [parent removeChildWindow:window];
	}
#if DEBUG_ZOMBIES > 0
	{
	    const char *title = [[window title] UTF8String];
	    if (title == nil) {
................................................................................
	wmPtr->window = NULL;
        [window release];

	/* 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;
		}
	    }
	}
................................................................................
	for (attribute = 0; attribute < _WMATT_LAST_ATTRIBUTE; ++attribute) {
	    Tcl_ListObjAppendElement(NULL, result,
		    Tcl_NewStringObj(WmAttributeNames[attribute], -1));
	    Tcl_ListObjAppendElement(NULL, result,
		    WmGetAttribute(winPtr, macWindow, attribute));
	}
	Tcl_SetObjResult(interp, result);
    } else if (objc == 4) {	/* wm attributes $win -attribute */
	if (Tcl_GetIndexFromObjStruct(interp, objv[3], WmAttributeNames,
		sizeof(char *), "attribute", 0, &attribute) != TCL_OK) {
	    return TCL_ERROR;
	}
	Tcl_SetObjResult(interp, WmGetAttribute(winPtr, macWindow, attribute));
    } else if ((objc - 3) % 2 == 0) {	/* wm attributes $win -att value... */
	int i;
................................................................................

    /*
     * If this window has a transient, the transient must also be deiconified if
     * it was withdrawn by the master.
     */

    for (Transient *transientPtr = wmPtr->transientPtr;
	    transientPtr != NULL; transientPtr = transientPtr->nextPtr) {
	TkWindow *winPtr2 = transientPtr->winPtr;
	WmInfo *wmPtr2 = winPtr2->wmInfoPtr;
	TkWindow *masterPtr = (TkWindow *) TkGetTransientMaster(winPtr2);

    	if (masterPtr == winPtr) {
	    if ((wmPtr2->hints.initial_state == WithdrawnState) &&
		    ((transientPtr->flags & WITHDRAWN_BY_MASTER) != 0)) {
		TkpWmSetState(winPtr2, NormalState);
		transientPtr->flags &= ~WITHDRAWN_BY_MASTER;
	    }
	}
    }

    return TCL_OK;
................................................................................

    /*
     * If this window has a transient the transient must be withdrawn when
     * the master is iconified.
     */

    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;
}
................................................................................

    if (objc < 4) {
	Tcl_WrongNumArgs(interp, 2, objv,
			 "window ?-default? image1 ?image2 ...?");
	return TCL_ERROR;
    }

    /*
     * Parse args.
     */

    if (strcmp(Tcl_GetString(objv[3]), "-default") == 0) {
	isDefault = 1;
	if (objc == 4) {
	    Tcl_WrongNumArgs(interp, 2, objv,
			     "window ?-default? image1 ?image2 ...?");
	    return TCL_ERROR;
	}
    }

    /*
     * Get icon name. We only use the first icon name because macOS does not
     * support multiple images in Tk photos.
     */

    char *icon;
    if (strcmp(Tcl_GetString(objv[3]), "-default") == 0) {
	icon = Tcl_GetString(objv[4]);
    } else {
	icon = Tcl_GetString(objv[3]);
    }

    /*
     * Get image and convert to NSImage that can be displayed as icon.
     */

    tk_icon = Tk_GetImage(interp, tkwin, icon, NULL, NULL);
    if (tk_icon == NULL) {
    	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
	      "can't use \"%s\" as iconphoto: not a photo image",
	      icon));
	Tcl_SetErrorCode(interp, "TK", "WM", "ICONPHOTO", "PHOTO", NULL);
	return TCL_ERROR;
    }

    NSImage *newIcon;
    Tk_SizeOfImage(tk_icon, &width, &height);
    newIcon = TkMacOSXGetNSImageWithTkImage(winPtr->display, tk_icon,
	    width, height);
    Tk_FreeImage(tk_icon);
    if (newIcon == NULL) {
	return TCL_ERROR;
    }
    [NSApp setApplicationIconImage: newIcon];
    return TCL_OK;
}
................................................................................
	}
	Tk_MakeWindowExist(tkwin2);
	wmPtr->hints.icon_window = Tk_WindowId(tkwin2);
	wmPtr->hints.flags |= IconWindowHint;
	wmPtr->icon = tkwin2;
	wmPtr2->iconFor = (Tk_Window) winPtr;
	if (!(wmPtr2->flags & WM_NEVER_MAPPED)) {

	    /*
	     * If the window is in normal or zoomed state, the icon should be
	     * unmapped.
	     */

	    if (wmPtr->hints.initial_state == NormalState ||
		    wmPtr->hints.initial_state == ZoomState) {
		Tk_UnmapWindow(tkwin2);
	    }
	}
    }
    return TCL_OK;
}
 
................................................................................

    /*
     * Delete any current protocol handler, then create a new one with the
     * specified command, unless the command is empty.
     */

    for (protPtr = wmPtr->protPtr, prevPtr = NULL; protPtr != NULL;
	    prevPtr = protPtr, protPtr = protPtr->nextPtr) {
	if (protPtr->protocol == protocol) {
	    if (prevPtr == NULL) {
		wmPtr->protPtr = protPtr->nextPtr;
	    } else {
		prevPtr->nextPtr = protPtr->nextPtr;
	    }
	    if (protPtr->command)
................................................................................
		    "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;
	}

	for (w = masterPtr; w != NULL && w->wmInfoPtr != NULL;
		w = (TkWindow *)w->wmInfoPtr->master) {
	    if (w == winPtr) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "setting \"%s\" as master creates a transient/master cycle",
		    Tk_PathName(masterPtr)));
		Tcl_SetErrorCode(interp, "TK", "WM", "TRANSIENT", "SELF", NULL);
		return TCL_ERROR;
	    }
	}

	/*
	 * Add the transient to the master's list, if it not already there.
	 */

	for (transient = wmPtr2->transientPtr;
	     transient != NULL && transient->winPtr != winPtr;
	     transient = transient->nextPtr) {}
	if (transient == NULL) {
	    transient = ckalloc(sizeof(Transient));
	    transient->winPtr = winPtr;
	    transient->flags = 0;
................................................................................
	}

	/*
	 * If the master is withdrawn or iconic then withdraw the transient.
	 */

	if ((wmPtr2->hints.initial_state == WithdrawnState ||
		wmPtr2->hints.initial_state == IconicState) &&
		wmPtr->hints.initial_state != WithdrawnState) {
	    TkpWmSetState(winPtr, WithdrawnState);
	    transient->flags |= WITHDRAWN_BY_MASTER;
	}

	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.
 *
 * Results:
 *	None
 *
 * Side effects:
 *      References to a master are removed from the transient's wmInfo
 *	structure and references to the transient are removed from its master's
 *	wmInfo.
 *
 *----------------------------------------------------------------------
 */

static void
RemoveTransient(
    TkWindow *winPtr)
{
    WmInfo *wmPtr = winPtr->wmInfoPtr, *wmPtr2;
    TkWindow *masterPtr;
    Transient *transPtr, *temp;

    if (wmPtr == NULL || wmPtr->master == NULL) {
	return;
    }
    masterPtr = (TkWindow*)wmPtr->master;
    wmPtr2 = masterPtr->wmInfoPtr;
    if (wmPtr2 == NULL) {
	return;
    }
    wmPtr->master = NULL;
    transPtr = wmPtr2->transientPtr;
    while (transPtr != NULL) {
	if (transPtr->winPtr != winPtr) {
	    break;
	}
	temp = transPtr->nextPtr;
	ckfree(transPtr);
	transPtr = temp;
    }
    wmPtr2->transientPtr = transPtr;
    while (transPtr != NULL) {
	if (transPtr->nextPtr && transPtr->nextPtr->winPtr == winPtr) {
	    temp = transPtr->nextPtr;
	    transPtr->nextPtr = temp->nextPtr;
	    ckfree(temp);
	} else {
	    transPtr = transPtr->nextPtr;
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
    [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;
}
................................................................................
	    && ((wmPtr->sizeHintsFlags & (PBaseSize|PResizeInc))
		    == (PBaseSize|PResizeInc))) {
	return;
    }

    /*
     * If gridding was previously off, then forget about any window size
     * requests made by the user or via "wm geometry": these are in pixel units
     * and there's no easy way to translate them to grid units since the new
     * requested size of the top-level window in pixels may not yet have been
     * registered yet (it may filter up the hierarchy in DoWhenIdle handlers).
     * However, if the window has never been mapped yet then just leave the
     * window size alone: assume that it is intended to be in grid units but
     * just happened to have been specified before this procedure was called.

     */

    if ((wmPtr->gridWin == NULL) && !(wmPtr->flags & WM_NEVER_MAPPED)) {
	wmPtr->width = -1;
	wmPtr->height = -1;
    }

................................................................................
    WmInfo *wmPtr = winPtr->wmInfoPtr;
    int macAboveBelow = (aboveBelow == Above ? NSWindowAbove : NSWindowBelow);
    int otherNumber = 0; /* 0 will be used when otherPtr is NULL. */

    /*
     * If the Tk windows has no drawable, or is withdrawn do nothing.
     */

    if (winPtr->window == None ||
	    wmPtr == NULL      ||
	    wmPtr->hints.initial_state == WithdrawnState) {
	return;
    }
    macWindow = TkMacOSXDrawableWindow(winPtr->window);
    if (macWindow == nil) {
	return;
    }
    if (otherPtr) {
	/*
	 * When otherPtr is non-NULL, if the other window has no drawable or is
	 * withdrawn, do nothing.
	 */

	WmInfo *otherWmPtr = otherPtr->wmInfoPtr;
	if (winPtr->window == None ||
		otherWmPtr == NULL ||
		otherWmPtr->hints.initial_state == WithdrawnState) {
	    return;
	}
	otherMacWindow = TkMacOSXDrawableWindow(otherPtr->window);
	if (otherMacWindow == nil) {
	    return;

	}

	/*
	 * If the other window is OK, get its number.
	 */


	otherNumber = [otherMacWindow windowNumber];
    }

    /*
     * Just let the Mac window manager deal with all the subtleties of keeping
     * track of off-screen windows, etc.
     */

    [macWindow orderWindow:macAboveBelow relativeTo:otherNumber];
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkWmAddToColormapWindows --
................................................................................
/*
 *----------------------------------------------------------------------
 *
 * InitialWindowBounds --
 *
 *	This function calculates the initial bounds for a new Mac toplevel
 *	window. Unless the geometry is specified by the user this code will
 *	auto place the windows in a cascade diagonially across the main monitor
 *	of the Mac.
 *
 * Results:
 *	Window bounds.
 *
 * Side effects:
 *	None.
 *
................................................................................
MODULE_SCOPE int
TkMacOSXIsWindowZoomed(
    TkWindow *winPtr)
{
    NSWindow *macWindow = TkMacOSXDrawableWindow(winPtr->window);
    return [macWindow isZoomed];
}

 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXZoomToplevel --
 *
 *	The function is invoked when the user clicks in the zoom region of a
................................................................................
    int index;

    if (objc < 3) {
	Tcl_WrongNumArgs(interp, 1, objv, "option window ?arg ...?");
	return TCL_ERROR;
    }


    winPtr = (TkWindow *)
	    Tk_NameToWindow(interp, Tcl_GetString(objv[2]), tkwin);
    if (winPtr == NULL) {
	return TCL_ERROR;
    }
    if (!(winPtr->flags & TK_TOP_LEVEL)) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
................................................................................
	if ([NSApp macMinorVersion] < 9) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
                "Window appearances did not exist until OSX 10.9.", -1));
	    Tcl_SetErrorCode(interp, "TK", "WINDOWSTYLE", "APPEARANCE", NULL);
	    return TCL_ERROR;
	}
	if ((objc < 3) || (objc > 4)) {
	    Tcl_WrongNumArgs(interp, 2, objv,
		    "appearance window ?appearancename?");
	    return TCL_ERROR;
	}
	if (objc == 4 && [NSApp macMinorVersion] < 14) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "Window appearances cannot be changed before OSX 10.14.",
		    -1));
	    Tcl_SetErrorCode(interp, "TK", "WINDOWSTYLE", "APPEARANCE", NULL);
	    return TCL_ERROR;
	}
	return WmWinAppearance(interp, winPtr, objc, objv);
    default:
	return TCL_ERROR;
    }
................................................................................
 *----------------------------------------------------------------------
 *
 * WmWinTabbingId --
 *
 *	This procedure is invoked to process the
 *	"::tk::unsupported::MacWindowStyle tabbingid" subcommand. The command
 *	allows you to get or set the tabbingIdentifier for the NSWindow
 *	associated with a Tk Window.  The syntax is:
 *
 *	    tk::unsupported::MacWindowStyle tabbingid window ?newId?
 *
 * Results:
 *	Returns the tabbingIdentifier of the window prior to calling this
 *      function.  If the optional newId argument is omitted, the window's
 *      tabbingIdentifier is not changed.
 *
 * Side effects:
 *	Windows may only be grouped together as tabs if they all have the same
 *      tabbingIdentifier.  In particular, by giving a window a unique
 *      tabbingIdentifier one can prevent it from becoming a tab in any other
 *      window.  Note, however, that changing the tabbingIdentifier of a window
 *      which is already a tab does not cause it to become a separate window.

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

static int
WmWinTabbingId(
    Tcl_Interp *interp,		/* Current interpreter. */
................................................................................

	/*
	 * If the tabbingIdentifier of a tab is changed we also turn it into a
	 * separate window so we don't violate the rule that all tabs in the
	 * same frame must have the same tabbingIdentifier.
	 */

	if ([idString compare:newIdString] != NSOrderedSame
#if MAC_OS_X_VERSION_MIN_REQUIRED > 101200
		&& [win tab]
#endif
		) {
	    [win moveTabToNewWindow:nil];
	}
	return TCL_OK;
    }
#endif
    return TCL_ERROR;
}
................................................................................
/*
 *----------------------------------------------------------------------
 *
 * WmWinAppearance --
 *
 *	This procedure is invoked to process the
 *	"::tk::unsupported::MacWindowStyle appearance" subcommand. The command
 *	allows you to get or set the appearance for the NSWindow associated
 *	with a Tk Window.  The syntax is:
 *
 *	    tk::unsupported::MacWindowStyle tabbingid window ?newAppearance?
 *
 *      Allowed appearance names are "aqua", "darkaqua", and "auto".
 *
 * Results:
 *      Returns the appearance setting of the window prior to calling this
 *	function.
 *
 * Side effects:
 *      The underlying NSWindow's appearance property is set to the specified
 *      value if the optional newAppearance argument is supplied. Otherwise the
 *      window's appearance property is not changed.  If the appearance is set
 *      to aqua or darkaqua then the window will use the associated
 *      NSAppearance even if the user has selected a different appearance with
 *      the system preferences.  If it is set to auto then the appearance
 *      property is set to nil, meaning that the preferences will determine the
 *      appearance.

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

static int
WmWinAppearance(
    Tcl_Interp *interp,		/* Current interpreter. */
................................................................................
    static const char *const appearanceStrings[] = {
	"aqua", "darkaqua", "auto", NULL
    };
    enum appearances {
	APPEARANCE_AQUA, APPEARANCE_DARKAQUA, APPEARANCE_AUTO
    };
    Tcl_Obj *result = NULL;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
    NSAppearanceName appearance;
#else
    NSString *appearance;
#endif
    const char *resultString;
    NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);
    if (win) {
	appearance = win.appearance.name;
	if (appearance == nil) {
	    resultString = appearanceStrings[APPEARANCE_AUTO];
	} else if (appearance == NSAppearanceNameAqua) {
	    resultString = appearanceStrings[APPEARANCE_AQUA];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400
	} else if (appearance == NSAppearanceNameDarkAqua) {
	    resultString = appearanceStrings[APPEARANCE_DARKAQUA];
#endif
	} else {
	    resultString = "unrecognized";
	}
	result = Tcl_NewStringObj(resultString, strlen(resultString));
    }
    if (result == NULL) {
	Tcl_Panic("Failed to read appearance name.");
................................................................................
    if (TkMacOSXHostToplevelExists(winPtr)) {
	return;
    }

    macWin = (MacDrawable *) winPtr->window;

    /*
     * If this is embedded, make sure its container's toplevel exists, then
     * return...
     */

    if (Tk_IsEmbedded(winPtr)) {
	TkWindow *contWinPtr = TkpGetOtherWindow(winPtr);

	if (contWinPtr != NULL) {
	    TkMacOSXMakeRealWindowExist(
................................................................................

	/*
	 * TODO: Here we should handle out of process embedding.
	 */
    }

    /*
     * If this is an override-redirect window, the NSWindow is created first as
     * a document window then converted to a simple window.
     */

    if (overrideRedirect) {
	wmPtr->macClass = kDocumentWindowClass;
    }
    macClass = wmPtr->macClass;
    wmPtr->attributes &= (tkAlwaysValidAttributes |
................................................................................
    [window setReleasedWhenClosed:NO];
    if (styleMask & NSUtilityWindowMask) {
	[(NSPanel*)window setFloatingPanel:YES];
    }
    if ((styleMask & (NSTexturedBackgroundWindowMask|NSHUDWindowMask)) &&
	    !(styleMask & NSDocModalWindowMask)) {
        /*
	 * Workaround for [Bug 2824538]: Textured windows are draggable from
	 *                               opaque content.
	 */
	[window setMovableByWindowBackground:NO];
    }
    [window setDocumentEdited:NO];
    wmPtr->window = window;
    macWin->view = window.contentView;
    TkMacOSXApplyWindowAttributes(winPtr, window);
    NSRect geometry = InitialWindowBounds(winPtr, window);
    geometry.size.width += structureRect.size.width;
    geometry.size.height += structureRect.size.height;
    geometry.origin.y = tkMacOSXZeroScreenHeight - (geometry.origin.y +
	    geometry.size.height);
    [window setFrame:geometry display:YES];
    TkMacOSXRegisterOffScreenWindow((Window) macWin, window);

    macWin->flags |= TK_HOST_EXISTS;
    if (overrideRedirect) {
    	XSetWindowAttributes atts;

    	atts.override_redirect = True;
    	Tk_ChangeWindowAttributes((Tk_Window) winPtr, CWOverrideRedirect, &atts);
    	ApplyMasterOverrideChanges(winPtr, NULL);
    }
}
 
/*
................................................................................
 */

MODULE_SCOPE void
TkpDisplayWindow(Tk_Window tkwin) {
    if (![NSApp isDrawing]) {
    	TkWindow *winPtr = (TkWindow*)tkwin;
    	NSWindow *w = TkMacOSXDrawableWindow(winPtr->window);

    	[[w contentView] setNeedsDisplay: YES];
    }
}
 
/*
 *----------------------------------------------------------------------
 *
................................................................................
				 * didn't originally belong to topLevelPtr's
				 * application. */
{
    if (winPtr->atts.override_redirect) {
	return 0;
    }

    if (Tk_IsTopLevel(winPtr) && !Tk_IsEmbedded(winPtr)) {
    	NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);

    	TkWmRestackToplevel(winPtr, Above, NULL);
    	if (force) {
    	    [NSApp activateIgnoringOtherApps:YES];
    	}
	if (win && [win canBecomeKeyWindow]) {
	    [win makeKeyAndOrderFront:NSApp];
	}
    }

    /*
     * Remember the current serial number for the X server and issue a dummy
     * server request. This marks the position at which we changed the focus,
................................................................................

void
TkMacOSXApplyWindowAttributes(
    TkWindow *winPtr,
    NSWindow *macWindow)
{
    WmInfo *wmPtr = winPtr->wmInfoPtr;

    ApplyWindowAttributeFlagChanges(winPtr, macWindow, 0, 0, 0, 1);
    if (wmPtr->master != NULL || winPtr->atts.override_redirect) {
	ApplyMasterOverrideChanges(winPtr, macWindow);
    }
}
 
/*
................................................................................
    UInt64 newAttributes = ForceAttributes(wmPtr->attributes, wmPtr->macClass);
    UInt64 changedAttributes = newAttributes ^ ForceAttributes(oldAttributes,
	    wmPtr->macClass);

    if (changedAttributes || wmPtr->flags != oldFlags || initial) {
	if (!macWindow) {
	    if (winPtr->window == None) {
		if (!create) {


		    return;
		}
		Tk_MakeWindowExist((Tk_Window) winPtr);
	    }
	    if (!TkMacOSXHostToplevelExists(winPtr)) {
		if (!create) {


		    return;
		}
		TkMacOSXMakeRealWindowExist(winPtr);
	    }
	    macWindow = TkMacOSXDrawableWindow(winPtr->window);
	}
	if ((changedAttributes & kWindowCloseBoxAttribute) || initial) {
	    [[macWindow standardWindowButton:NSWindowCloseButton]
		    setEnabled:!!(newAttributes & kWindowCloseBoxAttribute)];
	}
................................................................................
	}
	if ((changedAttributes & kWindowToolbarButtonAttribute) || initial) {
	    [macWindow setShowsToolbarButton:
		    !!(newAttributes & kWindowToolbarButtonAttribute)];
	    if ((newAttributes & kWindowToolbarButtonAttribute) &&
		    ![macWindow toolbar]) {
		NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@""];

		[toolbar setVisible:NO];
		[macWindow setToolbar:toolbar];
		[toolbar release];
		NSCell *toolbarButtonCell = [[macWindow standardWindowButton:
			NSWindowToolbarButton] cell];
		[toolbarButtonCell setTarget:[macWindow contentView]];
		[toolbarButtonCell setAction:@selector(tkToolbarButton:)];
................................................................................
	     * full screen, was included in the default as of OSX 10.13.  For
	     * uniformity we use the new default in all versions of the OS
	     * after 10.10.
	     */

#if !(MAC_OS_X_VERSION_MAX_ALLOWED < 101000)
	    if (!(macWindow.styleMask & NSUtilityWindowMask)) {

		/*
		 * Exclude overrideredirect, transient, and "help"-styled
		 * windows from moving into their own fullscreen space.

		 */

		if ((winPtr->atts.override_redirect) ||
			(wmPtr->master != NULL) ||
			(winPtr->wmInfoPtr->macClass == kHelpWindowClass)) {
		    b |= (NSWindowCollectionBehaviorCanJoinAllSpaces |
			    NSWindowCollectionBehaviorFullScreenAuxiliary);
		} else {
		    NSSize screenSize = [[macWindow screen] frame].size;
		    b |= NSWindowCollectionBehaviorFullScreenPrimary;

		    /*
		     * The default max size has height less than the screen
		     * height. This causes the window manager to refuse to
		     * allow the window to be resized when it is a split
		     * window. To work around this we make the max size equal
		     * to the screen size.
		     */

		    [macWindow setMaxFullScreenContentSize:screenSize];
		}
	    }
#endif

................................................................................

	/*
	 * The change of window class/attributes might have changed the window
	 * frame geometry:
	 */

	NSRect structureRect = [macWindow frameRectForContentRect:NSZeroRect];

	wmPtr->xInParent = -structureRect.origin.x;
	wmPtr->yInParent = structureRect.origin.y + structureRect.size.height;
	wmPtr->parentWidth = winPtr->changes.width + structureRect.size.width;
	wmPtr->parentHeight = winPtr->changes.height + structureRect.size.height;
    }
}
 
................................................................................
	    if (wmPtr->master != NULL) {
		wmPtr->flags |= WM_TOPMOST;
	    } else {
		wmPtr->flags &= ~WM_TOPMOST;
	    }
	} else {
	    const char *title = winPtr->wmInfoPtr->titleUid;

	    if (!title) {
		title = winPtr->nameUid;
	    }
	    [macWindow setStyleMask:styleMask];
	    [macWindow setTitle:[NSString stringWithUTF8String:title]];
	    [macWindow setExcludedFromWindowsMenu:NO];
	    wmPtr->flags &= ~WM_TOPMOST;
	}
	if (wmPtr->master != None) {
	    TkWindow *masterWinPtr = (TkWindow *) wmPtr->master;

	    if (masterWinPtr && (masterWinPtr->window != None)
		    && TkMacOSXHostToplevelExists(masterWinPtr)) {
		NSWindow *masterMacWin = TkMacOSXDrawableWindow(
			masterWinPtr->window);

		/*
		 * Try to add the transient window as a child window of the
		 * master. A child NSWindow retains its relative position with
		 * respect to the parent when the parent is moved.  This is
		 * pointless if the parent is offscreen, and adding a child to
		 * an offscreen window causes the parent to be displayed as a
		 * zombie.  So we only do this if the parent is visible.
		 */


		if (masterMacWin && [masterMacWin isVisible]
			&& (winPtr->flags & TK_MAPPED)) {

		    /*
		     * If the transient is already a child of some other window,
		     * remove it.
		     */

		    parentWindow = [macWindow parentWindow];
		    if (parentWindow && parentWindow != masterMacWin) {
			[parentWindow removeChildWindow:macWindow];
		    }

		    [masterMacWin addChildWindow:macWindow
					 ordered:NSWindowAbove];
		}
	    }
	} else {
	    parentWindow = [macWindow parentWindow];
	    if (parentWindow) {
		[parentWindow removeChildWindow:macWindow];
	    }
	}
................................................................................
	macWin->toplevel->referenceCount++;
	winPtr->flags &= ~TK_MAPPED;
#ifdef TK_REBUILD_TOPLEVEL
	winPtr->flags |= TK_REBUILD_TOPLEVEL;
#endif
    }

    /*
     * Repeat for all the children.
     */

    for (childPtr = winPtr->childList; childPtr != NULL;
	    childPtr = childPtr->nextPtr) {
	RemapWindows(childPtr, (MacDrawable *) winPtr->window);
    }
}
 
/*

Changes to jni/sdl2tk/macosx/ttkMacOSXTheme.c.

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
...
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
...
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
...
184
185
186
187
188
189
190
191

192
193
194
195
196
197
198
...
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
...
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
...
323
324
325
326
327
328
329

330

331
332
333
334
335
336
337
...
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
...
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
...
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
...
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
...
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
...
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
...
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
...
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
...
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
...
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
...
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
...
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
...
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
...
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
...
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
...
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
...
929
930
931
932
933
934
935

936

937
938
939
940
941
942
943
...
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
....
1001
1002
1003
1004
1005
1006
1007

1008
1009
1010
1011
1012
1013
1014
....
1049
1050
1051
1052
1053
1054
1055
1056

1057
1058

1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
....
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
....
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
....
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
....
1182
1183
1184
1185
1186
1187
1188
1189

1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
....
1216
1217
1218
1219
1220
1221
1222
1223

1224
1225
1226
1227
1228
1229
1230
....
1288
1289
1290
1291
1292
1293
1294

1295
1296
1297
1298
1299
1300
1301
....
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
....
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
....
1500
1501
1502
1503
1504
1505
1506
1507
1508

1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
....
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
....
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
....
1665
1666
1667
1668
1669
1670
1671

1672
1673
1674


1675
1676
1677
1678
1679
1680
1681
....
1715
1716
1717
1718
1719
1720
1721

1722
1723
1724


1725
1726
1727
1728
1729
1730
1731
....
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
....
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
....
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
....
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
....
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
....
2282
2283
2284
2285
2286
2287
2288
2289

2290
2291
2292
2293
2294
2295
2296
....
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
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
2352
2353
2354
2355
2356
....
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
....
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
....
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
....
2547
2548
2549
2550
2551
2552
2553

2554
2555
2556


2557
2558
2559
2560
2561
2562
2563
....
2781
2782
2783
2784
2785
2786
2787
2788

2789
2790
2791
2792
2793
2794
2795
 *
 * <URL: http://developer.apple.com/documentation/Carbon/Reference/
 *	Appearance_Manager/appearance_manager/APIIndex.html >
 *
 * Notes:
 *	"Active" means different things in Mac and Tk terminology --
 *	On Aqua, widgets are "Active" if they belong to the foreground window,
 *	"Inactive" if they are in a background window.
 *	Tk uses the term "active" to mean that the mouse cursor
 *	is over a widget; aka "hover", "prelight", or "hot-tracked".
 *	Aqua doesn't use this kind of feedback.
 *
 *	The QuickDraw/Carbon coordinate system is relative to the
 *	top-level window, not to the Tk_Window.  BoxToRect()
 *	accounts for this.
 */

#include "tkMacOSXPrivate.h"
#include "ttk/ttkTheme.h"
#include <math.h>
/*
 * Macros for handling drawing contexts.
................................................................................
 * 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.size.height = height;
    }
    return bounds;
}

#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
/*----------------------------------------------------------------------
 * +++ Support for contrasting background colors when GroupBoxes
 * or Tabbed panes are nested inside each other.  Early versions
 * of macOS used ridged borders, so do not need contrasting backgrounds.
 */

/*
 * For systems older than 10.14, [NSColor windowBackGroundColor] generates
 * garbage when called from this function.  In 10.14 it works correctly,
 * and must be used in order to have a background color which responds
 * to Dark Mode.  So we use this hard-wired RGBA color on the older systems
 * which don't support Dark Mode anyway.
 */

static CGFloat windowBackground[4] = {235.0/255, 235.0/255, 235.0/255, 1.0};
static CGFloat whiteRGBA[4] = {1.0, 1.0, 1.0, 1.0};
static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0};

/*
 * 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) {
................................................................................
	} else {
	    for (int i = 0; i < 4; i++) {
		rgba[i] = windowBackground[i];
	    }
	}
    }
    if (contrast) {
	int isDark  = (rgba[0] + rgba[1] + rgba[2] < 1.5);

	if (isDark) {
	    for (int i=0; i<3; i++) {
		rgba[i] += 8.0/255.0;
	    }
	} else {
	    for (int i=0; i<3; i++) {
		rgba[i] -= 8.0/255.0;
................................................................................
	winPtr->privatePtr->flags |= TTK_HAS_CONTRASTING_BG;
	for (int i = 0; i < 4; i++) {
	    winPtr->privatePtr->fillRGBA[i] = rgba[i];
	}
    }
}

/*
 * DrawGroupBox --
 *
 *    This is a standalone drawing procedure which draws the contrasting
 *    rounded rectangular box for LabelFrames and Notebook panes.
 */

static void DrawGroupBox(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin)
{
................................................................................
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextReplacePathWithStrokedPath(context);
    CGContextFillPath(context);
    CFRelease(path);
}


/* SolidFillRoundedRectangle --
 *
 *     Fill a rounded rectangle with a specified solid color.
 */

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);
}



/* 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);
}


static void DrawUpDownArrows(
    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 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 --
 *
 *    This is a standalone drawing procedure which draws column
 *    headers for a Treeview in the Aqua appearance.  The HITheme
 *    headers have not matched the native ones since OSX 10.8.
 *    Note that the header image is ignored, but we draw arrows
 *    according to the state.
 */

static void DrawListHeader(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin,
    int state)
................................................................................
	    DrawDownArrow(context, arrowBounds, 3, 8, blackRGBA);
	}
    }
}

#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */

#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
/*----------------------------------------------------------------------
 * +++ Drawing procedures for widgets in Apple's "Dark Mode" (10.14 and up).
 *
 *    The HIToolbox does not support Dark Mode, and apparently never will,
 *    so to make widgets look "native" we have to provide analogues of the
 *    HITheme drawing functions to be used in DarkAqua.  We continue to use
 *    HITheme in Aqua, since it understands earlier versions of the OS.
 */

/*
 *  Colors and gradients used in Dark Mode.
 */

static CGFloat darkButtonFace[4] = {112.0/255, 113.0/255, 115.0/255, 1.0};
static CGFloat darkPressedBevelFace[4] = {135.0/255, 136.0/255, 138.0/255, 1.0};
static CGFloat darkSelectedBevelFace[4] = {162.0/255, 163.0/255, 165.0/255, 1.0};
static CGFloat darkDisabledButtonFace[4] = {86.0/255, 87.0/255, 89.0/255, 1.0};
static CGFloat darkInactiveSelectedTab[4] = {159.0/255, 160.0/255, 161.0/255, 1.0};
................................................................................
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};


/* FillButtonBackground --
 *
 *    Fills a rounded rectangle with a transparent black gradient.
 */

static void FillButtonBackground(
    CGContextRef context,
    CGRect bounds,
    CGFloat radius)
{
    CGPathRef path;
    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);
    CFRelease(backgroundGradient);
}


/* HighlightButtonBorder --
 *
 * Accent the top border of a rounded rectangle with a transparent
 * white gradient.
 */

static void HighlightButtonBorder(
    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);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, topGradient, bounds.origin, topEnd, 0.0);
    CGContextRestoreGState(context);
    CFRelease(topGradient);
}

/*
 * DrawDarkButton --
 *
 *    This is a standalone drawing procedure which draws PushButtons and
 *    PopupButtons in the Dark Mode style.
 */

static void DrawDarkButton(
    CGRect bounds,
    ThemeButtonKind kind,
    Ttk_State state,
    CGContextRef context)
................................................................................
    /*
     * Fill the button face with the appropriate color.
     */

    bounds = CGRectInset(bounds, 1, 1);
    if (kind == kThemePushButton && (state & TTK_STATE_PRESSED)) {
	GradientFillRoundedRectangle(context, bounds, 4,
				   darkSelectedGradient, 2);
    } else {
	if (state & TTK_STATE_DISABLED) {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
					  components: darkDisabledButtonFace
					       count: 4];
	} else {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
................................................................................
	    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)
................................................................................
				   darkSelectedGradient, 2);
	CGContextRestoreGState(context);
    }
    DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA);
    HighlightButtonBorder(context, bounds);
}

/*
 * DrawDarkBevelButton --
 *
 *    This is a standalone drawing procedure which draws
 *    RoundedBevelButtons in the Dark Mode style.
 */

static void DrawDarkBevelButton(
    CGRect bounds,
    Ttk_State state,
    CGContextRef context)
{
................................................................................

    bounds = CGRectInset(bounds, 1, 1);
    if (state & TTK_STATE_PRESSED) {
	faceColor = [NSColor colorWithColorSpace: deviceRGB
					  components: darkPressedBevelFace
					       count: 4];
    } else if ((state & TTK_STATE_DISABLED) ||
	       (state & TTK_STATE_ALTERNATE)){
	faceColor = [NSColor colorWithColorSpace: deviceRGB
				      components: darkDisabledButtonFace
					   count: 4];
    } else if (state & TTK_STATE_SELECTED) {
	faceColor = [NSColor colorWithColorSpace: deviceRGB
				      components: darkSelectedBevelFace
					   count: 4];
................................................................................
				      components: darkButtonFace
					   count: 4];
    }
    SolidFillRoundedRectangle(context, bounds, 4, faceColor);
    HighlightButtonBorder(context, bounds);
}

/*
 * DrawDarkCheckBox --
 *
 *    This is a standalone drawing procedure which draws Checkboxes
 *    in the Dark Mode style.
 */

static void DrawDarkCheckBox(
    CGRect bounds,
    Ttk_State state,
    CGContextRef context)
{
................................................................................
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 4);
    bounds = CGRectInset(bounds, 1, 1);
    if (!(state & TTK_STATE_BACKGROUND) &&
	!(state & TTK_STATE_DISABLED) &&
	((state  & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) {
	GradientFillRoundedRectangle(context, bounds, 3,
				     darkSelectedGradient, 2);
    } else {
	GradientFillRoundedRectangle(context, bounds, 3,
				     darkInactiveGradient, 2);
    }
    HighlightButtonBorder(context, bounds);
    if ((state  & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE)) {
	CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
	if (state & TTK_STATE_DISABLED) {
	    stroke = [NSColor disabledControlTextColor];
	} else {
	    stroke = [NSColor controlTextColor];
	}
	CGContextSetStrokeColorWithColor(context, stroke.CGColor);
................................................................................
	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(
................................................................................
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 9);
    bounds = CGRectInset(bounds, 1, 1);
    if (!(state & TTK_STATE_BACKGROUND) &&
	!(state & TTK_STATE_DISABLED) &&
	((state  & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) {
	GradientFillRoundedRectangle(context, bounds, 8,
				     darkSelectedGradient, 2);
    } else {
	GradientFillRoundedRectangle(context, bounds, 8,
				     darkInactiveGradient, 2);
    }
    HighlightButtonBorder(context, bounds);
    if ((state  & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE)) {
	CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
	if (state & TTK_STATE_DISABLED) {
	    fill = [NSColor disabledControlTextColor];
	} else {
	    fill = [NSColor controlTextColor];
	}
	CGContextSetFillColorWithColor(context, fill.CGColor);
................................................................................
	CGContextFillPath(context);
    } else if (state & TTK_STATE_ALTERNATE) {
	CGRect bar = {{x + 5, y + 8}, {8, 2}};
	CGContextFillRect(context, bar);
    }
}

/*
 * DrawDarkTab --
 *
 *    This is a standalone drawing procedure which draws Tabbed Pane
 *    Tabs in the Dark Mode style.
 */

static void DrawDarkTab(
................................................................................
    }

    if (!(state & TTK_STATE_LAST_TAB)) {
	bounds.size.width += 10;
    }

    /*
     * Fill the tab face with the appropriate color or gradient.  Use a
     * solid color if the tab is not selected, otherwise use a blue or
     * gray gradient.
     */

    bounds = CGRectInset(bounds, 1, 1);
    if (!(state & TTK_STATE_SELECTED)) {
	if (state & TTK_STATE_DISABLED) {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
				     components: darkDisabledButtonFace
................................................................................
	        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
	 * always drawn last.)
	 */

	if ((state & TTK_STATE_FIRST_TAB) && !(state & TTK_STATE_LAST_TAB)) {
................................................................................
					  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(
................................................................................
    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(
................................................................................
    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);
................................................................................
	CGContextRestoreGState(context);
	break;
    default:
	break;
    }
}

/*
 * DrawListHeader --
 *
 *    This is a standalone drawing procedure which draws column
 *    headers for a Treeview in the Dark Mode.
 */

static void DrawDarkListHeader(
................................................................................
    CGContextStrokePath(context);
    CGContextAddLines(context, separator, 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, whiteRGBA);
	} else if (state & TTK_STATE_SELECTED) {
	    DrawDownArrow(context, arrowBounds, 3, 8, whiteRGBA);
	}
................................................................................

static Ttk_StateTable ButtonAdornmentTable[] = {
    { kThemeAdornmentDefault | kThemeAdornmentFocus,
	TTK_STATE_ALTERNATE | TTK_STATE_FOCUS, 0 },
    { kThemeAdornmentDefault, TTK_STATE_ALTERNATE, 0 },
    { kThemeAdornmentNone, TTK_STATE_ALTERNATE, 0 },
    { kThemeAdornmentFocus, TTK_STATE_FOCUS, 0 },
    { kThemeAdornmentNone, 0, 0 }};


/*

 * computeButtonDrawInfo --
 *    Fill in an appearance manager HIThemeButtonDrawInfo record.
 */

static inline HIThemeButtonDrawInfo computeButtonDrawInfo(
    ThemeButtonParams *params,
    Ttk_State state,
    Tk_Window tkwin)
{
    /*
     *  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;
................................................................................
	 * 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
	 * text to be left justified, no matter what -anchor setting is used
	 * in the style.
	 */

	*minWidth = 0;
    }
}

static void ButtonElementSize(
................................................................................
    ThemeButtonParams *params = clientData;
    const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin);
    static const CGRect scratchBounds = {{0, 0}, {100, 100}};
    CGRect contentBounds, backgroundBounds;
    int verticalPad;

    ButtonElementMinSize(clientData, elementRecord, tkwin,
		      minWidth, minHeight, paddingPtr);

    /*
     * Given a hypothetical bounding rectangle for a button, HIToolbox will
     * compute a bounding rectangle for the button contents and a bounding
     * rectangle for the button background.  The background bounds are large
     * enough to contain the image of the button in any state, which might
     * include highlight borders, shadows, etc.  The content rectangle is not
................................................................................
     * 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)
................................................................................
	case kThemeRadioButton:
	    DrawDarkRadioButton(bounds, state, dc.context);
	    break;
	case kThemeRoundedBevelButton:
	    DrawDarkBevelButton(bounds, state, dc.context);
	    break;
	default:
	    ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);

	}
#endif
    } else {
	/*
	 *  Apple's PushButton and PopupButton do not change their fill color
	 *  when the window is inactive.  However, except in 10.7 (Lion), the
	 *  color of the arrow button on a PopupButton does change.  For some
	 *  reason HITheme fills inactive buttons with a transparent color that
	 *  allows the window background to show through, leading to
	 *  inconsistent behavior.  We work around this by filling behind an
	 *  inactive PopupButton with a text background color before asking
	 *  HIToolbox to draw it. For PushButtons, we simply draw them in the
	 *  active state.
	 */

#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	if (info.kind == kThemePopupButton && (state & TTK_STATE_BACKGROUND)) {
	    CGRect innerBounds = CGRectInset(bounds, 1, 1);
	    NSColor *whiteRGBA = [NSColor whiteColor];
	    SolidFillRoundedRectangle(dc.context, innerBounds, 4, whiteRGBA);
................................................................................
	 */

	if (info.kind == kThemeRoundedBevelButton &&
	    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),
................................................................................
 * (or toolbar, if there is one). If you choose to inset a tab view in a
 * window, you should leave a margin of 20 pixels between the sides and bottom
 * of the tab view and the sides and bottom of the window (although 16 pixels
 * is also an acceptable margin-width). If you need to provide controls below
 * the tab view, leave enough space below the tab view so the controls are 20
 * pixels above the bottom edge of the window and 12 pixels between the tab
 * view and the controls.

 * If you choose to extend the tab view sides and bottom so that they meet the
 * window sides and bottom, you should leave a margin of at least 20 pixels
 * 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>
................................................................................
	.adornment = kHIThemeTabPaneAdornmentNormal,
    };
    bounds.origin.y -= kThemeMetricTabFrameOverlap;
    bounds.size.height += kThemeMetricTabFrameOverlap;
    ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrieRectntation);
#endif
    END_DRAWING
    [TkMacOSXDrawableView(macWin) setNeedsDisplay:YES];
}

static Ttk_ElementSpec PaneElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    PaneElementSize,
................................................................................
    PaneElementDraw
};

/*
 * Labelframe borders:
 * Use "primary group box ..."
 * Quoth DrawThemePrimaryGroup reference:
 * "The primary group box frame is drawn inside the specified
 * rectangle and is 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);
................................................................................
    Drawable d, Ttk_Box b, Ttk_State state)
{
    EntryElement *e = elementRecord;
    Ttk_Box inner = Ttk_PadBox(b, Ttk_UniformPadding(3));
    CGRect bounds = BoxToRect(d, inner);
    NSColor *background;
    Tk_3DBorder backgroundPtr = NULL;
    static 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);
................................................................................
	    .isFocused = state & TTK_STATE_FOCUS,
	};

	/*
	 * Earlier versions of the Aqua theme ignored the -fieldbackground
	 * option and used the -background as if it were -fieldbackground.
	 * Here we are enabling -fieldbackground.  For backwards compatibility,
	 * if -fieldbackground is set to the default color and -background
	 * is set to a different color then we use -background as -fieldbackground.

	 */

	if (0 != strcmp(Tcl_GetString(e->fieldbackgroundObj), defaultBG)) {
	    backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->fieldbackgroundObj);
	} else if (0 != strcmp(Tcl_GetString(e->backgroundObj), defaultBG)) {
	    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];
	    CGContextSetFillColorWithColor(dc.context, background.CGColor);
	    CGContextFillRect(dc.context, bounds);
	}
................................................................................
    EntryElementDraw
};

/*----------------------------------------------------------------------
 * +++ Combobox:
 *
 * NOTES:
 *    The HIToolbox has incomplete and inconsistent support for ComboBoxes.
 *    There is no constant available to get the height of a ComboBox with
 *    GetThemeMetric. In fact, ComboBoxes are the same (fixed) height as
 *    PopupButtons and PushButtons, but they have no shadow at the bottom.
 *    As a result, they are drawn 1 pixel above the center of the bounds
 *    rectangle rather than being centered like the other buttons.  One
 *    can request background bounds for a ComboBox, and it is reported with
 *    height 23, while the actual button face, including its 1-pixel border
 *    has height 21.  Attempting to request the content bounds returns a
 *    0 x 0 rectangle.  Measurement indicates that the arrow button has
 *    width 18.
 *
 *    With no help available from HIToolbox, we have to use hard-wired
 *    constants for the padding.  We shift the bounding rectangle downward
 *    by 1 pixel to account for the fact that the button is not centered.
 */

static Ttk_Padding ComboboxPadding = {4, 2, 20, 2 };

static void ComboboxElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
................................................................................
    ComboboxElementSize,
    ComboboxElementDraw
};

/*----------------------------------------------------------------------
 * +++ Spinbuttons.
 *
 *    From Apple HIG, part III, section "Controls", "The Stepper Control":
 *    there should be 2 pixels of space between the stepper control (AKA
 *    IncDecButton, AKA "little arrows") and the text field it modifies.
 *
 *    Ttk expects the up and down arrows to be distinct elements but HIToolbox
 *    draws them as one widget with two different pressed states.  We work
 *    around this by defining them as separate elements in the layout, but
 *    making each one have a drawing method which also draws the other one.
 *    The down button does no drawing when not pressed, and when pressed draws
 *    the entire IncDecButton in its "pressed down" state.  The up button draws
 *    the entire IncDecButton when not pressed and when pressed draws the
 *    IncDecButton in its "pressed up" state.  NOTE: This means that when the
 *    down button is pressed the IncDecButton will be drawn twice, first
 *    in unpressed state by the up arrow and then in "pressed down" state by
 *    the down button.  The drawing must be done in that order.  So the up
 *    button must be listed first in the layout.
 */

static Ttk_Padding SpinbuttonMargins = {0, 0, 2, 0};
static void SpinButtonUpElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
................................................................................
	.version = 0,
	.state = infoState,
	.kind = kThemeIncDecButton,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = kThemeAdornmentNone,
    };
    BEGIN_DRAWING(d)

    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkIncDecButton(bounds, infoState, state, dc.context);
    } else {


	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}

static Ttk_ElementSpec SpinButtonUpElementSpec = {
    TK_STYLE_VERSION_2,
................................................................................
	.state = infoState,
	.kind = kThemeIncDecButton,
	.value = Ttk_StateTableLookup(ButtonValueTable, state),
	.adornment = kThemeAdornmentNone,
    };

    BEGIN_DRAWING(d)

    if (TkMacOSXInDarkMode(tkwin)) {
	DrawDarkIncDecButton(bounds, infoState, state, dc.context);
    } else {


	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}

static Ttk_ElementSpec SpinButtonDownElementSpec = {
    TK_STYLE_VERSION_2,
................................................................................

/*----------------------------------------------------------------------
 * +++ DrawThemeTrack-based elements --
 *    Progress bars and scales. (See also: <<NOTE-TRACKS>>)
 */

/*
 * Apple does not change the appearance of a slider when the window
 * becomes inactive.  So we shouldn't either.
 */

static Ttk_StateTable ThemeTrackEnableTable[] = {
    { kThemeTrackDisabled, TTK_STATE_DISABLED, 0 },
    { kThemeTrackActive, TTK_STATE_BACKGROUND, 0 },
    { kThemeTrackActive, 0, 0 }
    /* { kThemeTrackNothingToScroll, ?, ? }, */
................................................................................
    ThemeTrackKind	kind;
    SInt32		thicknessMetric;
} TrackElementData;

static TrackElementData ScaleData = {
    kThemeSlider, kThemeMetricHSliderHeight
};


typedef struct {
    Tcl_Obj *fromObj;		/* minimum value */
    Tcl_Obj *toObj;		/* maximum value */
    Tcl_Obj *valueObj;		/* current value */
    Tcl_Obj *orientObj;		/* horizontal / vertical */
} TrackElement;
................................................................................

/*
 * Slider element -- <<NOTE-TRACKS>>
 * 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;
}
................................................................................
    {0,0,0,0}
};

static void PbarElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
    SInt32 size = 24;	/* @@@ Check HIG for correct default */

    ChkErr(GetThemeMetric, kThemeMetricLargeProgressBarThickness, &size);
    *minWidth = *minHeight = size;
}

static void PbarElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
................................................................................

/*----------------------------------------------------------------------
 * +++ Scrollbar element
 */

typedef struct
{
    Tcl_Obj     *orientObj;
} ScrollbarElement;

static Ttk_ElementOptionSpec ScrollbarElementOptions[] = {
    { "-orient", TK_OPTION_STRING,
	Tk_Offset(ScrollbarElement,orientObj), "horizontal" },
    {0,0,0,0}
};
................................................................................
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, unsigned int state)
{
    CGRect bounds = BoxToRect(d, b);
    HIThemeGrowBoxDrawInfo info = {
	.version = 0,
	/* Grow box only supports kThemeStateActive, kThemeStateInactive */
	.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);
................................................................................
    SizegripElementSize,
    SizegripElementDraw
};

/*----------------------------------------------------------------------
 * +++ Background and fill elements.
 *
 *    Before drawing any ttk widget, its bounding rectangle is filled with a
 *    background color.  This color must match the background color of the
 *    containing widget to avoid looking ugly. The need for care when doing
 *    this is exacerbated by the fact that ttk enforces its "native look" by
 *    not allowing user control of the background or highlight colors of ttk
 *    widgets.
 *
 *    This job is made more complicated in recent versions of macOS by the fact
 *    that the Appkit GroupBox (used for ttk LabelFrames) and TabbedPane (used
 *    for the Notebook widget) both place their content inside a rectangle with
 *    rounded corners that has a color which contrasts with the dialog
 *    background color.  Moreover, although the Apple human interface
 *    guidelines recommend against doing so, there are times when one wants to
 *    nest these widgets, for example having a GroupBox inside of a TabbedPane.
 *    To have the right contrast, each level of nesting requires a different
 *    color.
 *
 *    Previous Tk releases used the HIThemeDrawGroupBox routine to draw
 *    GroupBoxes and TabbedPanes. This meant that the best that could be done
 *    was to set the GroupBox to be of kind kHIThemeGroupBoxKindPrimaryOpaque,
 *    and set its fill color to be the system background color.  If widgets
 *    inside the box were drawn with the system background color the
 *    backgrounds would match.  But this produces a GroupBox with no contrast,
 *    the only visual clue being a faint highlighting around the top of the
 *    GroupBox.  Moreover, the TabbedPane does not have an Opaque version, so
 *    while it is drawn inside a contrasting rounded rectangle, the widgets
 *    inside the pane needed to be enclosed in a frame with the system
 *    background color. This added a visual artifact since the frame's
 *    background color does not match the Pane's background color.  That code
 *    has now been replaced with the standalone drawing procedure
 *    macOSXDrawGroupBox, which draws a rounded rectangle with an appropriate
 *    contrasting background color.
 *
 *    Patterned backgrounds, which are now obsolete, should be aligned with the
 *    coordinate system of the top-level window.  Apparently failing to do this
 *    used to cause graphics anomalies when drawing into an off-screen graphics
 *    port.  The code for handling this is currently commented out.

 */


static void FillElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
................................................................................
static void FieldElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    FieldElement *e = elementRecord;
    Tk_3DBorder backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->backgroundObj);
    XFillRectangle(Tk_Display(tkwin), d,
		   Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC),
		   b.x, b.y, b.width, b.height);
}

static Ttk_ElementSpec FieldElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(FieldElement),
    FieldElementOptions,
    TtkNullElementSize,
................................................................................
    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.
     */

   if ([NSApp macMinorVersion] > 8) {
       paddingPtr->top = 4;
    }
}

static Ttk_ElementSpec TreeAreaElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
................................................................................

static void TreeHeaderElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
    if ([NSApp macMinorVersion] > 8) {
	*minHeight = 24;

    } else {
	ButtonElementSize(clientData, elementRecord, tkwin, minWidth,
			  minHeight, paddingPtr);
    }
}

static void TreeHeaderElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
................................................................................

	/*
	 * 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)) {
	    DrawDarkListHeader(bounds, dc.context, tkwin, state);
	} else {


	    DrawListHeader(bounds, dc.context, tkwin, state);
	}
    } else {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}
................................................................................

    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);








|
|
<
|

|
|
<







 







<







 







|
|
|




|
|
|
|






|


|
|
|
|
|
|








|
|







 







|
>







 







|


|
|







 







>
|

|



|
|
|
|










<
>
|

|



|
|
|
|
|



>
|
|
>

|








<







 







>
|
>







 







>
|
>




|


|
|
<
|
|







 







|










|







 







>
|












|
|
>
|
>





|




>
|












|



|

|







|


|
|







 







|







 







|


|
|







 







|


|
|







 







|







 







|


|
|







 







|
|

|


|


|







 







|







 







|
|

|


|


|







 







|







 







|
|
<







 







<







 







|







 







|







 







>
|
>







 







|







 







>







 







|
>

<
>










|
|







 







|
|
|
|







 







|







 







|

|

|
|







 







|
>




|
|
|
|
|
|
|
|
|







 







|
>







 







>







 







<







 







|
|

|
|







 







|







 







|
|
>









|
|







 







|
|
|
|
|
|
|
|
|
|
<

|
|
|







 







|
|
|

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







 







>


|
>
>







 







>


|
>
>







 







|
|







 







<







 







|
|
<







 







|







 







|







 







|
>







 







|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

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

|
|
|
|
>

<







 







|
|







 







|
|







 







<


|







 







>


|
>
>







 







|
>







17
18
19
20
21
22
23
24
25

26
27
28
29

30
31
32
33
34
35
36
...
107
108
109
110
111
112
113

114
115
116
117
118
119
120
...
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
...
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
...
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
...
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
...
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
...
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
...
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
...
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
...
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
...
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
...
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
...
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
...
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
...
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
...
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
...
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
...
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
...
836
837
838
839
840
841
842
843
844

845
846
847
848
849
850
851
...
874
875
876
877
878
879
880

881
882
883
884
885
886
887
...
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
...
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
...
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
...
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
....
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
....
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066

1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
....
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
....
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
....
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
....
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
....
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
....
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
....
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
....
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
....
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
....
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
....
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
....
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
....
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
....
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
....
1773
1774
1775
1776
1777
1778
1779

1780
1781
1782
1783
1784
1785
1786
....
1872
1873
1874
1875
1876
1877
1878
1879
1880

1881
1882
1883
1884
1885
1886
1887
....
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
....
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
....
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
....
2320
2321
2322
2323
2324
2325
2326
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
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365

2366
2367
2368
2369
2370
2371
2372
....
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
....
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
....
2533
2534
2535
2536
2537
2538
2539

2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
....
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
....
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
 *
 * <URL: http://developer.apple.com/documentation/Carbon/Reference/
 *	Appearance_Manager/appearance_manager/APIIndex.html >
 *
 * Notes:
 *	"Active" means different things in Mac and Tk terminology --
 *	On Aqua, widgets are "Active" if they belong to the foreground window,
 *	"Inactive" if they are in a background window.  Tk uses the term
 *	"active" to mean that the mouse cursor is over a widget; aka "hover",

 *	"prelight", or "hot-tracked".  Aqua doesn't use this kind of feedback.
 *
 *	The QuickDraw/Carbon coordinate system is relative to the top-level
 *	window, not to the Tk_Window.  BoxToRect() accounts for this.

 */

#include "tkMacOSXPrivate.h"
#include "ttk/ttkTheme.h"
#include <math.h>
/*
 * Macros for handling drawing contexts.
................................................................................
 * 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.size.height = height;
    }
    return bounds;
}

#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
/*----------------------------------------------------------------------
 * +++ Support for contrasting background colors when GroupBoxes or Tabbed
 * panes are nested inside each other.  Early versions of macOS used ridged
 * borders, so do not need contrasting backgrounds.
 */

/*
 * For systems older than 10.14, [NSColor windowBackGroundColor] generates
 * garbage when called from this function.  In 10.14 it works correctly, and
 * must be used in order to have a background color which responds to Dark
 * Mode.  So we use this hard-wired RGBA color on the older systems which don't
 * support Dark Mode anyway.
 */

static CGFloat windowBackground[4] = {235.0/255, 235.0/255, 235.0/255, 1.0};
static CGFloat whiteRGBA[4] = {1.0, 1.0, 1.0, 1.0};
static CGFloat blackRGBA[4] = {0.0, 0.0, 0.0, 1.0};

/*----------------------------------------------------------------------
 * 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) {
................................................................................
	} else {
	    for (int i = 0; i < 4; i++) {
		rgba[i] = windowBackground[i];
	    }
	}
    }
    if (contrast) {
	int isDark = (rgba[0] + rgba[1] + rgba[2] < 1.5);

	if (isDark) {
	    for (int i=0; i<3; i++) {
		rgba[i] += 8.0/255.0;
	    }
	} else {
	    for (int i=0; i<3; i++) {
		rgba[i] -= 8.0/255.0;
................................................................................
	winPtr->privatePtr->flags |= TTK_HAS_CONTRASTING_BG;
	for (int i = 0; i < 4; i++) {
	    winPtr->privatePtr->fillRGBA[i] = rgba[i];
	}
    }
}

/*----------------------------------------------------------------------
 * DrawGroupBox --
 *
 *	This is a standalone drawing procedure which draws the contrasting
 *	rounded rectangular box for LabelFrames and Notebook panes.
 */

static void DrawGroupBox(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin)
{
................................................................................
    CGContextBeginPath(context);
    CGContextAddPath(context, path);
    CGContextReplacePathWithStrokedPath(context);
    CGContextFillPath(context);
    CFRelease(path);
}

/*----------------------------------------------------------------------
 * SolidFillRoundedRectangle --
 *
 *	Fill a rounded rectangle with a specified solid color.
 */

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);
}


/*----------------------------------------------------------------------
 * 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);
}


static void DrawUpDownArrows(
    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 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 --
 *
 *    This is a standalone drawing procedure which draws column headers for a
 *    Treeview in the Aqua appearance.  The HITheme headers have not matched

 *    the native ones since OSX 10.8.  Note that the header image is ignored,
 *    but we draw arrows according to the state.
 */

static void DrawListHeader(
    CGRect bounds,
    CGContextRef context,
    Tk_Window tkwin,
    int state)
................................................................................
	    DrawDownArrow(context, arrowBounds, 3, 8, blackRGBA);
	}
    }
}

#endif /* MAC_OS_X_VERSION_MIN_REQUIRED > 1080 */

#if MAC_OS_X_VERSION_MIN_REQUIRED > 101300
/*----------------------------------------------------------------------
 * +++ Drawing procedures for widgets in Apple's "Dark Mode" (10.14 and up).
 *
 *    The HIToolbox does not support Dark Mode, and apparently never will,
 *    so to make widgets look "native" we have to provide analogues of the
 *    HITheme drawing functions to be used in DarkAqua.  We continue to use
 *    HITheme in Aqua, since it understands earlier versions of the OS.
 */

/*
 * Colors and gradients used in Dark Mode.
 */

static CGFloat darkButtonFace[4] = {112.0/255, 113.0/255, 115.0/255, 1.0};
static CGFloat darkPressedBevelFace[4] = {135.0/255, 136.0/255, 138.0/255, 1.0};
static CGFloat darkSelectedBevelFace[4] = {162.0/255, 163.0/255, 165.0/255, 1.0};
static CGFloat darkDisabledButtonFace[4] = {86.0/255, 87.0/255, 89.0/255, 1.0};
static CGFloat darkInactiveSelectedTab[4] = {159.0/255, 160.0/255, 161.0/255, 1.0};
................................................................................
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};

/*----------------------------------------------------------------------
 * FillButtonBackground --
 *
 *    Fills a rounded rectangle with a transparent black gradient.
 */

static void FillButtonBackground(
    CGContextRef context,
    CGRect bounds,
    CGFloat radius)
{
    CGPathRef path;
    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);
    CFRelease(backgroundGradient);
}

/*----------------------------------------------------------------------
 * HighlightButtonBorder --
 *
 * Accent the top border of a rounded rectangle with a transparent
 * white gradient.
 */

static void HighlightButtonBorder(
    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);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, topGradient, bounds.origin, topEnd, 0.0);
    CGContextRestoreGState(context);
    CFRelease(topGradient);
}

/*----------------------------------------------------------------------
 * DrawDarkButton --
 *
 *	This is a standalone drawing procedure which draws PushButtons and
 *	PopupButtons in the Dark Mode style.
 */

static void DrawDarkButton(
    CGRect bounds,
    ThemeButtonKind kind,
    Ttk_State state,
    CGContextRef context)
................................................................................
    /*
     * Fill the button face with the appropriate color.
     */

    bounds = CGRectInset(bounds, 1, 1);
    if (kind == kThemePushButton && (state & TTK_STATE_PRESSED)) {
	GradientFillRoundedRectangle(context, bounds, 4,
		darkSelectedGradient, 2);
    } else {
	if (state & TTK_STATE_DISABLED) {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
					  components: darkDisabledButtonFace
					       count: 4];
	} else {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
................................................................................
	    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)
................................................................................
				   darkSelectedGradient, 2);
	CGContextRestoreGState(context);
    }
    DrawUpDownArrows(context, bounds, 3, 5, whiteRGBA);
    HighlightButtonBorder(context, bounds);
}

/*----------------------------------------------------------------------
 * DrawDarkBevelButton --
 *
 *	This is a standalone drawing procedure which draws RoundedBevelButtons
 *	in the Dark Mode style.
 */

static void DrawDarkBevelButton(
    CGRect bounds,
    Ttk_State state,
    CGContextRef context)
{
................................................................................

    bounds = CGRectInset(bounds, 1, 1);
    if (state & TTK_STATE_PRESSED) {
	faceColor = [NSColor colorWithColorSpace: deviceRGB
					  components: darkPressedBevelFace
					       count: 4];
    } else if ((state & TTK_STATE_DISABLED) ||
	       (state & TTK_STATE_ALTERNATE)) {
	faceColor = [NSColor colorWithColorSpace: deviceRGB
				      components: darkDisabledButtonFace
					   count: 4];
    } else if (state & TTK_STATE_SELECTED) {
	faceColor = [NSColor colorWithColorSpace: deviceRGB
				      components: darkSelectedBevelFace
					   count: 4];
................................................................................
				      components: darkButtonFace
					   count: 4];
    }
    SolidFillRoundedRectangle(context, bounds, 4, faceColor);
    HighlightButtonBorder(context, bounds);
}

/*----------------------------------------------------------------------
 * DrawDarkCheckBox --
 *
 *	This is a standalone drawing procedure which draws Checkboxes in the
 *	Dark Mode style.
 */

static void DrawDarkCheckBox(
    CGRect bounds,
    Ttk_State state,
    CGContextRef context)
{
................................................................................
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 4);
    bounds = CGRectInset(bounds, 1, 1);
    if (!(state & TTK_STATE_BACKGROUND) &&
	    !(state & TTK_STATE_DISABLED) &&
	    ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) {
	GradientFillRoundedRectangle(context, bounds, 3,
		darkSelectedGradient, 2);
    } else {
	GradientFillRoundedRectangle(context, bounds, 3,
		darkInactiveGradient, 2);
    }
    HighlightButtonBorder(context, bounds);
    if ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE)) {
	CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
	if (state & TTK_STATE_DISABLED) {
	    stroke = [NSColor disabledControlTextColor];
	} else {
	    stroke = [NSColor controlTextColor];
	}
	CGContextSetStrokeColorWithColor(context, stroke.CGColor);
................................................................................
	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(
................................................................................
    x = bounds.origin.x;
    y = bounds.origin.y;

    CGContextClipToRect(context, bounds);
    FillButtonBackground(context, bounds, 9);
    bounds = CGRectInset(bounds, 1, 1);
    if (!(state & TTK_STATE_BACKGROUND) &&
	    !(state & TTK_STATE_DISABLED) &&
	    ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE))) {
	GradientFillRoundedRectangle(context, bounds, 8,
		darkSelectedGradient, 2);
    } else {
	GradientFillRoundedRectangle(context, bounds, 8,
		darkInactiveGradient, 2);
    }
    HighlightButtonBorder(context, bounds);
    if ((state & TTK_STATE_SELECTED) || (state & TTK_STATE_ALTERNATE)) {
	CGContextSetStrokeColorSpace(context, deviceRGB.CGColorSpace);
	if (state & TTK_STATE_DISABLED) {
	    fill = [NSColor disabledControlTextColor];
	} else {
	    fill = [NSColor controlTextColor];
	}
	CGContextSetFillColorWithColor(context, fill.CGColor);
................................................................................
	CGContextFillPath(context);
    } else if (state & TTK_STATE_ALTERNATE) {
	CGRect bar = {{x + 5, y + 8}, {8, 2}};
	CGContextFillRect(context, bar);
    }
}

/*----------------------------------------------------------------------
 * DrawDarkTab --
 *
 *    This is a standalone drawing procedure which draws Tabbed Pane
 *    Tabs in the Dark Mode style.
 */

static void DrawDarkTab(
................................................................................
    }

    if (!(state & TTK_STATE_LAST_TAB)) {
	bounds.size.width += 10;
    }

    /*
     * Fill the tab face with the appropriate color or gradient.  Use a solid
     * color if the tab is not selected, otherwise use a blue or gray gradient.

     */

    bounds = CGRectInset(bounds, 1, 1);
    if (!(state & TTK_STATE_SELECTED)) {
	if (state & TTK_STATE_DISABLED) {
	    faceColor = [NSColor colorWithColorSpace: deviceRGB
				     components: darkDisabledButtonFace
................................................................................
	        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
	 * always drawn last.)
	 */

	if ((state & TTK_STATE_FIRST_TAB) && !(state & TTK_STATE_LAST_TAB)) {
................................................................................
					  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(
................................................................................
    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(
................................................................................
    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);
................................................................................
	CGContextRestoreGState(context);
	break;
    default:
	break;
    }
}

/*----------------------------------------------------------------------
 * DrawListHeader --
 *
 *    This is a standalone drawing procedure which draws column
 *    headers for a Treeview in the Dark Mode.
 */

static void DrawDarkListHeader(
................................................................................
    CGContextStrokePath(context);
    CGContextAddLines(context, separator, 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, whiteRGBA);
	} else if (state & TTK_STATE_SELECTED) {
	    DrawDownArrow(context, arrowBounds, 3, 8, whiteRGBA);
	}
................................................................................

static Ttk_StateTable ButtonAdornmentTable[] = {
    { kThemeAdornmentDefault | kThemeAdornmentFocus,
	TTK_STATE_ALTERNATE | TTK_STATE_FOCUS, 0 },
    { kThemeAdornmentDefault, TTK_STATE_ALTERNATE, 0 },
    { kThemeAdornmentNone, TTK_STATE_ALTERNATE, 0 },
    { kThemeAdornmentFocus, TTK_STATE_FOCUS, 0 },
    { kThemeAdornmentNone, 0, 0 }
};


/*----------------------------------------------------------------------
 * computeButtonDrawInfo --
 *    Fill in an appearance manager HIThemeButtonDrawInfo record.
 */

static inline HIThemeButtonDrawInfo computeButtonDrawInfo(
    ThemeButtonParams *params,
    Ttk_State state,
    Tk_Window tkwin)
{
    /*
     * 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;
................................................................................
	 * 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
	 * text to be left justified, no matter what -anchor setting is used in
	 * the style.
	 */

	*minWidth = 0;
    }
}

static void ButtonElementSize(
................................................................................
    ThemeButtonParams *params = clientData;
    const HIThemeButtonDrawInfo info = computeButtonDrawInfo(params, 0, tkwin);
    static const CGRect scratchBounds = {{0, 0}, {100, 100}};
    CGRect contentBounds, backgroundBounds;
    int verticalPad;

    ButtonElementMinSize(clientData, elementRecord, tkwin,
	    minWidth, minHeight, paddingPtr);

    /*
     * Given a hypothetical bounding rectangle for a button, HIToolbox will
     * compute a bounding rectangle for the button contents and a bounding
     * rectangle for the button background.  The background bounds are large
     * enough to contain the image of the button in any state, which might
     * include highlight borders, shadows, etc.  The content rectangle is not
................................................................................
     * 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)
................................................................................
	case kThemeRadioButton:
	    DrawDarkRadioButton(bounds, state, dc.context);
	    break;
	case kThemeRoundedBevelButton:
	    DrawDarkBevelButton(bounds, state, dc.context);
	    break;
	default:
	    ChkErr(HIThemeDrawButton, &bounds, &info, dc.context,
		    HIOrientation, NULL);
	}
#endif
    } else {
	/*
	 * Apple's PushButton and PopupButton do not change their fill color
	 * when the window is inactive.  However, except in 10.7 (Lion), the
	 * color of the arrow button on a PopupButton does change.  For some
	 * reason HITheme fills inactive buttons with a transparent color that
	 * allows the window background to show through, leading to
	 * inconsistent behavior.  We work around this by filling behind an
	 * inactive PopupButton with a text background color before asking
	 * HIToolbox to draw it. For PushButtons, we simply draw them in the
	 * active state.
	 */

#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
	if (info.kind == kThemePopupButton && (state & TTK_STATE_BACKGROUND)) {
	    CGRect innerBounds = CGRectInset(bounds, 1, 1);
	    NSColor *whiteRGBA = [NSColor whiteColor];
	    SolidFillRoundedRectangle(dc.context, innerBounds, 4, whiteRGBA);
................................................................................
	 */

	if (info.kind == kThemeRoundedBevelButton &&
	    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),
................................................................................
 * (or toolbar, if there is one). If you choose to inset a tab view in a
 * window, you should leave a margin of 20 pixels between the sides and bottom
 * of the tab view and the sides and bottom of the window (although 16 pixels
 * is also an acceptable margin-width). If you need to provide controls below
 * the tab view, leave enough space below the tab view so the controls are 20
 * pixels above the bottom edge of the window and 12 pixels between the tab
 * view and the controls.
 *
 * If you choose to extend the tab view sides and bottom so that they meet the
 * window sides and bottom, you should leave a margin of at least 20 pixels
 * 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>
................................................................................
	.adornment = kHIThemeTabPaneAdornmentNormal,
    };
    bounds.origin.y -= kThemeMetricTabFrameOverlap;
    bounds.size.height += kThemeMetricTabFrameOverlap;
    ChkErr(HIThemeDrawTabPane, &bounds, &info, dc.context, HIOrieRectntation);
#endif
    END_DRAWING

}

static Ttk_ElementSpec PaneElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
    PaneElementSize,
................................................................................
    PaneElementDraw
};

/*
 * Labelframe borders:
 * Use "primary group box ..."
 * Quoth DrawThemePrimaryGroup reference:
 * "The primary group box frame is drawn inside the specified rectangle and is
 * 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);
................................................................................
    Drawable d, Ttk_Box b, Ttk_State state)
{
    EntryElement *e = elementRecord;
    Ttk_Box inner = Ttk_PadBox(b, Ttk_UniformPadding(3));
    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);
................................................................................
	    .isFocused = state & TTK_STATE_FOCUS,
	};

	/*
	 * Earlier versions of the Aqua theme ignored the -fieldbackground
	 * option and used the -background as if it were -fieldbackground.
	 * Here we are enabling -fieldbackground.  For backwards compatibility,
	 * if -fieldbackground is set to the default color and -background is
	 * set to a different color then we use -background as
	 * -fieldbackground.
	 */

	if (0 != strcmp(Tcl_GetString(e->fieldbackgroundObj), defaultBG)) {
	    backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->fieldbackgroundObj);
	} else if (0 != strcmp(Tcl_GetString(e->backgroundObj), defaultBG)) {
	    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];
	    CGContextSetFillColorWithColor(dc.context, background.CGColor);
	    CGContextFillRect(dc.context, bounds);
	}
................................................................................
    EntryElementDraw
};

/*----------------------------------------------------------------------
 * +++ Combobox:
 *
 * NOTES:
 *	The HIToolbox has incomplete and inconsistent support for ComboBoxes.
 *	There is no constant available to get the height of a ComboBox with
 *	GetThemeMetric. In fact, ComboBoxes are the same (fixed) height as
 *	PopupButtons and PushButtons, but they have no shadow at the bottom.
 *	As a result, they are drawn 1 pixel above the center of the bounds
 *	rectangle rather than being centered like the other buttons.  One can
 *	request background bounds for a ComboBox, and it is reported with
 *	height 23, while the actual button face, including its 1-pixel border
 *	has height 21. Attempting to request the content bounds returns a 0x0
 *	rectangle.  Measurement indicates that the arrow button has width 18.

 *
 *	With no help available from HIToolbox, we have to use hard-wired
 *	constants for the padding. We shift the bounding rectangle downward by
 *	1 pixel to account for the fact that the button is not centered.
 */

static Ttk_Padding ComboboxPadding = {4, 2, 20, 2 };

static void ComboboxElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
................................................................................
    ComboboxElementSize,
    ComboboxElementDraw
};

/*----------------------------------------------------------------------
 * +++ Spinbuttons.
 *
 *	From Apple HIG, part III, section "Controls", "The Stepper Control":
 *	there should be 2 pixels of space between the stepper control (AKA
 *	IncDecButton, AKA "little arrows") and the text field it modifies.
 *
 *	Ttk expects the up and down arrows to be distinct elements but
 *	HIToolbox draws them as one widget with two different pressed states.
 *	We work around this by defining them as separate elements in the
 *	layout, but making each one have a drawing method which also draws the
 *	other one.  The down button does no drawing when not pressed, and when
 *	pressed draws the entire IncDecButton in its "pressed down" state.  The
 *	up button draws the entire IncDecButton when not pressed and when
 *	pressed draws the IncDecButton in its "pressed up" state.  NOTE: This
 *	means that when the down button is pressed the IncDecButton will be
 *	drawn twice, first in unpressed state by the up arrow and then in
 *	"pressed down" state by the down button.  The drawing must be done in
 *	that order.  So the up button must be listed first in the layout.
 */

static Ttk_Padding SpinbuttonMargins = {0, 0, 2, 0};
static void SpinButtonUpElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
................................................................................
	.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,
................................................................................
	.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,
................................................................................

/*----------------------------------------------------------------------
 * +++ DrawThemeTrack-based elements --
 *    Progress bars and scales. (See also: <<NOTE-TRACKS>>)
 */

/*
 * Apple does not change the appearance of a slider when the window becomes
 * inactive.  So we shouldn't either.
 */

static Ttk_StateTable ThemeTrackEnableTable[] = {
    { kThemeTrackDisabled, TTK_STATE_DISABLED, 0 },
    { kThemeTrackActive, TTK_STATE_BACKGROUND, 0 },
    { kThemeTrackActive, 0, 0 }
    /* { kThemeTrackNothingToScroll, ?, ? }, */
................................................................................
    ThemeTrackKind	kind;
    SInt32		thicknessMetric;
} TrackElementData;

static TrackElementData ScaleData = {
    kThemeSlider, kThemeMetricHSliderHeight
};


typedef struct {
    Tcl_Obj *fromObj;		/* minimum value */
    Tcl_Obj *toObj;		/* maximum value */
    Tcl_Obj *valueObj;		/* current value */
    Tcl_Obj *orientObj;		/* horizontal / vertical */
} TrackElement;
................................................................................

/*
 * Slider element -- <<NOTE-TRACKS>>
 * 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;
}
................................................................................
    {0,0,0,0}
};

static void PbarElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
    SInt32 size = 24;		/* @@@ Check HIG for correct default */

    ChkErr(GetThemeMetric, kThemeMetricLargeProgressBarThickness, &size);
    *minWidth = *minHeight = size;
}

static void PbarElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
................................................................................

/*----------------------------------------------------------------------
 * +++ Scrollbar element
 */

typedef struct
{
    Tcl_Obj *orientObj;
} ScrollbarElement;

static Ttk_ElementOptionSpec ScrollbarElementOptions[] = {
    { "-orient", TK_OPTION_STRING,
	Tk_Offset(ScrollbarElement,orientObj), "horizontal" },
    {0,0,0,0}
};
................................................................................
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, unsigned int state)
{
    CGRect bounds = BoxToRect(d, b);
    HIThemeGrowBoxDrawInfo info = {
	.version = 0,
	/* Grow box only supports kThemeStateActive, kThemeStateInactive */
	.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);
................................................................................
    SizegripElementSize,
    SizegripElementDraw
};

/*----------------------------------------------------------------------
 * +++ Background and fill elements.
 *
 *	Before drawing any ttk widget, its bounding rectangle is filled with a
 *	background color.  This color must match the background color of the
 *	containing widget to avoid looking ugly. The need for care when doing
 *	this is exacerbated by the fact that ttk enforces its "native look" by
 *	not allowing user control of the background or highlight colors of ttk
 *	widgets.
 *
 *	This job is made more complicated in recent versions of macOS by the
 *	fact that the Appkit GroupBox (used for ttk LabelFrames) and TabbedPane
 *	(used for the Notebook widget) both place their content inside a
 *	rectangle with rounded corners that has a color which contrasts with
 *	the dialog background color.  Moreover, although the Apple human
 *	interface guidelines recommend against doing so, there are times when
 *	one wants to nest these widgets, for example having a GroupBox inside
 *	of a TabbedPane.  To have the right contrast, each level of nesting
 *	requires a different color.
 *
 *	Previous Tk releases used the HIThemeDrawGroupBox routine to draw
 *	GroupBoxes and TabbedPanes. This meant that the best that could be done
 *	was to set the GroupBox to be of kind
 *	kHIThemeGroupBoxKindPrimaryOpaque, and set its fill color to be the
 *	system background color.  If widgets inside the box were drawn with the
 *	system background color the backgrounds would match.  But this produces
 *	a GroupBox with no contrast, the only visual clue being a faint
 *	highlighting around the top of the GroupBox.  Moreover, the TabbedPane
 *	does not have an Opaque version, so while it is drawn inside a
 *	contrasting rounded rectangle, the widgets inside the pane needed to be
 *	enclosed in a frame with the system background color. This added a
 *	visual artifact since the frame's background color does not match the
 *	Pane's background color.  That code has now been replaced with the
 *	standalone drawing procedure macOSXDrawGroupBox, which draws a rounded
 *	rectangle with an appropriate contrasting background color.
 *
 *	Patterned backgrounds, which are now obsolete, should be aligned with
 *	the coordinate system of the top-level window.  Apparently failing to
 *	do this used to cause graphics anomalies when drawing into an
 *	off-screen graphics port.  The code for handling this is currently
 *	commented out.
 */


static void FillElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    CGRect bounds = BoxToRect(d, b);
#if MAC_OS_X_VERSION_MIN_REQUIRED > 1080
................................................................................
static void FieldElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
    FieldElement *e = elementRecord;
    Tk_3DBorder backgroundPtr = Tk_Get3DBorderFromObj(tkwin,e->backgroundObj);
    XFillRectangle(Tk_Display(tkwin), d,
	    Tk_3DBorderGC(tkwin, backgroundPtr, TK_3D_FLAT_GC),
	    b.x, b.y, b.width, b.height);
}

static Ttk_ElementSpec FieldElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(FieldElement),
    FieldElementOptions,
    TtkNullElementSize,
................................................................................
    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.
     */

    if ([NSApp macMinorVersion] > 8) {
	paddingPtr->top = 4;
    }
}

static Ttk_ElementSpec TreeAreaElementSpec = {
    TK_STYLE_VERSION_2,
    sizeof(NullElement),
    TtkNullElementOptions,
................................................................................

static void TreeHeaderElementSize(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *minWidth, int *minHeight, Ttk_Padding *paddingPtr)
{
    if ([NSApp macMinorVersion] > 8) {
	*minHeight = 24;

    } else {
	ButtonElementSize(clientData, elementRecord, tkwin, minWidth,
		minHeight, paddingPtr);
    }
}

static void TreeHeaderElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, Ttk_State state)
{
................................................................................

	/*
	 * 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 MAC_OS_X_VERSION_MIN_REQUIRED > 101300
	if (TkMacOSXInDarkMode(tkwin)) {
	    DrawDarkListHeader(bounds, dc.context, tkwin, state);
	} else
#endif
	{
	    DrawListHeader(bounds, dc.context, tkwin, state);
	}
    } else {
	ChkErr(HIThemeDrawButton, &bounds, &info, dc.context, HIOrientation, NULL);
    }
    END_DRAWING
}
................................................................................

    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);