Check-in [f9d93e8f51]
Not logged in

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

Overview
Comment:merge with trunk
Timelines: family | ancestors | descendants | both | wtf-8-experiment
Files: files | file ages | folders
SHA1:f9d93e8f510a34805eb1f91fecb60790ffb89281
User & Date: chw 2019-04-12 04:59:07
Context
2019-04-13
06:53
merge with trunk check-in: a7259ebe61 user: chw tags: wtf-8-experiment
2019-04-12
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
2019-04-11
09:55
merge with trunk check-in: 72260cb0db user: chw tags: wtf-8-experiment
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
....
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
....
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842

1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
....
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
....
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
2742
....
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
....
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
3662
....
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
3743
....
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
3907
....
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
....
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
....
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
....
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
....
5579
5580
5581
5582
5583
5584
5585

5586
5587
5588
5589
5590
5591

5592
5593
5594
5595
5596
5597
5598
....
5785
5786
5787
5788
5789
5790
5791
5792

5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
....
5837
5838
5839
5840
5841
5842
5843
5844




5845
5846
5847
5848
5849
5850
5851
....
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
....
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
....
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
....
6095
6096
6097
6098
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
....
6144
6145
6146
6147
6148
6149
6150

6151
6152
6153
6154
6155
6156
6157
....
6538
6539
6540
6541
6542
6543
6544
6545
6546

6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
....
6703
6704
6705
6706
6707
6708
6709

6710
6711
6712
6713
6714
6715
6716
....
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753

6754
6755
6756
6757
6758
6759
6760

6761
6762
6763
6764
6765
6766
6767
....
6790
6791
6792
6793
6794
6795
6796

6797
6798
6799
6800
6801
6802
6803
....
6833
6834
6835
6836
6837
6838
6839
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
....
6885
6886
6887
6888
6889
6890
6891

6892
6893
6894
6895
6896
6897
6898
....
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
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
....
7232
7233
7234
7235
7236
7237
7238

7239


7240
7241
7242
7243
7244
7245
7246
	| 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
....
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
....
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
....
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
....
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
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
....
2737
2738
2739
2740
2741
2742
2743

2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
....
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
....
3640
3641
3642
3643
3644
3645
3646
3647
3648
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
....
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
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
....
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
....
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915

3916
3917
3918
3919
3920
3921
3922
....
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

5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
....
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
....
5460
5461
5462
5463
5464
5465
5466

5467
5468
5469
5470
5471
5472
5473
....
5553
5554
5555
5556
5557
5558
5559

5560
5561
5562
5563
5564
5565
5566
....
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
....
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825

5826
5827
5828
5829
5830
5831
5832
....
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
....
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902

5903
5904
5905
5906
5907
5908
5909
....
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
....
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
....
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
....
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
....
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
....
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
....
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
....
6774
6775
6776
6777
6778
6779
6780
6781


6782
6783
6784
6785
6786
6787


6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
....
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
....
6864
6865
6866
6867
6868
6869
6870

6871
6872
6873

6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
....
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
....
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
7047
7048

7049
7050

7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
....
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
	| 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);

Changes to jni/tcl/generic/tclExecute.c.

6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
....
8227
8228
8229
8230
8231
8232
8233
























































































































8234
8235
8236
8237
8238
8239
8240
....
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
....
8779
8780
8781
8782
8783
8784
8785

8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
....
8856
8857
8858
8859
8860
8861
8862

8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
....
8969
8970
8971
8972
8973
8974
8975

8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
	if (GetNumberFromObj(NULL, OBJ_AT_TOS, &ptr1, &type1) != TCL_OK) {
	    type1 = 0;
	} else if (type1 == TCL_NUMBER_LONG) {
	    /* value is between LONG_MIN and LONG_MAX */
	    /* [string is integer] is -UINT_MAX to UINT_MAX range */
	    int i;

	    if (Tcl_GetIntFromObj(NULL, OBJ_AT_TOS, &i) != TCL_OK) {
		type1 = TCL_NUMBER_WIDE;
	    }
#ifndef TCL_WIDE_INT_IS_LONG
	} else if (type1 == TCL_NUMBER_WIDE) {
	    /* value is between WIDE_MIN and WIDE_MAX */
	    /* [string is wideinteger] is -UWIDE_MAX to UWIDE_MAX range */
	    int i;
	    if (Tcl_GetIntFromObj(NULL, OBJ_AT_TOS, &i) == TCL_OK) {
		type1 = TCL_NUMBER_LONG;
	    }
#endif
	} else if (type1 == TCL_NUMBER_BIG) {
	    /* value is an integer outside the WIDE_MIN to WIDE_MAX range */
	    /* [string is wideinteger] is -UWIDE_MAX to UWIDE_MAX range */
	    Tcl_WideInt w;

	    if (Tcl_GetWideIntFromObj(NULL, OBJ_AT_TOS, &w) == TCL_OK) {
		type1 = TCL_NUMBER_WIDE;
	    }
	}
	TclNewIntObj(objResultPtr, type1);
	TRACE(("\"%.20s\" => %d\n", O2S(OBJ_AT_TOS), type1));
	NEXT_INST_F(1, 1, 1);

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

    contextPtr->index = PTR2INT(data[2]);
    contextPtr->skip = PTR2INT(data[3]);
    contextPtr->oPtr->flags |= FILTER_HANDLING;
    return result;
}
 
























































































































/*
 *----------------------------------------------------------------------
 *
 * ExecuteExtendedBinaryMathOp, ExecuteExtendedUnaryMathOp --
 *
 *	These functions do advanced math for binary and unary operators
 *	respectively, so that the main TEBC code does not bear the cost of
................................................................................
    int type1, type2;
    ClientData ptr1, ptr2;
    double d1, d2, dResult;
    long l1, l2, lResult;
    Tcl_WideInt w1, w2, wResult;
    mp_int big1, big2, bigResult, bigRemainder;
    Tcl_Obj *objResultPtr;
    int invalid, numPos, zero;
    long shift;

    (void) GetNumberFromObj(NULL, valuePtr, &ptr1, &type1);
    (void) GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2);

    switch (opcode) {
    case INST_MOD:
................................................................................
#if (LONG_MAX == 0x7fffffff)
	    if (l2 - 2 < (long)MaxBase32Size
		    && l1 <= MaxBase32[l2 - 2]
		    && l1 >= -MaxBase32[l2 - 2]) {
		/*
		 * Small powers of 32-bit integers.
		 */


		lResult = l1 * l1;		/* b**2 */
		switch (l2) {
		case 2:
		    break;
		case 3:
		    lResult *= l1;		/* b**3 */
		    break;
		case 4:
		    lResult *= lResult;		/* b**4 */
		    break;
		case 5:
		    lResult *= lResult;		/* b**4 */
		    lResult *= l1;		/* b**5 */
		    break;
		case 6:
		    lResult *= l1;		/* b**3 */
		    lResult *= lResult;		/* b**6 */
		    break;
		case 7:
		    lResult *= l1;		/* b**3 */
		    lResult *= lResult;		/* b**6 */
		    lResult *= l1;		/* b**7 */
		    break;
		case 8:
		    lResult *= lResult;		/* b**4 */
		    lResult *= lResult;		/* b**8 */
		    break;
		}
		LONG_RESULT(lResult);
	    }

	    if (l1 - 3 >= 0 && l1 -2 < (long)Exp32IndexSize
		    && l2 - 2 < (long)(Exp32ValueSize + MaxBase32Size)) {
		base = Exp32Index[l1 - 3]
			+ (unsigned short) (l2 - 2 - MaxBase32Size);
................................................................................

	if (l2 - 2 < (long)MaxBase64Size
		&& w1 <=  MaxBase64[l2 - 2]
		&& w1 >= -MaxBase64[l2 - 2]) {
	    /*
	     * Small powers of integers whose result is wide.
	     */


	    wResult = w1 * w1;		/* b**2 */
	    switch (l2) {
	    case 2:
		break;
	    case 3:
		wResult *= l1;		/* b**3 */
		break;
	    case 4:
		wResult *= wResult;	/* b**4 */
		break;
	    case 5:
		wResult *= wResult;	/* b**4 */
		wResult *= w1;		/* b**5 */
		break;
	    case 6:
		wResult *= w1;		/* b**3 */
		wResult *= wResult;	/* b**6 */
		break;
	    case 7:
		wResult *= w1;		/* b**3 */
		wResult *= wResult;	/* b**6 */
		wResult *= w1;		/* b**7 */
		break;
	    case 8:
		wResult *= wResult;	/* b**4 */
		wResult *= wResult;	/* b**8 */
		break;
	    case 9:
		wResult *= wResult;	/* b**4 */
		wResult *= wResult;	/* b**8 */
		wResult *= w1;		/* b**9 */
		break;
	    case 10:
		wResult *= wResult;	/* b**4 */
		wResult *= w1;		/* b**5 */
		wResult *= wResult;	/* b**10 */
		break;
	    case 11:
		wResult *= wResult;	/* b**4 */
		wResult *= w1;		/* b**5 */
		wResult *= wResult;	/* b**10 */
		wResult *= w1;		/* b**11 */
		break;
	    case 12:
		wResult *= w1;		/* b**3 */
		wResult *= wResult;	/* b**6 */
		wResult *= wResult;	/* b**12 */
		break;
	    case 13:
		wResult *= w1;		/* b**3 */
		wResult *= wResult;	/* b**6 */
		wResult *= wResult;	/* b**12 */
		wResult *= w1;		/* b**13 */
		break;
	    case 14:
		wResult *= w1;		/* b**3 */
		wResult *= wResult;	/* b**6 */
		wResult *= w1;		/* b**7 */
		wResult *= wResult;	/* b**14 */
		break;
	    case 15:
		wResult *= w1;		/* b**3 */
		wResult *= wResult;	/* b**6 */
		wResult *= w1;		/* b**7 */
		wResult *= wResult;	/* b**14 */
		wResult *= w1;		/* b**15 */
		break;
	    case 16:
		wResult *= wResult;	/* b**4 */
		wResult *= wResult;	/* b**8 */
		wResult *= wResult;	/* b**16 */
		break;
	    }
	    WIDE_RESULT(wResult);
	}

	/*
	 * Handle cases of powers > 16 that still fit in a 64-bit word by
	 * doing table lookup.
	 */
................................................................................
		wResult = oddExponent ? -Exp64Value[base] : Exp64Value[base];
		WIDE_RESULT(wResult);
	    }
	}
#endif

    overflowExpon:

	Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
	if ((big2.used > 1)
#if DIGIT_BIT > 28
		    || ((big2.used == 1) && (big2.dp[0] >= (1<<28)))
#endif
	) {
	    mp_clear(&big2);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "exponent too large", -1));
	    return GENERAL_ARITHMETIC_ERROR;
	}
	Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
	mp_init(&bigResult);
	mp_expt_d(&big1, big2.dp[0], &bigResult);
	mp_clear(&big1);
	mp_clear(&big2);
	BIG_RESULT(&bigResult);
    }

    case INST_ADD:
    case INST_SUB:
    case INST_MULT:
    case INST_DIV:







|







|








|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
|
<
|
|
<
<
<






|

<







6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
....
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
....
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
....
8899
8900
8901
8902
8903
8904
8905
8906
8907




























8908
8909
8910
8911
8912
8913
8914
....
8949
8950
8951
8952
8953
8954
8955
8956
8957









































































8958
8959
8960
8961
8962
8963
8964
....
8990
8991
8992
8993
8994
8995
8996
8997
8998

8999
9000



9001
9002
9003
9004
9005
9006
9007
9008

9009
9010
9011
9012
9013
9014
9015
	if (GetNumberFromObj(NULL, OBJ_AT_TOS, &ptr1, &type1) != TCL_OK) {
	    type1 = 0;
	} else if (type1 == TCL_NUMBER_LONG) {
	    /* value is between LONG_MIN and LONG_MAX */
	    /* [string is integer] is -UINT_MAX to UINT_MAX range */
	    int i;

	    if (TclGetIntFromObj(NULL, OBJ_AT_TOS, &i) != TCL_OK) {
		type1 = TCL_NUMBER_WIDE;
	    }
#ifndef TCL_WIDE_INT_IS_LONG
	} else if (type1 == TCL_NUMBER_WIDE) {
	    /* value is between WIDE_MIN and WIDE_MAX */
	    /* [string is wideinteger] is -UWIDE_MAX to UWIDE_MAX range */
	    int i;
	    if (TclGetIntFromObj(NULL, OBJ_AT_TOS, &i) == TCL_OK) {
		type1 = TCL_NUMBER_LONG;
	    }
#endif
	} else if (type1 == TCL_NUMBER_BIG) {
	    /* value is an integer outside the WIDE_MIN to WIDE_MAX range */
	    /* [string is wideinteger] is -UWIDE_MAX to UWIDE_MAX range */
	    Tcl_WideInt w;

	    if (TclGetWideIntFromObj(NULL, OBJ_AT_TOS, &w) == TCL_OK) {
		type1 = TCL_NUMBER_WIDE;
	    }
	}
	TclNewIntObj(objResultPtr, type1);
	TRACE(("\"%.20s\" => %d\n", O2S(OBJ_AT_TOS), type1));
	NEXT_INST_F(1, 1, 1);

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

    contextPtr->index = PTR2INT(data[2]);
    contextPtr->skip = PTR2INT(data[3]);
    contextPtr->oPtr->flags |= FILTER_HANDLING;
    return result;
}
 
/*
 * LongPwrSmallExpon -- , WidePwrSmallExpon --
 *
 * Helpers to calculate small powers of integers whose result is long or wide.
 */
static inline long
LongPwrSmallExpon(long l1, long exponent) {

    long lResult;

    lResult = l1 * l1;		/* b**2 */
    switch (exponent) {
    case 2:
	break;
    case 3:
	lResult *= l1;		/* b**3 */
	break;
    case 4:
	lResult *= lResult;	/* b**4 */
	break;
    case 5:
	lResult *= lResult;	/* b**4 */
	lResult *= l1;		/* b**5 */
	break;
    case 6:
	lResult *= l1;		/* b**3 */
	lResult *= lResult;	/* b**6 */
	break;
    case 7:
	lResult *= l1;		/* b**3 */
	lResult *= lResult;	/* b**6 */
	lResult *= l1;		/* b**7 */
	break;
    case 8:
	lResult *= lResult;	/* b**4 */
	lResult *= lResult;	/* b**8 */
	break;
    }
    return lResult;    
}
static inline Tcl_WideInt
WidePwrSmallExpon(Tcl_WideInt w1, long exponent) {

    Tcl_WideInt wResult;

    wResult = w1 * w1;		/* b**2 */
    switch (exponent) {
    case 2:
	break;
    case 3:
	wResult *= w1;		/* b**3 */
	break;
    case 4:
	wResult *= wResult;	/* b**4 */
	break;
    case 5:
	wResult *= wResult;	/* b**4 */
	wResult *= w1;		/* b**5 */
	break;
    case 6:
	wResult *= w1;		/* b**3 */
	wResult *= wResult;	/* b**6 */
	break;
    case 7:
	wResult *= w1;		/* b**3 */
	wResult *= wResult;	/* b**6 */
	wResult *= w1;		/* b**7 */
	break;
    case 8:
	wResult *= wResult;	/* b**4 */
	wResult *= wResult;	/* b**8 */
	break;
    case 9:
	wResult *= wResult;	/* b**4 */
	wResult *= wResult;	/* b**8 */
	wResult *= w1;		/* b**9 */
	break;
    case 10:
	wResult *= wResult;	/* b**4 */
	wResult *= w1;		/* b**5 */
	wResult *= wResult;	/* b**10 */
	break;
    case 11:
	wResult *= wResult;	/* b**4 */
	wResult *= w1;		/* b**5 */
	wResult *= wResult;	/* b**10 */
	wResult *= w1;		/* b**11 */
	break;
    case 12:
	wResult *= w1;		/* b**3 */
	wResult *= wResult;	/* b**6 */
	wResult *= wResult;	/* b**12 */
	break;
    case 13:
	wResult *= w1;		/* b**3 */
	wResult *= wResult;	/* b**6 */
	wResult *= wResult;	/* b**12 */
	wResult *= w1;		/* b**13 */
	break;
    case 14:
	wResult *= w1;		/* b**3 */
	wResult *= wResult;	/* b**6 */
	wResult *= w1;		/* b**7 */
	wResult *= wResult;	/* b**14 */
	break;
    case 15:
	wResult *= w1;		/* b**3 */
	wResult *= wResult;	/* b**6 */
	wResult *= w1;		/* b**7 */
	wResult *= wResult;	/* b**14 */
	wResult *= w1;		/* b**15 */
	break;
    case 16:
	wResult *= wResult;	/* b**4 */
	wResult *= wResult;	/* b**8 */
	wResult *= wResult;	/* b**16 */
	break;
    }
    return wResult;
}
/*
 *----------------------------------------------------------------------
 *
 * ExecuteExtendedBinaryMathOp, ExecuteExtendedUnaryMathOp --
 *
 *	These functions do advanced math for binary and unary operators
 *	respectively, so that the main TEBC code does not bear the cost of
................................................................................
    int type1, type2;
    ClientData ptr1, ptr2;
    double d1, d2, dResult;
    long l1, l2, lResult;
    Tcl_WideInt w1, w2, wResult;
    mp_int big1, big2, bigResult, bigRemainder;
    Tcl_Obj *objResultPtr;
    int invalid, zero;
    long shift;

    (void) GetNumberFromObj(NULL, valuePtr, &ptr1, &type1);
    (void) GetNumberFromObj(NULL, value2Ptr, &ptr2, &type2);

    switch (opcode) {
    case INST_MOD:
................................................................................
#if (LONG_MAX == 0x7fffffff)
	    if (l2 - 2 < (long)MaxBase32Size
		    && l1 <= MaxBase32[l2 - 2]
		    && l1 >= -MaxBase32[l2 - 2]) {
		/*
		 * Small powers of 32-bit integers.
		 */
		lResult = LongPwrSmallExpon(l1, l2);





























		LONG_RESULT(lResult);
	    }

	    if (l1 - 3 >= 0 && l1 -2 < (long)Exp32IndexSize
		    && l2 - 2 < (long)(Exp32ValueSize + MaxBase32Size)) {
		base = Exp32Index[l1 - 3]
			+ (unsigned short) (l2 - 2 - MaxBase32Size);
................................................................................

	if (l2 - 2 < (long)MaxBase64Size
		&& w1 <=  MaxBase64[l2 - 2]
		&& w1 >= -MaxBase64[l2 - 2]) {
	    /*
	     * Small powers of integers whose result is wide.
	     */
	    wResult = WidePwrSmallExpon(w1, l2);










































































	    WIDE_RESULT(wResult);
	}

	/*
	 * Handle cases of powers > 16 that still fit in a 64-bit word by
	 * doing table lookup.
	 */
................................................................................
		wResult = oddExponent ? -Exp64Value[base] : Exp64Value[base];
		WIDE_RESULT(wResult);
	    }
	}
#endif

    overflowExpon:

	if ((TclGetWideIntFromObj(NULL, value2Ptr, &w2) != TCL_OK)

		|| (value2Ptr->typePtr != &tclIntType)
		|| (Tcl_WideUInt)w2 >= (1<<28)) {



	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "exponent too large", -1));
	    return GENERAL_ARITHMETIC_ERROR;
	}
	Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
	mp_init(&bigResult);
	mp_expt_d(&big1, w2, &bigResult);
	mp_clear(&big1);

	BIG_RESULT(&bigResult);
    }

    case INST_ADD:
    case INST_SUB:
    case INST_MULT:
    case INST_DIV:

Changes to jni/tcl/generic/tclTomMathInterface.c.

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    unsigned long v;
    mp_digit *p;

    /*
     * Allocate enough memory to hold the largest possible long
     */

    status = mp_init_size(a,
	    (CHAR_BIT * sizeof(long) + DIGIT_BIT - 1) / DIGIT_BIT);
    if (status != MP_OKAY) {
	Tcl_Panic("initialization failure in TclBNInitBignumFromLong");
    }

    /*
     * Convert arg to sign and magnitude.
     */
................................................................................
    int status;
    mp_digit *p;

    /*
     * Allocate enough memory to hold the largest possible Tcl_WideUInt.
     */

    status = mp_init_size(a,
	    (CHAR_BIT * sizeof(Tcl_WideUInt) + DIGIT_BIT - 1) / DIGIT_BIT);
    if (status != MP_OKAY) {
	Tcl_Panic("initialization failure in TclBNInitBignumFromWideUInt");
    }

    a->sign = 0;

    /*







|
<







 







|
<







115
116
117
118
119
120
121
122

123
124
125
126
127
128
129
...
201
202
203
204
205
206
207
208

209
210
211
212
213
214
215
    unsigned long v;
    mp_digit *p;

    /*
     * Allocate enough memory to hold the largest possible long
     */

    status = mp_init(a);

    if (status != MP_OKAY) {
	Tcl_Panic("initialization failure in TclBNInitBignumFromLong");
    }

    /*
     * Convert arg to sign and magnitude.
     */
................................................................................
    int status;
    mp_digit *p;

    /*
     * Allocate enough memory to hold the largest possible Tcl_WideUInt.
     */

    status = mp_init(a);

    if (status != MP_OKAY) {
	Tcl_Panic("initialization failure in TclBNInitBignumFromWideUInt");
    }

    a->sign = 0;

    /*

Changes to jni/tcl/libtommath/bn_mp_sqrt.c.

10
11
12
13
14
15
16



17
18
19
20
21
22
23
24
25

26
27
28
29
30
31
32
..
33
34
35
36
37
38
39


40
41
42
43
44
45
46
..
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
92
93
94
95
96
97
98
99

100
101
102

103





104
105
106
107
108
109
110
 * additional optimizations in place.
 *
 * SPDX-License-Identifier: Unlicense
 */

#ifndef NO_FLOATING_POINT
#include <math.h>



#endif

/* this function is less generic than mp_n_root, simpler and faster */
int mp_sqrt(const mp_int *arg, mp_int *ret)
{
   int res;
   mp_int t1, t2;
   int i, j, k;
#ifndef NO_FLOATING_POINT

   volatile double d;
   mp_digit dig;
#endif

   /* must be positive */
   if (arg->sign == MP_NEG) {
      return MP_VAL;
................................................................................
   }

   /* easy out */
   if (mp_iszero(arg) == MP_YES) {
      mp_zero(ret);
      return MP_OKAY;
   }



   i = (arg->used / 2) - 1;
   j = 2 * i;
   if ((res = mp_init_size(&t1, i+2)) != MP_OKAY) {
      return res;
   }

................................................................................
      goto E2;
   }

   for (k = 0; k < i; ++k) {
      t1.dp[k] = (mp_digit) 0;
   }

#ifndef NO_FLOATING_POINT

   /* Estimate the square root using the hardware floating point unit. */

   d = 0.0;
   for (k = arg->used-1; k >= j; --k) {
      d = ldexp(d, DIGIT_BIT) + (double)(arg->dp[k]);
   }

................................................................................
   } else {
      t1.used = i+1;
      t1.dp[i] = ((mp_digit) d) - 1;
   }

#else

   /* Estimate the square root as having 1 in the most significant place. */


   t1.used = i + 2;
   t1.dp[i+1] = (mp_digit) 1;

   t1.dp[i] = (mp_digit) 0;






#endif

   /* t1 > 0  */
   if ((res = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
      goto E1;
   }







>
>
>







<

>







 







>
>







 







<
<







 







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







10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
34
35
..
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
53
54
55
56
57
58
59


60
61
62
63
64
65
66
..
95
96
97
98
99
100
101
102
103
104


105
106
107
108
109
110
111
112
113
114
115
116
117
118
 * additional optimizations in place.
 *
 * SPDX-License-Identifier: Unlicense
 */

#ifndef NO_FLOATING_POINT
#include <math.h>
#if (DIGIT_BIT != 28) || (FLT_RADIX != 2) || (DBL_MANT_DIG != 53) || (DBL_MAX_EXP != 1024)
#define NO_FLOATING_POINT
#endif
#endif

/* this function is less generic than mp_n_root, simpler and faster */
int mp_sqrt(const mp_int *arg, mp_int *ret)
{
   int res;
   mp_int t1, t2;

#ifndef NO_FLOATING_POINT
   int i, j, k;
   volatile double d;
   mp_digit dig;
#endif

   /* must be positive */
   if (arg->sign == MP_NEG) {
      return MP_VAL;
................................................................................
   }

   /* easy out */
   if (mp_iszero(arg) == MP_YES) {
      mp_zero(ret);
      return MP_OKAY;
   }

#ifndef NO_FLOATING_POINT

   i = (arg->used / 2) - 1;
   j = 2 * i;
   if ((res = mp_init_size(&t1, i+2)) != MP_OKAY) {
      return res;
   }

................................................................................
      goto E2;
   }

   for (k = 0; k < i; ++k) {
      t1.dp[k] = (mp_digit) 0;
   }



   /* Estimate the square root using the hardware floating point unit. */

   d = 0.0;
   for (k = arg->used-1; k >= j; --k) {
      d = ldexp(d, DIGIT_BIT) + (double)(arg->dp[k]);
   }

................................................................................
   } else {
      t1.used = i+1;
      t1.dp[i] = ((mp_digit) d) - 1;
   }

#else

   if ((res = mp_init_copy(&t1, arg)) != MP_OKAY) {
      return res;
   }



   if ((res = mp_init(&t2)) != MP_OKAY) {
      goto E2;
   }

   /* First approx. (not very bad for large arg) */
   mp_rshd(&t1, t1.used/2);

#endif

   /* t1 > 0  */
   if ((res = mp_div(arg, &t1, &t2, NULL)) != MP_OKAY) {
      goto E1;
   }