Tk Source Code

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

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

Overview
Comment:Merged core-8-5-branch
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | tip-438
Files: files | file ages | folders
SHA1: a888e91124f5029107da81689b05454f84f24505
User & Date: fvogel 2015-12-21 12:12:06
Context
2015-12-26
20:52
[.text sync -command $cmd] schedules execution of $cmd by the event loop at idle time check-in: 86e88288 user: fvogel tags: tip-438
2015-12-21
12:12
Merged core-8-5-branch check-in: a888e911 user: fvogel tags: tip-438
2015-12-20
22:16
Test text-11a.41 now correctly written passes. check-in: 8213d743 user: fvogel tags: tip-438
2015-12-19
22:54
Fixed bug [793909] - Problem with nonexistent namespaces check-in: ab7e1a03 user: fvogel tags: core-8-5-branch
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to generic/tkEntry.c.

387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
...
676
677
678
679
680
681
682
683



684
685
686
687
688
689
690
...
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735



736
737
738
739
740
741
742
....
1092
1093
1094
1095
1096
1097
1098

1099
1100
1101
1102
1103
1104
1105
....
1294
1295
1296
1297
1298
1299
1300











1301
1302
1303
1304
1305
1306
1307
....
1312
1313
1314
1315
1316
1317
1318






1319
1320
1321
1322
1323
1324
1325
1326
....
1337
1338
1339
1340
1341
1342
1343






1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357



1358
1359
1360
1361
1362
1363
1364
1365
....
1986
1987
1988
1989
1990
1991
1992
1993

1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
....
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
....
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093

2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
....
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
....
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210

2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
....
2247
2248
2249
2250
2251
2252
2253













2254
2255
2256
2257
2258
2259
2260
....
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
....
3718
3719
3720
3721
3722
3723
3724
3725



3726
3727
3728
3729
3730
3731
3732
....
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796



3797
3798
3799
3800
3801
3802
3803
....
3997
3998
3999
4000
4001
4002
4003
4004


4005
4006
4007
4008
4009
4010



4011
4012
4013

4014
4015
4016
4017
4018
4019
4020
....
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
....
4178
4179
4180
4181
4182
4183
4184

4185
4186
4187
4188
4189
4190
4191
....
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
....
4270
4271
4272
4273
4274
4275
4276
4277
4278



4279
4280
4281
4282
4283
4284
4285
/*
 * Forward declarations for functions defined later in this file:
 */

static int		ConfigureEntry(Tcl_Interp *interp, Entry *entryPtr,
			    int objc, Tcl_Obj *const objv[], int flags);
static void		DeleteChars(Entry *entryPtr, int index, int count);
static void		DestroyEntry(char *memPtr);
static void		DisplayEntry(ClientData clientData);
static void		EntryBlinkProc(ClientData clientData);
static void		EntryCmdDeletedProc(ClientData clientData);
static void		EntryComputeGeometry(Entry *entryPtr);
static void		EntryEventProc(ClientData clientData,
			    XEvent *eventPtr);
................................................................................
static void		EntryUpdateScrollbar(Entry *entryPtr);
static int		EntryValidate(Entry *entryPtr, char *cmd);
static int		EntryValidateChange(Entry *entryPtr, char *change,
		const char *newStr, int index, int type);
static void		ExpandPercents(Entry *entryPtr, const char *before,
			    const char *change, const char *newStr, int index,
			    int type, Tcl_DString *dsPtr);
static void		EntryValueChanged(Entry *entryPtr,
			    const char *newValue);
static void		EntryVisibleRange(Entry *entryPtr,
			    double *firstPtr, double *lastPtr);
static int		EntryWidgetObjCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
			    Tcl_Obj *const objv[]);
static void		EntryWorldChanged(ClientData instanceData);
static int		GetEntryIndex(Tcl_Interp *interp, Entry *entryPtr,
			    char *string, int *indexPtr);
static void		InsertChars(Entry *entryPtr, int index, char *string);

/*
 * These forward declarations are the spinbox specific ones:
 */

static int		SpinboxWidgetObjCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
................................................................................
	    }
	} else {
	    result = ConfigureEntry(interp, entryPtr, objc-2, objv+2, 0);
	}
	break;

    case COMMAND_DELETE: {
	int first, last;

	if ((objc < 3) || (objc > 4)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&first) != TCL_OK) {
................................................................................
	if (objc == 3) {
	    last = first + 1;
	} else if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[3]),
		&last) != TCL_OK) {
	    goto error;
	}
	if ((last >= first) && (entryPtr->state == STATE_NORMAL)) {
	    DeleteChars(entryPtr, first, last - first);



	}
	break;
    }

    case COMMAND_GET:
	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
................................................................................
	    goto error;
	}
	Tcl_SetObjResult(interp, Tcl_NewIntObj(index));
	break;
    }

    case COMMAND_INSERT: {
	int index;

	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index text");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&index) != TCL_OK) {
	    goto error;
	}
	if (entryPtr->state == STATE_NORMAL) {
	    InsertChars(entryPtr, index, Tcl_GetString(objv[3]));



	}
	break;
    }

    case COMMAND_SCAN: {
	int x;
	char *minorCmd;
................................................................................
    char *oldValues = NULL;	/* lint initialization */
    char *oldFormat = NULL;	/* lint initialization */
    int error;
    int oldExport = 0;		/* lint initialization */
    int valuesChanged = 0;	/* lint initialization */
    double oldFrom = 0.0;	/* lint initialization */
    double oldTo = 0.0;		/* lint initialization */


    /*
     * Eliminate any existing trace on a variable monitored by the entry.
     */

    if ((entryPtr->textVarName != NULL)
	    && (entryPtr->flags & ENTRY_VAR_TRACED)) {
................................................................................
     */

    if (entryPtr->textVarName != NULL) {
	const char *value;

	value = Tcl_GetVar(interp, entryPtr->textVarName, TCL_GLOBAL_ONLY);
	if (value == NULL) {











	    EntryValueChanged(entryPtr, NULL);
	} else {
	    EntrySetValue(entryPtr, value);
	}
    }

    if (entryPtr->type == TK_SPINBOX) {
................................................................................

	    /*
	     * No check for error return, because there shouldn't be one given
	     * the check for valid list above.
	     */

	    Tcl_ListObjIndex(interp, sbPtr->listObj, 0, &objPtr);






	    EntryValueChanged(entryPtr, Tcl_GetString(objPtr));
	} else if ((sbPtr->valueStr == NULL)
		&& !DOUBLES_EQ(sbPtr->fromValue, sbPtr->toValue)
		&& (!DOUBLES_EQ(sbPtr->fromValue, oldFrom)
			|| !DOUBLES_EQ(sbPtr->toValue, oldTo))) {
	    /*
	     * If the valueStr is empty and -from && -to are specified, check
	     * to see if the current string is within the range. If not, it
................................................................................
		if (dvalue > sbPtr->toValue) {
		    dvalue = sbPtr->toValue;
		} else if (dvalue < sbPtr->fromValue) {
		    dvalue = sbPtr->fromValue;
		}
	    }
	    sprintf(sbPtr->formatBuf, sbPtr->valueFormat, dvalue);






	    EntryValueChanged(entryPtr, sbPtr->formatBuf);
	}
    }

    /*
     * Set up a trace on the variable's value after we've possibly constrained
     * the value according to new -from/-to values.
     */

    if ((entryPtr->textVarName != NULL)
	    && !(entryPtr->flags & ENTRY_VAR_TRACED)) {
	Tcl_TraceVar(interp, entryPtr->textVarName,
		TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
		EntryTextVarProc, (ClientData) entryPtr);



	entryPtr->flags |= ENTRY_VAR_TRACED;
    }

    EntryWorldChanged((ClientData) entryPtr);
    if (error) {
	Tcl_SetObjResult(interp, errorResult);
	Tcl_DecrRefCount(errorResult);
	return TCL_ERROR;
................................................................................
 *----------------------------------------------------------------------
 *
 * InsertChars --
 *
 *	Add new characters to an entry widget.
 *
 * Results:
 *	None.

 *
 * Side effects:
 *	New information gets added to entryPtr; it will be redisplayed soon,
 *	but not necessarily immediately.
 *
 *----------------------------------------------------------------------
 */

static void
InsertChars(
    Entry *entryPtr,		/* Entry that is to get the new elements. */
    int index,			/* Add the new elements before this character
				 * index. */
    char *value)		/* New characters to add (NULL-terminated
				 * string). */
{
................................................................................
    const char *string;
    char *newStr;

    string = entryPtr->string;
    byteIndex = Tcl_UtfAtIndex(string, index) - string;
    byteCount = strlen(value);
    if (byteCount == 0) {
	return;
    }

    newByteCount = entryPtr->numBytes + byteCount + 1;
    newStr = (char *) ckalloc((unsigned) newByteCount);
    memcpy(newStr, string, byteIndex);
    strcpy(newStr + byteIndex, value);
    strcpy(newStr + byteIndex + byteCount, string + byteIndex);

    if ((entryPtr->validate == VALIDATE_KEY ||
	    entryPtr->validate == VALIDATE_ALL) &&
	    EntryValidateChange(entryPtr, value, newStr, index,
		    VALIDATE_INSERT) != TCL_OK) {
	ckfree(newStr);
	return;
    }

    ckfree((char *)string);
    entryPtr->string = newStr;

    /*
     * The following construction is used because inserting improperly formed
................................................................................
    }
    if (entryPtr->leftIndex > index) {
	entryPtr->leftIndex += charsAdded;
    }
    if (entryPtr->insertPos >= index) {
	entryPtr->insertPos += charsAdded;
    }
    EntryValueChanged(entryPtr, NULL);
}
 
/*
 *----------------------------------------------------------------------
 *
 * DeleteChars --
 *
 *	Remove one or more characters from an entry widget.
 *
 * Results:
 *	None.

 *
 * Side effects:
 *	Memory gets freed, the entry gets modified and (eventually)
 *	redisplayed.
 *
 *----------------------------------------------------------------------
 */

static void
DeleteChars(
    Entry *entryPtr,		/* Entry widget to modify. */
    int index,			/* Index of first character to delete. */
    int count)			/* How many characters to delete. */
{
    int byteIndex, byteCount, newByteCount;
    const char *string;
    char *newStr, *toDelete;

    if ((index + count) > entryPtr->numChars) {
	count = entryPtr->numChars - index;
    }
    if (count <= 0) {
	return;
    }

    string = entryPtr->string;
    byteIndex = Tcl_UtfAtIndex(string, index) - string;
    byteCount = Tcl_UtfAtIndex(string + byteIndex, count) - (string+byteIndex);

    newByteCount = entryPtr->numBytes + 1 - byteCount;
................................................................................

    if ((entryPtr->validate == VALIDATE_KEY ||
	    entryPtr->validate == VALIDATE_ALL) &&
	    EntryValidateChange(entryPtr, toDelete, newStr, index,
		    VALIDATE_DELETE) != TCL_OK) {
	ckfree(newStr);
	ckfree(toDelete);
	return;
    }

    ckfree(toDelete);
    ckfree((char *)entryPtr->string);
    entryPtr->string = newStr;
    entryPtr->numChars -= count;
    entryPtr->numBytes -= byteCount;
................................................................................
    if (entryPtr->insertPos >= index) {
	if (entryPtr->insertPos >= (index + count)) {
	    entryPtr->insertPos -= count;
	} else {
	    entryPtr->insertPos = index;
	}
    }
    EntryValueChanged(entryPtr, NULL);
}
 
/*
 *----------------------------------------------------------------------
 *
 * EntryValueChanged --
 *
 *	This function is invoked when characters are inserted into an entry or
 *	deleted from it. It updates the entry's associated variable, if there
 *	is one, and does other bookkeeping such as arranging for redisplay.
 *
 * Results:
 *	None.

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

static void
EntryValueChanged(
    Entry *entryPtr,		/* Entry whose value just changed. */
    const char *newValue)	/* If this value is not NULL, we first force
				 * the value of the entry to this. */
{
    if (newValue != NULL) {
	EntrySetValue(entryPtr, newValue);
    }

    if (entryPtr->textVarName == NULL) {
	newValue = NULL;
    } else {
	newValue = Tcl_SetVar(entryPtr->interp, entryPtr->textVarName,
		entryPtr->string, TCL_GLOBAL_ONLY);
    }

    if ((newValue != NULL) && (strcmp(newValue, entryPtr->string) != 0)) {
	/*
	 * The value of the variable is different than what we asked for.
	 * This means that a trace on the variable modified it. In this case
	 * our trace function wasn't invoked since the modification came while
................................................................................
	 * Arrange for redisplay.
	 */

	entryPtr->flags |= UPDATE_SCROLLBAR;
	EntryComputeGeometry(entryPtr);
	EventuallyRedraw(entryPtr);
    }













}
 
/*
 *----------------------------------------------------------------------
 *
 * EntrySetValue --
 *
................................................................................
	    }
	} else {
	    result = ConfigureEntry(interp, entryPtr, objc-2, objv+2, 0);
	}
	break;

    case SB_CMD_DELETE: {
	int first, last;

	if ((objc < 3) || (objc > 4)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&first) != TCL_OK) {
................................................................................
	} else {
	    if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[3]),
		    &last) != TCL_OK) {
		goto error;
	    }
	}
	if ((last >= first) && (entryPtr->state == STATE_NORMAL)) {
	    DeleteChars(entryPtr, first, last - first);



	}
	break;
    }

    case SB_CMD_GET:
	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
................................................................................
	    goto error;
	}
	Tcl_SetObjResult(interp, Tcl_NewIntObj(index));
	break;
    }

    case SB_CMD_INSERT: {
	int index;

	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index text");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&index) != TCL_OK) {
	    goto error;
	}
	if (entryPtr->state == STATE_NORMAL) {
	    InsertChars(entryPtr, index, Tcl_GetString(objv[3]));



	}
	break;
    }

    case SB_CMD_INVOKE:
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "elemName");
................................................................................
		}
	    }
	    break;
	}
	break;
    }

    case SB_CMD_SET:


	if (objc > 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?string?");
	    goto error;
	}
	if (objc == 3) {
	    EntryValueChanged(entryPtr, Tcl_GetString(objv[2]));



	}
	Tcl_SetStringObj(Tcl_GetObjResult(interp), entryPtr->string, -1);
	break;


    case SB_CMD_VALIDATE: {
	int code;

	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
	    goto error;
................................................................................
 *	This function is invoked when the invoke method for the widget is
 *	called.
 *
 * Results:
 *	TCL_OK.
 *
 * Side effects:
 *	An background error condition may arise when invoking the callback.
 *	The widget value may change.
 *
 *--------------------------------------------------------------
 */

static int
SpinboxInvoke(
................................................................................
	type = "down";
	up = 0;
	break;
    default:
	return TCL_OK;
    }


    if (fabs(sbPtr->increment) > MIN_DBL_VAL) {
	if (sbPtr->listObj != NULL) {
	    Tcl_Obj *objPtr;

	    Tcl_ListObjIndex(interp, sbPtr->listObj, sbPtr->eIndex, &objPtr);
	    if (strcmp(Tcl_GetString(objPtr), entryPtr->string)) {
		/*
................................................................................
			sbPtr->eIndex = sbPtr->nElements-1;
		    } else {
			sbPtr->eIndex = 0;
		    }
		}
	    }
	    Tcl_ListObjIndex(interp, sbPtr->listObj, sbPtr->eIndex, &objPtr);
	    EntryValueChanged(entryPtr, Tcl_GetString(objPtr));
	} else if (!DOUBLES_EQ(sbPtr->fromValue, sbPtr->toValue)) {
	    double dvalue;

	    if (sscanf(entryPtr->string, "%lf", &dvalue) <= 0) {
		/*
		 * If the string doesn't scan as a double value, just
		 * use the -from value
................................................................................
		     * manipulated the value by hand.
		     */

		    dvalue = sbPtr->toValue;
		}
	    }
	    sprintf(sbPtr->formatBuf, sbPtr->valueFormat, dvalue);
	    EntryValueChanged(entryPtr, sbPtr->formatBuf);
	}



    }

    if (sbPtr->command != NULL) {
	Tcl_DStringInit(&script);
	ExpandPercents(entryPtr, sbPtr->command, type, "", 0,
		VALIDATE_BUTTON, &script);
	Tcl_DStringAppend(&script, "", 1);






|







 







|









|







 







|







 







|
>
>
>







 







|










|
>
>
>







 







>







 







>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
|







 







>
>
>
>
>
>











|


>
>
>
|







 







|
>








|







 







|













|







 







|










|
>








|













|







 







|







 







|












|
>







|













|







 







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







 







|







 







|
>
>
>







 







|










|
>
>
>







 







|
>
>





|
>
>
>



>







 







|







 







>







 







|







 







|

>
>
>







387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
...
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
...
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
....
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
....
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
....
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
....
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
....
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
....
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
....
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
....
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
....
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
....
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
....
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
....
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
....
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
....
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
....
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
....
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
....
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
....
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
/*
 * Forward declarations for functions defined later in this file:
 */

static int		ConfigureEntry(Tcl_Interp *interp, Entry *entryPtr,
			    int objc, Tcl_Obj *const objv[], int flags);
static int		DeleteChars(Entry *entryPtr, int index, int count);
static void		DestroyEntry(char *memPtr);
static void		DisplayEntry(ClientData clientData);
static void		EntryBlinkProc(ClientData clientData);
static void		EntryCmdDeletedProc(ClientData clientData);
static void		EntryComputeGeometry(Entry *entryPtr);
static void		EntryEventProc(ClientData clientData,
			    XEvent *eventPtr);
................................................................................
static void		EntryUpdateScrollbar(Entry *entryPtr);
static int		EntryValidate(Entry *entryPtr, char *cmd);
static int		EntryValidateChange(Entry *entryPtr, char *change,
		const char *newStr, int index, int type);
static void		ExpandPercents(Entry *entryPtr, const char *before,
			    const char *change, const char *newStr, int index,
			    int type, Tcl_DString *dsPtr);
static int		EntryValueChanged(Entry *entryPtr,
			    const char *newValue);
static void		EntryVisibleRange(Entry *entryPtr,
			    double *firstPtr, double *lastPtr);
static int		EntryWidgetObjCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
			    Tcl_Obj *const objv[]);
static void		EntryWorldChanged(ClientData instanceData);
static int		GetEntryIndex(Tcl_Interp *interp, Entry *entryPtr,
			    char *string, int *indexPtr);
static int		InsertChars(Entry *entryPtr, int index, char *string);

/*
 * These forward declarations are the spinbox specific ones:
 */

static int		SpinboxWidgetObjCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
................................................................................
	    }
	} else {
	    result = ConfigureEntry(interp, entryPtr, objc-2, objv+2, 0);
	}
	break;

    case COMMAND_DELETE: {
	int first, last, code;

	if ((objc < 3) || (objc > 4)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&first) != TCL_OK) {
................................................................................
	if (objc == 3) {
	    last = first + 1;
	} else if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[3]),
		&last) != TCL_OK) {
	    goto error;
	}
	if ((last >= first) && (entryPtr->state == STATE_NORMAL)) {
	    code = DeleteChars(entryPtr, first, last - first);
            if (code != TCL_OK) {
                goto error;
            }
	}
	break;
    }

    case COMMAND_GET:
	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
................................................................................
	    goto error;
	}
	Tcl_SetObjResult(interp, Tcl_NewIntObj(index));
	break;
    }

    case COMMAND_INSERT: {
	int index, code;

	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index text");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&index) != TCL_OK) {
	    goto error;
	}
	if (entryPtr->state == STATE_NORMAL) {
	    code = InsertChars(entryPtr, index, Tcl_GetString(objv[3]));
            if (code != TCL_OK) {
                goto error;
            }
	}
	break;
    }

    case COMMAND_SCAN: {
	int x;
	char *minorCmd;
................................................................................
    char *oldValues = NULL;	/* lint initialization */
    char *oldFormat = NULL;	/* lint initialization */
    int error;
    int oldExport = 0;		/* lint initialization */
    int valuesChanged = 0;	/* lint initialization */
    double oldFrom = 0.0;	/* lint initialization */
    double oldTo = 0.0;		/* lint initialization */
    int code;

    /*
     * Eliminate any existing trace on a variable monitored by the entry.
     */

    if ((entryPtr->textVarName != NULL)
	    && (entryPtr->flags & ENTRY_VAR_TRACED)) {
................................................................................
     */

    if (entryPtr->textVarName != NULL) {
	const char *value;

	value = Tcl_GetVar(interp, entryPtr->textVarName, TCL_GLOBAL_ONLY);
	if (value == NULL) {

            /*
             * Since any trace on the textvariable was eliminated above,
             * the only possible reason for EntryValueChanged to return
             * an error is that the textvariable lives in a namespace
             * that does not (yet) exist. Indeed, namespaces are not
             * automatically created as needed. Don't trap this error
             * here, better do it below when attempting to trace the
             * variable.
             */

	    EntryValueChanged(entryPtr, NULL);
	} else {
	    EntrySetValue(entryPtr, value);
	}
    }

    if (entryPtr->type == TK_SPINBOX) {
................................................................................

	    /*
	     * No check for error return, because there shouldn't be one given
	     * the check for valid list above.
	     */

	    Tcl_ListObjIndex(interp, sbPtr->listObj, 0, &objPtr);

            /*
	     * No check for error return here as well, because any possible
	     * error will be trapped below when attempting tracing.
	     */

            EntryValueChanged(entryPtr, Tcl_GetString(objPtr));
	} else if ((sbPtr->valueStr == NULL)
		&& !DOUBLES_EQ(sbPtr->fromValue, sbPtr->toValue)
		&& (!DOUBLES_EQ(sbPtr->fromValue, oldFrom)
			|| !DOUBLES_EQ(sbPtr->toValue, oldTo))) {
	    /*
	     * If the valueStr is empty and -from && -to are specified, check
	     * to see if the current string is within the range. If not, it
................................................................................
		if (dvalue > sbPtr->toValue) {
		    dvalue = sbPtr->toValue;
		} else if (dvalue < sbPtr->fromValue) {
		    dvalue = sbPtr->fromValue;
		}
	    }
	    sprintf(sbPtr->formatBuf, sbPtr->valueFormat, dvalue);

            /*
	     * No check for error return here as well, because any possible
	     * error will be trapped below when attempting tracing.
	     */

	    EntryValueChanged(entryPtr, sbPtr->formatBuf);
	}
    }

    /*
     * Set up a trace on the variable's value after we've possibly constrained
     * the value according to new -from/-to values.
     */

    if ((entryPtr->textVarName != NULL)
	    && !(entryPtr->flags & ENTRY_VAR_TRACED)) {
	code = Tcl_TraceVar(interp, entryPtr->textVarName,
		TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
		EntryTextVarProc, (ClientData) entryPtr);
        if (code != TCL_OK) {
            return TCL_ERROR;
        }
        entryPtr->flags |= ENTRY_VAR_TRACED;
    }

    EntryWorldChanged((ClientData) entryPtr);
    if (error) {
	Tcl_SetObjResult(interp, errorResult);
	Tcl_DecrRefCount(errorResult);
	return TCL_ERROR;
................................................................................
 *----------------------------------------------------------------------
 *
 * InsertChars --
 *
 *	Add new characters to an entry widget.
 *
 * Results:
 *	A standard Tcl result. If an error occurred then an error message is
 *	left in the interp's result.
 *
 * Side effects:
 *	New information gets added to entryPtr; it will be redisplayed soon,
 *	but not necessarily immediately.
 *
 *----------------------------------------------------------------------
 */

static int
InsertChars(
    Entry *entryPtr,		/* Entry that is to get the new elements. */
    int index,			/* Add the new elements before this character
				 * index. */
    char *value)		/* New characters to add (NULL-terminated
				 * string). */
{
................................................................................
    const char *string;
    char *newStr;

    string = entryPtr->string;
    byteIndex = Tcl_UtfAtIndex(string, index) - string;
    byteCount = strlen(value);
    if (byteCount == 0) {
	return TCL_OK;
    }

    newByteCount = entryPtr->numBytes + byteCount + 1;
    newStr = (char *) ckalloc((unsigned) newByteCount);
    memcpy(newStr, string, byteIndex);
    strcpy(newStr + byteIndex, value);
    strcpy(newStr + byteIndex + byteCount, string + byteIndex);

    if ((entryPtr->validate == VALIDATE_KEY ||
	    entryPtr->validate == VALIDATE_ALL) &&
	    EntryValidateChange(entryPtr, value, newStr, index,
		    VALIDATE_INSERT) != TCL_OK) {
	ckfree(newStr);
	return TCL_OK;
    }

    ckfree((char *)string);
    entryPtr->string = newStr;

    /*
     * The following construction is used because inserting improperly formed
................................................................................
    }
    if (entryPtr->leftIndex > index) {
	entryPtr->leftIndex += charsAdded;
    }
    if (entryPtr->insertPos >= index) {
	entryPtr->insertPos += charsAdded;
    }
    return EntryValueChanged(entryPtr, NULL);
}
 
/*
 *----------------------------------------------------------------------
 *
 * DeleteChars --
 *
 *	Remove one or more characters from an entry widget.
 *
 * Results:
 *	A standard Tcl result. If an error occurred then an error message is
 *	left in the interp's result.
 *
 * Side effects:
 *	Memory gets freed, the entry gets modified and (eventually)
 *	redisplayed.
 *
 *----------------------------------------------------------------------
 */

static int
DeleteChars(
    Entry *entryPtr,		/* Entry widget to modify. */
    int index,			/* Index of first character to delete. */
    int count)			/* How many characters to delete. */
{
    int byteIndex, byteCount, newByteCount;
    const char *string;
    char *newStr, *toDelete;

    if ((index + count) > entryPtr->numChars) {
	count = entryPtr->numChars - index;
    }
    if (count <= 0) {
	return TCL_OK;
    }

    string = entryPtr->string;
    byteIndex = Tcl_UtfAtIndex(string, index) - string;
    byteCount = Tcl_UtfAtIndex(string + byteIndex, count) - (string+byteIndex);

    newByteCount = entryPtr->numBytes + 1 - byteCount;
................................................................................

    if ((entryPtr->validate == VALIDATE_KEY ||
	    entryPtr->validate == VALIDATE_ALL) &&
	    EntryValidateChange(entryPtr, toDelete, newStr, index,
		    VALIDATE_DELETE) != TCL_OK) {
	ckfree(newStr);
	ckfree(toDelete);
	return TCL_OK;
    }

    ckfree(toDelete);
    ckfree((char *)entryPtr->string);
    entryPtr->string = newStr;
    entryPtr->numChars -= count;
    entryPtr->numBytes -= byteCount;
................................................................................
    if (entryPtr->insertPos >= index) {
	if (entryPtr->insertPos >= (index + count)) {
	    entryPtr->insertPos -= count;
	} else {
	    entryPtr->insertPos = index;
	}
    }
    return EntryValueChanged(entryPtr, NULL);
}
 
/*
 *----------------------------------------------------------------------
 *
 * EntryValueChanged --
 *
 *	This function is invoked when characters are inserted into an entry or
 *	deleted from it. It updates the entry's associated variable, if there
 *	is one, and does other bookkeeping such as arranging for redisplay.
 *
 * Results:
 *	A standard Tcl result. If an error occurred then an error message is
 *	left in the interp's result.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
EntryValueChanged(
    Entry *entryPtr,		/* Entry whose value just changed. */
    const char *newValue)	/* If this value is not NULL, we first force
				 * the value of the entry to this. */
{
    if (newValue != NULL) {
	EntrySetValue(entryPtr, newValue);
    }

    if (entryPtr->textVarName == NULL) {
	newValue = NULL;
    } else {
	newValue = Tcl_SetVar(entryPtr->interp, entryPtr->textVarName,
		entryPtr->string, TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG);
    }

    if ((newValue != NULL) && (strcmp(newValue, entryPtr->string) != 0)) {
	/*
	 * The value of the variable is different than what we asked for.
	 * This means that a trace on the variable modified it. In this case
	 * our trace function wasn't invoked since the modification came while
................................................................................
	 * Arrange for redisplay.
	 */

	entryPtr->flags |= UPDATE_SCROLLBAR;
	EntryComputeGeometry(entryPtr);
	EventuallyRedraw(entryPtr);
    }

    /*
     * An error may have happened when setting the textvariable in case there
     * is a trace on that variable and the trace proc triggered an error.
     * Another possibility is that the textvariable is in a namespace that
     * does not (yet) exist.
     * Signal this error.
     */

    if ((entryPtr->textVarName != NULL) && (newValue == NULL)) {
        return TCL_ERROR;
    }
    return TCL_OK;
}
 
/*
 *----------------------------------------------------------------------
 *
 * EntrySetValue --
 *
................................................................................
	    }
	} else {
	    result = ConfigureEntry(interp, entryPtr, objc-2, objv+2, 0);
	}
	break;

    case SB_CMD_DELETE: {
	int first, last, code;

	if ((objc < 3) || (objc > 4)) {
	    Tcl_WrongNumArgs(interp, 2, objv, "firstIndex ?lastIndex?");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&first) != TCL_OK) {
................................................................................
	} else {
	    if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[3]),
		    &last) != TCL_OK) {
		goto error;
	    }
	}
	if ((last >= first) && (entryPtr->state == STATE_NORMAL)) {
	    code = DeleteChars(entryPtr, first, last - first);
            if (code != TCL_OK) {
                goto error;
            }
	}
	break;
    }

    case SB_CMD_GET:
	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
................................................................................
	    goto error;
	}
	Tcl_SetObjResult(interp, Tcl_NewIntObj(index));
	break;
    }

    case SB_CMD_INSERT: {
	int index, code;

	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index text");
	    goto error;
	}
	if (GetEntryIndex(interp, entryPtr, Tcl_GetString(objv[2]),
		&index) != TCL_OK) {
	    goto error;
	}
	if (entryPtr->state == STATE_NORMAL) {
	    code = InsertChars(entryPtr, index, Tcl_GetString(objv[3]));
            if (code != TCL_OK) {
                goto error;
            }
	}
	break;
    }

    case SB_CMD_INVOKE:
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "elemName");
................................................................................
		}
	    }
	    break;
	}
	break;
    }

    case SB_CMD_SET: {
	int code = TCL_OK;

	if (objc > 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?string?");
	    goto error;
	}
	if (objc == 3) {
	    code = EntryValueChanged(entryPtr, Tcl_GetString(objv[2]));
            if (code != TCL_OK) {
                goto error;
            }
	}
	Tcl_SetStringObj(Tcl_GetObjResult(interp), entryPtr->string, -1);
	break;
    }

    case SB_CMD_VALIDATE: {
	int code;

	if (objc != 2) {
	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
	    goto error;
................................................................................
 *	This function is invoked when the invoke method for the widget is
 *	called.
 *
 * Results:
 *	TCL_OK.
 *
 * Side effects:
 *	A background error condition may arise when invoking the callback.
 *	The widget value may change.
 *
 *--------------------------------------------------------------
 */

static int
SpinboxInvoke(
................................................................................
	type = "down";
	up = 0;
	break;
    default:
	return TCL_OK;
    }

    code = TCL_OK;
    if (fabs(sbPtr->increment) > MIN_DBL_VAL) {
	if (sbPtr->listObj != NULL) {
	    Tcl_Obj *objPtr;

	    Tcl_ListObjIndex(interp, sbPtr->listObj, sbPtr->eIndex, &objPtr);
	    if (strcmp(Tcl_GetString(objPtr), entryPtr->string)) {
		/*
................................................................................
			sbPtr->eIndex = sbPtr->nElements-1;
		    } else {
			sbPtr->eIndex = 0;
		    }
		}
	    }
	    Tcl_ListObjIndex(interp, sbPtr->listObj, sbPtr->eIndex, &objPtr);
	    code = EntryValueChanged(entryPtr, Tcl_GetString(objPtr));
	} else if (!DOUBLES_EQ(sbPtr->fromValue, sbPtr->toValue)) {
	    double dvalue;

	    if (sscanf(entryPtr->string, "%lf", &dvalue) <= 0) {
		/*
		 * If the string doesn't scan as a double value, just
		 * use the -from value
................................................................................
		     * manipulated the value by hand.
		     */

		    dvalue = sbPtr->toValue;
		}
	    }
	    sprintf(sbPtr->formatBuf, sbPtr->valueFormat, dvalue);
	    code = EntryValueChanged(entryPtr, sbPtr->formatBuf);
	}
    }
    if (code != TCL_OK) {
        return TCL_ERROR;
    }

    if (sbPtr->command != NULL) {
	Tcl_DStringInit(&script);
	ExpandPercents(entryPtr, sbPtr->command, type, "", 0,
		VALIDATE_BUTTON, &script);
	Tcl_DStringAppend(&script, "", 1);

Changes to macosx/README.

382
383
384
385
386
387
388





























































If you used non-default install locations for Tcl.framework, specify them as
make overrides to the tk/macosx GNUmakefile, e.g.
	make -C tk${ver}/macosx \
	    TCL_FRAMEWORK_DIR=$HOME/Library/Frameworks TCLSH_DIR=$HOME/usr/bin
	sudo make -C tk${ver}/macosx install \
	    TCL_FRAMEWORK_DIR=$HOME/Library/Frameworks TCLSH_DIR=$HOME/usr/bin
The Makefile variables TCL_FRAMEWORK_DIR and TCLSH_DIR were added with Tk 8.4.3.



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
If you used non-default install locations for Tcl.framework, specify them as
make overrides to the tk/macosx GNUmakefile, e.g.
	make -C tk${ver}/macosx \
	    TCL_FRAMEWORK_DIR=$HOME/Library/Frameworks TCLSH_DIR=$HOME/usr/bin
	sudo make -C tk${ver}/macosx install \
	    TCL_FRAMEWORK_DIR=$HOME/Library/Frameworks TCLSH_DIR=$HOME/usr/bin
The Makefile variables TCL_FRAMEWORK_DIR and TCLSH_DIR were added with Tk 8.4.3.

4. About the event loop in Tk for Mac OSX
-----------------------------------------

The main program in a typical OSX application looks like this (see *)

    void NSApplicationMain(int argc, char *argv[]) {
        [NSApplication sharedApplication];
        [NSBundle loadNibNamed:@"myMain" owner:NSApp];
        [NSApp run];
    }

The run method implements the event loop for the application.  There
are three key steps in the run method.  First it calls 
[NSApp finishLaunching], which creates the bouncing application icon
and does other mysterious things. Second it creates an
NSAutoreleasePool.  Third, it starts an event loop which drains the
NSAutoreleasePool every time the queue is empty, and replaces the
drained pool with a new one.  This third step is essential to
preventing memory leaks, since the internal methods of Appkit objects
all assume that an autorelease pool is in scope and will be drained
when the event processing cycle ends.

Mac OSX Tk does not call the [NSApp run] method at all.  Instead it
uses the event loop built in to Tk.  So we must take care to replicate
the important features of the method ourselves.  Here is how this
works in outline.

We add a private NSAUtoreleasePool* property to our subclass of
NSApplication.  (The subclass is called TKApplication but can be
referenced with the global variable NSApp).  The TkpInit
function calls [NSApp _setup] which initializes this property by
creating an NSAutoreleasePool. A bit later on, TkpInit calls
[NSAPP _setupEventLoop] which in turn calls the
[NSApp finishLaunching] method.

Each time that Tcl processes an event in its queue, it calls a
platform specific function which, in the case of Mac OSX, is named
TkMacOSXEventsCheckProc.  In the unix implementations of Tk, including
the Mac OSX version, this function collects events from an "event
source", and transfers them to the Tcl event queue.  In Mac OSX the
event source is the NSApplication event queue.  Each NSEvent is
converted to a Tcl event which is added to the Tcl event queue.  The
NSEvent is also passed to [NSApp sendevent], which sends the event on
to the application's NSWindows, which send it to their NSViews, etc.
Since the CheckProc function gets called for every Tk event, it is an
appropriate place to drain the main NSAutoreleasePool and replace it
with a new pool.  This is done by calling the method
[NSApp _resetAutoreleasePool], where _resetAutoreleasePool is a method
which we define for the subclass TKApplication.

One minor caveat is that there are several steps of the Tk
initialization which precede the call to TkpInit.  Notably, the font
package is initialized first.  Since there is no NSAUtoreleasePool in
scope prior to calling TkpInit, the functions called in these
preliminary stages need to create and drain their own
NSAutoreleasePools whenever they call methods of Appkit objects
(e.g. NSFont).

* https://developer.apple.com/library/mac/documentation/Cocoa/\
Reference/ApplicationKit/Classes/NSApplication_Class

Changes to macosx/tkMacOSXDraw.c.

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
...
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
....
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
....
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
....
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
....
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
....
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
....
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
....
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
....
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
	unsigned int height)
{
    MacDrawable *mac_drawable = (MacDrawable *) drawable;
    CGContextRef cg_context=NULL;
    CGImageRef cg_image=NULL, sub_cg_image=NULL;
    NSBitmapImageRep *bitmap_rep=NULL;
    NSView *view=NULL;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    if ( mac_drawable->flags & TK_IS_PIXMAP ) {
	/*
	   This means that the MacDrawable is functioning as a Tk Pixmap, so its view
	   field is NULL.
	*/
	cg_context = GetCGContextForDrawable(drawable);
	CGRect image_rect = CGRectMake(x, y, width, height);
................................................................................
	} else {
	    TkMacOSXDbgMsg("Could not lock focus on view.");
	}

    } else {
	TkMacOSXDbgMsg("Invalid source drawable");
    }
    [pool drain];
    return bitmap_rep;
}
 
/*
 *----------------------------------------------------------------------
 *
 * XCopyArea --
................................................................................
    int useCG, /* advisory only ! */
    TkMacOSXDrawingContext *dcPtr)
{
    MacDrawable *macDraw = ((MacDrawable*)d);
    int dontDraw = 0, isWin = 0;
    TkMacOSXDrawingContext dc = {};
    CGRect clipBounds;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    dc.clipRgn = TkMacOSXGetClipRgn(d);
    if (!dontDraw) {
	ClipToGC(d, gc, &dc.clipRgn);
	dontDraw = dc.clipRgn ? HIShapeIsEmpty(dc.clipRgn) : 0;
    }
    if (dontDraw) {
................................................................................
    }
end:
    if (dontDraw && dc.clipRgn) {
	CFRelease(dc.clipRgn);
	dc.clipRgn = NULL;
    }
    *dcPtr = dc;
    [pool drain];
    return !dontDraw;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXRestoreDrawingContext --
................................................................................
 *----------------------------------------------------------------------
 */

void
TkMacOSXRestoreDrawingContext(
    TkMacOSXDrawingContext *dcPtr)
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    if (dcPtr->context) {
	CGContextSynchronize(dcPtr->context);
	[[dcPtr->view window] setViewsNeedDisplay:YES];
	[[dcPtr->view window] enableFlushWindow];
	if (dcPtr->focusLocked) {
	    [dcPtr->view unlockFocus];
	} else {
................................................................................
    }
    if (dcPtr->clipRgn) {
	CFRelease(dcPtr->clipRgn);
    }
#ifdef TK_MAC_DEBUG
    bzero(dcPtr, sizeof(TkMacOSXDrawingContext));
#endif /* TK_MAC_DEBUG */
    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetClipRgn --
 *
................................................................................

HIShapeRef
TkMacOSXGetClipRgn(
    Drawable drawable)		/* Drawable. */
{
    MacDrawable *macDraw = (MacDrawable *) drawable;
    HIShapeRef clipRgn = NULL;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    
    if (macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(macDraw->winPtr);
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s", macDraw->winPtr->pathName);
	NSView *view = TkMacOSXDrawableView(macDraw);
	if ([view lockFocusIfCanDraw]) {
................................................................................
    }

    if (macDraw->drawRgn) {
	clipRgn = HIShapeCreateCopy(macDraw->drawRgn);
    } else if (macDraw->visRgn) {
	clipRgn = HIShapeCreateCopy(macDraw->visRgn);
    }
    [pool drain];
    return clipRgn;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetUpClippingRgn --
................................................................................
    Display *display,
    Drawable d,
    int x, int y,
    int width, int height)
{
    MacDrawable *macDraw = (MacDrawable *) d;
    NSView *view = TkMacOSXDrawableView(macDraw);
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    
    if (macDraw->drawRgn) {
	CFRelease(macDraw->drawRgn);
	macDraw->drawRgn = NULL;
    }

    if (width >= 0 && height >= 0) {
................................................................................
	}
    } else {
	if (view && (macDraw->flags & TK_FOCUSED_VIEW)) {
	    [view unlockFocus];
	    macDraw->flags &= ~TK_FOCUSED_VIEW;
	}
    }
    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * ClipToGC --
 *






<







 







<







 







<







 







<







 







<







 







<







 







<







 







<







 







<







 







<







134
135
136
137
138
139
140

141
142
143
144
145
146
147
...
170
171
172
173
174
175
176

177
178
179
180
181
182
183
....
1630
1631
1632
1633
1634
1635
1636

1637
1638
1639
1640
1641
1642
1643
....
1760
1761
1762
1763
1764
1765
1766

1767
1768
1769
1770
1771
1772
1773
....
1783
1784
1785
1786
1787
1788
1789

1790
1791
1792
1793
1794
1795
1796
....
1799
1800
1801
1802
1803
1804
1805

1806
1807
1808
1809
1810
1811
1812
....
1824
1825
1826
1827
1828
1829
1830

1831
1832
1833
1834
1835
1836
1837
....
1849
1850
1851
1852
1853
1854
1855

1856
1857
1858
1859
1860
1861
1862
....
1901
1902
1903
1904
1905
1906
1907

1908
1909
1910
1911
1912
1913
1914
....
1934
1935
1936
1937
1938
1939
1940

1941
1942
1943
1944
1945
1946
1947
	unsigned int height)
{
    MacDrawable *mac_drawable = (MacDrawable *) drawable;
    CGContextRef cg_context=NULL;
    CGImageRef cg_image=NULL, sub_cg_image=NULL;
    NSBitmapImageRep *bitmap_rep=NULL;
    NSView *view=NULL;

    if ( mac_drawable->flags & TK_IS_PIXMAP ) {
	/*
	   This means that the MacDrawable is functioning as a Tk Pixmap, so its view
	   field is NULL.
	*/
	cg_context = GetCGContextForDrawable(drawable);
	CGRect image_rect = CGRectMake(x, y, width, height);
................................................................................
	} else {
	    TkMacOSXDbgMsg("Could not lock focus on view.");
	}

    } else {
	TkMacOSXDbgMsg("Invalid source drawable");
    }

    return bitmap_rep;
}
 
/*
 *----------------------------------------------------------------------
 *
 * XCopyArea --
................................................................................
    int useCG, /* advisory only ! */
    TkMacOSXDrawingContext *dcPtr)
{
    MacDrawable *macDraw = ((MacDrawable*)d);
    int dontDraw = 0, isWin = 0;
    TkMacOSXDrawingContext dc = {};
    CGRect clipBounds;


    dc.clipRgn = TkMacOSXGetClipRgn(d);
    if (!dontDraw) {
	ClipToGC(d, gc, &dc.clipRgn);
	dontDraw = dc.clipRgn ? HIShapeIsEmpty(dc.clipRgn) : 0;
    }
    if (dontDraw) {
................................................................................
    }
end:
    if (dontDraw && dc.clipRgn) {
	CFRelease(dc.clipRgn);
	dc.clipRgn = NULL;
    }
    *dcPtr = dc;

    return !dontDraw;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXRestoreDrawingContext --
................................................................................
 *----------------------------------------------------------------------
 */

void
TkMacOSXRestoreDrawingContext(
    TkMacOSXDrawingContext *dcPtr)
{

    if (dcPtr->context) {
	CGContextSynchronize(dcPtr->context);
	[[dcPtr->view window] setViewsNeedDisplay:YES];
	[[dcPtr->view window] enableFlushWindow];
	if (dcPtr->focusLocked) {
	    [dcPtr->view unlockFocus];
	} else {
................................................................................
    }
    if (dcPtr->clipRgn) {
	CFRelease(dcPtr->clipRgn);
    }
#ifdef TK_MAC_DEBUG
    bzero(dcPtr, sizeof(TkMacOSXDrawingContext));
#endif /* TK_MAC_DEBUG */

}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetClipRgn --
 *
................................................................................

HIShapeRef
TkMacOSXGetClipRgn(
    Drawable drawable)		/* Drawable. */
{
    MacDrawable *macDraw = (MacDrawable *) drawable;
    HIShapeRef clipRgn = NULL;

    
    if (macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
	TkMacOSXUpdateClipRgn(macDraw->winPtr);
#ifdef TK_MAC_DEBUG_DRAWING
	TkMacOSXDbgMsg("%s", macDraw->winPtr->pathName);
	NSView *view = TkMacOSXDrawableView(macDraw);
	if ([view lockFocusIfCanDraw]) {
................................................................................
    }

    if (macDraw->drawRgn) {
	clipRgn = HIShapeCreateCopy(macDraw->drawRgn);
    } else if (macDraw->visRgn) {
	clipRgn = HIShapeCreateCopy(macDraw->visRgn);
    }

    return clipRgn;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXSetUpClippingRgn --
................................................................................
    Display *display,
    Drawable d,
    int x, int y,
    int width, int height)
{
    MacDrawable *macDraw = (MacDrawable *) d;
    NSView *view = TkMacOSXDrawableView(macDraw);

    
    if (macDraw->drawRgn) {
	CFRelease(macDraw->drawRgn);
	macDraw->drawRgn = NULL;
    }

    if (width >= 0 && height >= 0) {
................................................................................
	}
    } else {
	if (view && (macDraw->flags & TK_FOCUSED_VIEW)) {
	    [view unlockFocus];
	    macDraw->flags &= ~TK_FOCUSED_VIEW;
	}
    }

}
 
/*
 *----------------------------------------------------------------------
 *
 * ClipToGC --
 *

Changes to macosx/tkMacOSXEvent.c.

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
 *	Flushes all visible Cocoa windows
 *
 *----------------------------------------------------------------------
 */
MODULE_SCOPE void
TkMacOSXFlushWindows(void)
{
    /* This can be called from outside the Appkit event loop,
     * so it needs its own AutoreleasePool.
     */
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    NSArray *macWindows = [NSApp orderedWindows];

    for (NSWindow *w in macWindows) {
	if (TkMacOSXGetXWindow(w)) {
	    [w flushWindow];
	}
    }
    [pool drain];
}
 
/*
 * Local Variables:
 * mode: objc
 * c-basic-offset: 4
 * fill-column: 79
 * coding: utf-8
 * End:
 */






<
<
<
<







<










122
123
124
125
126
127
128




129
130
131
132
133
134
135

136
137
138
139
140
141
142
143
144
145
 *	Flushes all visible Cocoa windows
 *
 *----------------------------------------------------------------------
 */
MODULE_SCOPE void
TkMacOSXFlushWindows(void)
{




    NSArray *macWindows = [NSApp orderedWindows];

    for (NSWindow *w in macWindows) {
	if (TkMacOSXGetXWindow(w)) {
	    [w flushWindow];
	}
    }

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

Changes to macosx/tkMacOSXFont.c.

206
207
208
209
210
211
212

213
214
215
216
217
218
219
...
367
368
369
370
371
372
373

374
375
376
377
378
379
380
...
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
...
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
	nsFont = [NSFont fontWithName:family size:size];
    }
    if (!nsFont && fallbackToDefault) {
	nsFont = [fm convertFont:defaultFont toFamily:family];
	nsFont = [fm convertFont:nsFont toSize:size];
	nsFont = [fm convertFont:nsFont toHaveTrait:traits];
    }

    #undef defaultFont
    return nsFont;
}
 
/*
 *---------------------------------------------------------------------------
 *
................................................................................
{
    Tcl_Interp *interp = mainPtr->interp;
    Tk_Window tkwin = (Tk_Window) mainPtr->winPtr;
    const struct SystemFontMapEntry *systemFont = systemFontMap;
    NSFont *nsFont;
    TkFontAttributes fa;
    NSMutableCharacterSet *cs;

    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    /* force this for now */
    if (!mainPtr->winPtr->mainPtr) {
	mainPtr->winPtr->mainPtr = mainPtr;
    }
    while (systemFont->systemName) {
................................................................................
	    nsFont = FindNSFont(*aliases++, traits, weight, points, 0);
	}
    }
    if (!nsFont) {
	nsFont = FindNSFont(faPtr->family, traits, weight, points, 1);
    }
    if (!nsFont) {
	Tcl_Panic("Could not deternmine NSFont from TkFontAttributes");
    }
    if (tkFontPtr == NULL) {
	fontPtr = (MacFont *) ckalloc(sizeof(MacFont));
    } else {
	fontPtr = (MacFont *) tkFontPtr;
	TkpDeleteFont(tkFontPtr);
    }
................................................................................
    Tk_Window tkwin,		/* Window on the font's display */
    Tk_Font tkfont,		/* Font to query */
    Tcl_UniChar c,		/* Character of interest */
    TkFontAttributes* faPtr)	/* Output: Font attributes */
{
    MacFont *fontPtr = (MacFont *) tkfont;
    NSFont *nsFont = fontPtr->nsFont;

    *faPtr = fontPtr->font.fa;
    if (nsFont && ![[nsFont coveredCharacterSet] characterIsMember:c]) {
	UTF16Char ch = c;

	nsFont = [nsFont bestMatchingFontForCharacters:&ch
		length:1 attributes:nil actualCoveredLength:NULL];
	if (nsFont) {






>







 







>







 







|







 







<







206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
...
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
...
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
...
673
674
675
676
677
678
679

680
681
682
683
684
685
686
	nsFont = [NSFont fontWithName:family size:size];
    }
    if (!nsFont && fallbackToDefault) {
	nsFont = [fm convertFont:defaultFont toFamily:family];
	nsFont = [fm convertFont:nsFont toSize:size];
	nsFont = [fm convertFont:nsFont toHaveTrait:traits];
    }
    [nsFont retain];
    #undef defaultFont
    return nsFont;
}
 
/*
 *---------------------------------------------------------------------------
 *
................................................................................
{
    Tcl_Interp *interp = mainPtr->interp;
    Tk_Window tkwin = (Tk_Window) mainPtr->winPtr;
    const struct SystemFontMapEntry *systemFont = systemFontMap;
    NSFont *nsFont;
    TkFontAttributes fa;
    NSMutableCharacterSet *cs;
    /* Since we called before TkpInit, we need our own autorelease pool. */
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    /* force this for now */
    if (!mainPtr->winPtr->mainPtr) {
	mainPtr->winPtr->mainPtr = mainPtr;
    }
    while (systemFont->systemName) {
................................................................................
	    nsFont = FindNSFont(*aliases++, traits, weight, points, 0);
	}
    }
    if (!nsFont) {
	nsFont = FindNSFont(faPtr->family, traits, weight, points, 1);
    }
    if (!nsFont) {
	Tcl_Panic("Could not determine NSFont from TkFontAttributes");
    }
    if (tkFontPtr == NULL) {
	fontPtr = (MacFont *) ckalloc(sizeof(MacFont));
    } else {
	fontPtr = (MacFont *) tkFontPtr;
	TkpDeleteFont(tkFontPtr);
    }
................................................................................
    Tk_Window tkwin,		/* Window on the font's display */
    Tk_Font tkfont,		/* Font to query */
    Tcl_UniChar c,		/* Character of interest */
    TkFontAttributes* faPtr)	/* Output: Font attributes */
{
    MacFont *fontPtr = (MacFont *) tkfont;
    NSFont *nsFont = fontPtr->nsFont;

    *faPtr = fontPtr->font.fa;
    if (nsFont && ![[nsFont coveredCharacterSet] characterIsMember:c]) {
	UTF16Char ch = c;

	nsFont = [nsFont bestMatchingFontForCharacters:&ch
		length:1 attributes:nil actualCoveredLength:NULL];
	if (nsFont) {

Changes to macosx/tkMacOSXInit.c.

55
56
57
58
59
60
61



62
63
64







65
66
67
68
69
70
71
..
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
...
127
128
129
130
131
132
133


134
135
136
137
138
139
140
...
153
154
155
156
157
158
159

160
161
162
163
164
165
166
167

168
169
170
171
172
173
174
...
238
239
240
241
242
243
244

245
246
247
248
249
250
251
252
253

254

255
256
257
258
259
260
261
...
304
305
306
307
308
309
310


311
312
313
314
315
316

317
318
319
320
321
322
323
...
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
...
491
492
493
494
495
496
497

498
499
500
501
502
503
504
@end

@interface TKApplication(TKMenus)
- (void)_setupMenus;
@end

@implementation TKApplication



@end

@implementation TKApplication(TKInit)







#ifdef TK_MAC_DEBUG_NOTIFICATIONS
- (void)_postedNotification:(NSNotification *)notification {
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
}
#endif
- (void)_setupApplicationNotifications {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
................................................................................
    observe(NSTextInputContextKeyboardSelectionDidChangeNotification, keyboardChanged:);
#undef observe
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
    CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(), NULL, &keyboardChanged, kTISNotifySelectedKeyboardInputSourceChanged, NULL, CFNotificationSuspensionBehaviorCoalesce);
#endif
}
- (void)_setupEventLoop {

    /*Remove private API calls here.*/

    [self finishLaunching];
    [self setWindowsNeedUpdate:YES];

}
- (void)_setup:(Tcl_Interp *)interp {
    _eventInterp = interp;


    _defaultMainMenu = nil;

    [self _setupMenus];
    [self setDelegate:self];
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    [[NSNotificationCenter defaultCenter] addObserver:self
	    selector:@selector(_postedNotification:) name:nil object:nil];
#endif
    [self _setupWindowNotifications];
    [self _setupApplicationNotifications];

}
- (NSString *)tkFrameworkImagePath:(NSString*)image {
    NSString *path = nil;

    if (tkLibPath[0] != '\0') {
	path = [[NSBundle bundleWithPath:[[NSString stringWithUTF8String:
		tkLibPath] stringByAppendingString:@"/../.."]]
		pathForImageResource:image];
    }
    if (!path) {
	const char *tk_library = Tcl_GetVar2(_eventInterp, "tk_library", NULL,
................................................................................
	path = [[NSString stringWithUTF8String:getenv("TK_SRCROOT")]
		stringByAppendingFormat:@"/macosx/%@", image];
	if (![[NSFileManager defaultManager] isReadableFileAtPath:path]) {
	    path = nil;
	}
    }
#endif


    return path;
}
@end

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

static void
SetApplicationIcon(
    ClientData clientData)
{

    NSString *path = [NSApp tkFrameworkImagePath:@"Tk.icns"];
    if (path) {
	NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
	if (image) {
	    [NSApp setApplicationIconImage:image];
	    [image release];
	}
    }

}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpInit --
 *
................................................................................
	if (Tcl_MacOSXOpenVersionedBundleResources(interp,
		"com.tcltk.tklibrary", TK_FRAMEWORK_VERSION, 0, PATH_MAX,
		tkLibPath) != TCL_OK) {
	    TkMacOSXDbgMsg("Tcl_MacOSXOpenVersionedBundleResources failed");
	}
#endif


	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	[[NSUserDefaults standardUserDefaults] registerDefaults:
		[NSDictionary dictionaryWithObjectsAndKeys:
		[NSNumber numberWithBool:YES],
		@"_NSCanWrapButtonTitles",
		[NSNumber numberWithInt:-1],
		@"NSStringDrawingTypesetterBehavior",
		nil]];
	[TKApplication sharedApplication];

	[NSApp _setup:interp];


	/* Check whether we are a bundled executable: */
	bundleRef = CFBundleGetMainBundle();
	if (bundleRef) {
	    bundleUrl = CFBundleCopyBundleURL(bundleRef);
	}
	if (bundleUrl) {
................................................................................
	     * Set application icon to generic Tk icon, do it at idle time
	     * instead of now to ensure tk_library is setup.
	     */

	    Tcl_DoWhenIdle(SetApplicationIcon, NULL);
	}



	[NSApp _setupEventLoop];
	TkMacOSXInitAppleEvents(interp);
	TkMacOSXUseAntialiasedText(interp, -1);
	TkMacOSXInitCGDrawing(interp, TRUE, 0);
	[pool drain];


	/*
	 * FIXME: Close stdin & stdout for remote debugging otherwise we will
	 * fight with gdb for stdin & stdout
	 */

	if (getenv("XCNOSTDIN") != NULL) {
	    close(0);
................................................................................
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE void
TkMacOSXDefaultStartupScript(void)
{
    CFBundleRef bundleRef;

    bundleRef = CFBundleGetMainBundle();

    if (bundleRef != NULL) {
	CFURLRef appMainURL = CFBundleCopyResourceURL(bundleRef,
		CFSTR("AppMain"), CFSTR("tcl"), CFSTR("Scripts"));

	if (appMainURL != NULL) {
	    CFURLRef scriptFldrURL;
................................................................................
			    (unsigned char *) scriptPath, PATH_MAX);
		    CFRelease(scriptFldrURL);
		}
	    }
	    CFRelease(appMainURL);
	}
    }

}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetNamedSymbol --
 *






>
>
>



>
>
>
>
>
>
>







 







<
<
>


>



>
>

>








>



>







 







>
>







 







>








>







 







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







 







>
>
|
|
|
|
|
|
>







 







|
<
|







 







>







55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
..
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
...
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
...
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
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
...
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
...
490
491
492
493
494
495
496
497

498
499
500
501
502
503
504
505
...
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
@end

@interface TKApplication(TKMenus)
- (void)_setupMenus;
@end

@implementation TKApplication
#ifndef __clang__
@synthesize poolProtected = _poolProtected;
#endif
@end

@implementation TKApplication(TKInit)
- (void) _resetAutoreleasePool
{
    if(![self poolProtected]) {
	[_mainPool drain];
	_mainPool = [NSAutoreleasePool new];
    }
}
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
- (void)_postedNotification:(NSNotification *)notification {
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
}
#endif
- (void)_setupApplicationNotifications {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
................................................................................
    observe(NSTextInputContextKeyboardSelectionDidChangeNotification, keyboardChanged:);
#undef observe
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
    CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(), NULL, &keyboardChanged, kTISNotifySelectedKeyboardInputSourceChanged, NULL, CFNotificationSuspensionBehaviorCoalesce);
#endif
}
- (void)_setupEventLoop {


    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    [self finishLaunching];
    [self setWindowsNeedUpdate:YES];
    [pool drain];
}
- (void)_setup:(Tcl_Interp *)interp {
    _eventInterp = interp;
    _mainPool = nil;
    [NSApp setPoolProtected:NO];
    _defaultMainMenu = nil;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    [self _setupMenus];
    [self setDelegate:self];
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    [[NSNotificationCenter defaultCenter] addObserver:self
	    selector:@selector(_postedNotification:) name:nil object:nil];
#endif
    [self _setupWindowNotifications];
    [self _setupApplicationNotifications];
    [pool drain];
}
- (NSString *)tkFrameworkImagePath:(NSString*)image {
    NSString *path = nil;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    if (tkLibPath[0] != '\0') {
	path = [[NSBundle bundleWithPath:[[NSString stringWithUTF8String:
		tkLibPath] stringByAppendingString:@"/../.."]]
		pathForImageResource:image];
    }
    if (!path) {
	const char *tk_library = Tcl_GetVar2(_eventInterp, "tk_library", NULL,
................................................................................
	path = [[NSString stringWithUTF8String:getenv("TK_SRCROOT")]
		stringByAppendingFormat:@"/macosx/%@", image];
	if (![[NSFileManager defaultManager] isReadableFileAtPath:path]) {
	    path = nil;
	}
    }
#endif
    [path retain];
    [pool drain];
    return path;
}
@end

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

static void
SetApplicationIcon(
    ClientData clientData)
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    NSString *path = [NSApp tkFrameworkImagePath:@"Tk.icns"];
    if (path) {
	NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
	if (image) {
	    [NSApp setApplicationIconImage:image];
	    [image release];
	}
    }
    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkpInit --
 *
................................................................................
	if (Tcl_MacOSXOpenVersionedBundleResources(interp,
		"com.tcltk.tklibrary", TK_FRAMEWORK_VERSION, 0, PATH_MAX,
		tkLibPath) != TCL_OK) {
	    TkMacOSXDbgMsg("Tcl_MacOSXOpenVersionedBundleResources failed");
	}
#endif

	{
	    NSAutoreleasePool *pool = [NSAutoreleasePool new];
		[[NSUserDefaults standardUserDefaults] registerDefaults:
		     [NSDictionary dictionaryWithObjectsAndKeys:
		     [NSNumber numberWithBool:YES],
		     @"_NSCanWrapButtonTitles",
		     [NSNumber numberWithInt:-1],
		     @"NSStringDrawingTypesetterBehavior",
		     nil]];
	    [TKApplication sharedApplication];
	    [pool drain];
	    [NSApp _setup:interp];
	}

	/* Check whether we are a bundled executable: */
	bundleRef = CFBundleGetMainBundle();
	if (bundleRef) {
	    bundleUrl = CFBundleCopyBundleURL(bundleRef);
	}
	if (bundleUrl) {
................................................................................
	     * Set application icon to generic Tk icon, do it at idle time
	     * instead of now to ensure tk_library is setup.
	     */

	    Tcl_DoWhenIdle(SetApplicationIcon, NULL);
	}

	{
	    NSAutoreleasePool *pool = [NSAutoreleasePool new];
	    [NSApp _setupEventLoop];
	    TkMacOSXInitAppleEvents(interp);
	    TkMacOSXUseAntialiasedText(interp, -1);
	    TkMacOSXInitCGDrawing(interp, TRUE, 0);
	    [pool drain];
	}
	
	/*
	 * FIXME: Close stdin & stdout for remote debugging otherwise we will
	 * fight with gdb for stdin & stdout
	 */

	if (getenv("XCNOSTDIN") != NULL) {
	    close(0);
................................................................................
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE void
TkMacOSXDefaultStartupScript(void)
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    CFBundleRef bundleRef = CFBundleGetMainBundle();

    if (bundleRef != NULL) {
	CFURLRef appMainURL = CFBundleCopyResourceURL(bundleRef,
		CFSTR("AppMain"), CFSTR("tcl"), CFSTR("Scripts"));

	if (appMainURL != NULL) {
	    CFURLRef scriptFldrURL;
................................................................................
			    (unsigned char *) scriptPath, PATH_MAX);
		    CFRelease(scriptFldrURL);
		}
	    }
	    CFRelease(appMainURL);
	}
    }
    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetNamedSymbol --
 *

Changes to macosx/tkMacOSXKeyEvent.c.

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
  NSRect rect;
  NSPoint pt;

  pt.x = caret_x;
  pt.y = caret_y;

  pt = [self convertPoint: pt toView: nil];
  pt = [[self window] convertBaseToScreen: pt];
  pt.y -= caret_height;

  rect.origin = pt;
  rect.size.width = caret_height;
  rect.size.height = caret_height;
  return rect;
}






|







324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
  NSRect rect;
  NSPoint pt;

  pt.x = caret_x;
  pt.y = caret_y;

  pt = [self convertPoint: pt toView: nil];
  pt = [[self window] convertPointToScreen: pt];
  pt.y -= caret_height;

  rect.origin = pt;
  rect.size.width = caret_height;
  rect.size.height = caret_height;
  return rect;
}

Changes to macosx/tkMacOSXMenu.c.

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
...
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
...
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
...
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
    if ([sender isKindOfClass:[NSMenuItem class]]) {
	NSMenuItem *menuItem = (NSMenuItem *)sender;
	TkMenu *menuPtr = (TkMenu *)_tkMenu;
	TkMenuEntry *mePtr = (TkMenuEntry *)[menuItem tag];

	if (menuPtr && mePtr) {
	    Tcl_Interp *interp = menuPtr->interp;
	    /*Add time for errors to fire if necessary. This is sub-optimal but avoids issues with Tcl/Cocoa event loop integration.*/


	    Tcl_Sleep(100);

	    NSAutoreleasePool *pool = [NSAutoreleasePool new];
	    Tcl_Preserve(interp);
	    Tcl_Preserve(menuPtr);

	    int result = TkInvokeMenu(interp, menuPtr, mePtr->index);

	    if (result != TCL_OK && result != TCL_CONTINUE &&
		    result != TCL_BREAK) {
		Tcl_AddErrorInfo(interp, "\n    (menu invoke)");
		Tcl_BackgroundError(interp);
	    }
	    Tcl_Release(menuPtr);
	    Tcl_Release(interp);
	    [pool drain];
	}
    }
}
@end

@implementation TKMenu(TKMenuDelegate)
#define keyEquivModifiersMatch(km, m) (( \
................................................................................

@interface NSApplication(TKMenu)
- (void) setAppleMenu: (NSMenu *) menu;
@end

@implementation TKApplication(TKMenu)

- (void) safeSetMainMenu: (NSMenu *) menu
{
    NSAutoreleasePool* pool = [NSAutoreleasePool new];
    [self setMainMenu: menu];
    [pool drain];
}

- (void) menuBeginTracking: (NSNotification *) notification
{
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
#endif
    //TkMacOSXClearMenubarActive();
    //TkMacOSXPreprocessMenu();
................................................................................
		[menu itemAtIndex:0] : nil;

	if (![menu isSpecial:tkMainMenu]) {
	    TkMenuEntry *mePtr = (TkMenuEntry *)[applicationMenuItem tag];

	    if (!mePtr || !(mePtr->entryFlags & ENTRY_APPLE_MENU)) {
		applicationMenuItem = [NSMenuItem itemWithSubmenu:
			[[_defaultApplicationMenu copy] autorelease]];
		[menu insertItem:applicationMenuItem atIndex:0];
	    }
	    [menu setSpecial:tkMainMenu];
	}
	applicationMenu = (TKMenu *)[applicationMenuItem submenu];
	if (![applicationMenu isSpecial:tkApplicationMenu]) {
	    for (NSMenuItem *item in _defaultApplicationMenuItems) {
		[applicationMenu addItem:[[item copy] autorelease]];
	    }
	    [applicationMenu setSpecial:tkApplicationMenu];
	}

	NSArray *itemArray = [menu itemArray];

	for (NSMenuItem *item in itemArray) {
	    TkMenuEntry *mePtr = (TkMenuEntry *)[item tag];
	    TKMenu *submenu = (TKMenu *)[item submenu];

	    if (mePtr && submenu) {
		if ((mePtr->entryFlags & ENTRY_WINDOWS_MENU) &&
			![submenu isSpecial:tkWindowsMenu]) {
		    NSInteger index = 0;

		    for (NSMenuItem *i in _defaultWindowsMenuItems) {
			[submenu insertItem:[[i copy] autorelease] atIndex:
				index++];
		    }
		    [self setWindowsMenu:submenu];
		    [submenu setSpecial:tkWindowsMenu];
		} else if ((mePtr->entryFlags & ENTRY_HELP_MENU) &&
			![submenu isSpecial:tkHelpMenu]) {
		    NSInteger index = 0;

		    for (NSMenuItem *i in _defaultHelpMenuItems) {
			[submenu insertItem:[[i copy] autorelease] atIndex:
				index++];
		    }
		    [submenu setSpecial:tkHelpMenu];
		}
	    }
	}
    } else {
	menu = _defaultMainMenu;
................................................................................
	    [applicationMenu itemWithTitle:@"Services"];

    if (servicesMenuItem && [servicesMenuItem submenu] != _servicesMenu) {
	[[_servicesMenu itemInSupermenu] setSubmenu:nil];
	[servicesMenuItem setSubmenu:_servicesMenu];
    }
    [self setAppleMenu:applicationMenu];
    [self safeSetMainMenu:menu];
}
@end

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






|
>
>

<
<












<







 







<
<
<
<
<
<
<







 







|







|









<






|
<








|
<







 







|







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
...
372
373
374
375
376
377
378







379
380
381
382
383
384
385
...
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432

433
434
435
436
437
438
439

440
441
442
443
444
445
446
447
448

449
450
451
452
453
454
455
...
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
    if ([sender isKindOfClass:[NSMenuItem class]]) {
	NSMenuItem *menuItem = (NSMenuItem *)sender;
	TkMenu *menuPtr = (TkMenu *)_tkMenu;
	TkMenuEntry *mePtr = (TkMenuEntry *)[menuItem tag];

	if (menuPtr && mePtr) {
	    Tcl_Interp *interp = menuPtr->interp;
	    /*Add time for errors to fire if necessary. This is sub-optimal
	     *but avoids issues with Tcl/Cocoa event loop integration.
	     */
	    Tcl_Sleep(100);


	    Tcl_Preserve(interp);
	    Tcl_Preserve(menuPtr);

	    int result = TkInvokeMenu(interp, menuPtr, mePtr->index);

	    if (result != TCL_OK && result != TCL_CONTINUE &&
		    result != TCL_BREAK) {
		Tcl_AddErrorInfo(interp, "\n    (menu invoke)");
		Tcl_BackgroundError(interp);
	    }
	    Tcl_Release(menuPtr);
	    Tcl_Release(interp);

	}
    }
}
@end

@implementation TKMenu(TKMenuDelegate)
#define keyEquivModifiersMatch(km, m) (( \
................................................................................

@interface NSApplication(TKMenu)
- (void) setAppleMenu: (NSMenu *) menu;
@end

@implementation TKApplication(TKMenu)








- (void) menuBeginTracking: (NSNotification *) notification
{
#ifdef TK_MAC_DEBUG_NOTIFICATIONS
    TKLog(@"-[%@(%p) %s] %@", [self class], self, _cmd, notification);
#endif
    //TkMacOSXClearMenubarActive();
    //TkMacOSXPreprocessMenu();
................................................................................
		[menu itemAtIndex:0] : nil;

	if (![menu isSpecial:tkMainMenu]) {
	    TkMenuEntry *mePtr = (TkMenuEntry *)[applicationMenuItem tag];

	    if (!mePtr || !(mePtr->entryFlags & ENTRY_APPLE_MENU)) {
		applicationMenuItem = [NSMenuItem itemWithSubmenu:
			[_defaultApplicationMenu copy]];
		[menu insertItem:applicationMenuItem atIndex:0];
	    }
	    [menu setSpecial:tkMainMenu];
	}
	applicationMenu = (TKMenu *)[applicationMenuItem submenu];
	if (![applicationMenu isSpecial:tkApplicationMenu]) {
	    for (NSMenuItem *item in _defaultApplicationMenuItems) {
		[applicationMenu addItem:[item copy]];
	    }
	    [applicationMenu setSpecial:tkApplicationMenu];
	}

	NSArray *itemArray = [menu itemArray];

	for (NSMenuItem *item in itemArray) {
	    TkMenuEntry *mePtr = (TkMenuEntry *)[item tag];
	    TKMenu *submenu = (TKMenu *)[item submenu];

	    if (mePtr && submenu) {
		if ((mePtr->entryFlags & ENTRY_WINDOWS_MENU) &&
			![submenu isSpecial:tkWindowsMenu]) {
		    NSInteger index = 0;

		    for (NSMenuItem *i in _defaultWindowsMenuItems) {
			[submenu insertItem:[i copy] atIndex:index++];

		    }
		    [self setWindowsMenu:submenu];
		    [submenu setSpecial:tkWindowsMenu];
		} else if ((mePtr->entryFlags & ENTRY_HELP_MENU) &&
			![submenu isSpecial:tkHelpMenu]) {
		    NSInteger index = 0;

		    for (NSMenuItem *i in _defaultHelpMenuItems) {
			[submenu insertItem:[i copy] atIndex:index++];

		    }
		    [submenu setSpecial:tkHelpMenu];
		}
	    }
	}
    } else {
	menu = _defaultMainMenu;
................................................................................
	    [applicationMenu itemWithTitle:@"Services"];

    if (servicesMenuItem && [servicesMenuItem submenu] != _servicesMenu) {
	[[_servicesMenu itemInSupermenu] setSubmenu:nil];
	[servicesMenuItem setSubmenu:_servicesMenu];
    }
    [self setAppleMenu:applicationMenu];
    [self setMainMenu:menu];
}
@end

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

Changes to macosx/tkMacOSXNotify.c.

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214


215
216
217
218
219
220
221
222
223

224
225
226
227


228
229
230
231
232
233
234
...
247
248
249
250
251
252
253

254
255
256
257
258
259
260

261
262
263
264
265
266
267
...
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292


293

294
295
296
297
298
299
300
301
302
303
304
305
306
	[self displayIfNeeded];
    }
    return nil;
}
@end

@implementation TKApplication(TKNotify)
/* Call super then redisplay all of our windows. */
- (NSEvent *)nextEventMatchingMask:(NSUInteger)mask
	untilDate:(NSDate *)expiration inMode:(NSString *)mode
	dequeue:(BOOL)deqFlag {
    NSEvent *event = [super nextEventMatchingMask:mask
					untilDate:expiration
					   inMode:mode
					  dequeue:deqFlag];
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    [NSApp makeWindowsPerform:@selector(tkDisplayIfNeeded) inOrder:NO];
    [pool drain];
    return event;
}

 /*
 * Call super then check the pasteboard.
  */
- (void)sendEvent:(NSEvent *)theEvent {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    [super sendEvent:theEvent];
    [NSApp tkCheckPasteboard];
    [pool drain];
}
@end

#pragma mark -
 
/*
 *----------------------------------------------------------------------
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsSetupProc --
 *
 *	This procedure implements the setup part of the MacOSX event
 *	source. It is invoked by Tcl_DoOneEvent before calling 
 *      TkMacOSXEventsProc to process all queued NSEvents.  In our
 *      case, all we need to do is to set the Tcl MaxBlockTime to
 *      0 before starting the loop to process all queued NSEvents.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *      
 *	If NSEvents are queued, then the maximum block time will be set
 *	to 0 to ensure that control returns immediately to Tcl.
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXEventsSetupProc(
    ClientData clientData,
    int flags)
{


    if (flags & TCL_WINDOW_EVENTS &&
	![[NSRunLoop currentRunLoop] currentMode]) {
	static Tcl_Time zeroBlockTime = { 0, 0 };
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
 	/* Call this with dequeue=NO -- just checking if the queue is empty. */ 
	NSEvent *currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
 						   untilDate:[NSDate distantPast]
 						      inMode:GetRunLoopMode(TkMacOSXGetModalSession())
 						     dequeue:NO];

	if (currentEvent && currentEvent.type > 0) {
	    Tcl_SetMaxBlockTime(&zeroBlockTime);
	}
	[pool drain];


    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsCheckProc --
................................................................................
 */
static void
TkMacOSXEventsCheckProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];

    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {

	NSEvent *currentEvent = nil;
	NSEvent *testEvent = nil;
	NSModalSession modalSession;

	do {

	    modalSession = TkMacOSXGetModalSession();
	    testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
					      untilDate:[NSDate distantPast]
						 inMode:GetRunLoopMode(modalSession)
						dequeue:NO];
	    /* We must not steal any events during LiveResize. */
	    if (testEvent && [[testEvent window] inLiveResize]) {
................................................................................
		break;
	    }

	    currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
					      untilDate:[NSDate distantPast]
						 inMode:GetRunLoopMode(modalSession)
						dequeue:YES];
	    if (!currentEvent) {
		break; /* No events are available. */
	    }
	    NSAutoreleasePool *pool = [NSAutoreleasePool new];
	    /* Generate Xevents. */
	    int oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);
	    NSEvent *processedEvent = [NSApp tkProcessEvent:currentEvent];
	    Tcl_SetServiceMode(oldServiceMode);
	    if (processedEvent) { /* Should always be non-NULL. */
#ifdef TK_MAC_DEBUG_EVENTS
		TKLog(@"   event: %@", currentEvent);
#endif
		if (modalSession) {
		    [NSApp _modalSession:modalSession sendEvent:currentEvent];
		} else {
		    [NSApp sendEvent:currentEvent];
		}
	    }


	    [pool drain];

	} while (1);
    }
}

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






|







|
|
|







<


<







 







|








|











>
>
|
<

<
|

|
|
|
>
|
|
|
<
>
>







 







>

<





>







 







|
|
<
<
|
|
|
|
|

|

|
|
|
|
|
|
>
>
|
>













45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

70
71

72
73
74
75
76
77
78
...
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215

216

217
218
219
220
221
222
223
224
225

226
227
228
229
230
231
232
233
234
...
247
248
249
250
251
252
253
254
255

256
257
258
259
260
261
262
263
264
265
266
267
268
...
269
270
271
272
273
274
275
276
277


278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
	[self displayIfNeeded];
    }
    return nil;
}
@end

@implementation TKApplication(TKNotify)
/* Display all windows each time an event is removed from the queue.*/
- (NSEvent *)nextEventMatchingMask:(NSUInteger)mask
	untilDate:(NSDate *)expiration inMode:(NSString *)mode
	dequeue:(BOOL)deqFlag {
    NSEvent *event = [super nextEventMatchingMask:mask
					untilDate:expiration
					   inMode:mode
					  dequeue:deqFlag];
    /* Retain this event for later use. Must be released.*/
    [event retain];
    [NSApp makeWindowsPerform:@selector(tkDisplayIfNeeded) inOrder:NO];
    return event;
}

 /*
 * Call super then check the pasteboard.
  */
- (void)sendEvent:(NSEvent *)theEvent {

    [super sendEvent:theEvent];
    [NSApp tkCheckPasteboard];

}
@end

#pragma mark -
 
/*
 *----------------------------------------------------------------------
................................................................................
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsSetupProc --
 *
 *	This procedure implements the setup part of the MacOSX event
 *	source. It is invoked by Tcl_DoOneEvent before calling
 *      TkMacOSXEventsProc to process all queued NSEvents.  In our
 *      case, all we need to do is to set the Tcl MaxBlockTime to
 *      0 before starting the loop to process all queued NSEvents.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *
 *	If NSEvents are queued, then the maximum block time will be set
 *	to 0 to ensure that control returns immediately to Tcl.
 *
 *----------------------------------------------------------------------
 */

static void
TkMacOSXEventsSetupProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];
    /* runloopMode will be nil if we are in the Tcl event loop. */
    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {

	static Tcl_Time zeroBlockTime = { 0, 0 };

	/* Call this with dequeue=NO -- just checking if the queue is empty. */
	NSEvent *currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
				       untilDate:[NSDate distantPast]
				       inMode:GetRunLoopMode(TkMacOSXGetModalSession())
				       dequeue:NO];
	if (currentEvent) {
	    if (currentEvent.type > 0) {
		Tcl_SetMaxBlockTime(&zeroBlockTime);
	    }

	    [currentEvent release];
	}
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXEventsCheckProc --
................................................................................
 */
static void
TkMacOSXEventsCheckProc(
    ClientData clientData,
    int flags)
{
    NSString *runloopMode = [[NSRunLoop currentRunLoop] currentMode];
    /* runloopMode will be nil if we are in the Tcl event loop. */
    if (flags & TCL_WINDOW_EVENTS && !runloopMode) {

	NSEvent *currentEvent = nil;
	NSEvent *testEvent = nil;
	NSModalSession modalSession;

	do {
	    [NSApp _resetAutoreleasePool];
	    modalSession = TkMacOSXGetModalSession();
	    testEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
					      untilDate:[NSDate distantPast]
						 inMode:GetRunLoopMode(modalSession)
						dequeue:NO];
	    /* We must not steal any events during LiveResize. */
	    if (testEvent && [[testEvent window] inLiveResize]) {
................................................................................
		break;
	    }

	    currentEvent = [NSApp nextEventMatchingMask:NSAnyEventMask
					      untilDate:[NSDate distantPast]
						 inMode:GetRunLoopMode(modalSession)
						dequeue:YES];
	    if (currentEvent) {
		[NSApp _resetAutoreleasePool];


		/* Generate Xevents. */
		int oldServiceMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);
		NSEvent *processedEvent = [NSApp tkProcessEvent:currentEvent];
		Tcl_SetServiceMode(oldServiceMode);
		if (processedEvent) { /* Should always be non-NULL. */
#ifdef TK_MAC_DEBUG_EVENTS
		    TKLog(@"   event: %@", currentEvent);
#endif
		    if (modalSession) {
			[NSApp _modalSession:modalSession sendEvent:currentEvent];
		    } else {
			[NSApp sendEvent:currentEvent];
		    }
		}
		[currentEvent release];
	    } else {
		break;
	    }
	} while (1);
    }
}

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

Changes to macosx/tkMacOSXPrivate.h.

269
270
271
272
273
274
275

276

277
278
279

280
281
282
283
284
285
286
@private
    Tcl_Interp *_eventInterp;
    NSMenu *_servicesMenu;
    TKMenu *_defaultMainMenu, *_defaultApplicationMenu;
    NSArray *_defaultApplicationMenuItems, *_defaultWindowsMenuItems;
    NSArray *_defaultHelpMenuItems;
    NSWindow *_windowWithMouse;

}

@end
@interface TKApplication(TKInit)
- (NSString *)tkFrameworkImagePath:(NSString*)image;

@end
@interface TKApplication(TKEvent)
- (NSEvent *)tkProcessEvent:(NSEvent *)theEvent;
@end
@interface TKApplication(TKMouseEvent)
- (NSEvent *)tkProcessMouseEvent:(NSEvent *)theEvent;
@end






>

>



>







269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
@private
    Tcl_Interp *_eventInterp;
    NSMenu *_servicesMenu;
    TKMenu *_defaultMainMenu, *_defaultApplicationMenu;
    NSArray *_defaultApplicationMenuItems, *_defaultWindowsMenuItems;
    NSArray *_defaultHelpMenuItems;
    NSWindow *_windowWithMouse;
    NSAutoreleasePool *_mainPool;
}
@property BOOL poolProtected;
@end
@interface TKApplication(TKInit)
- (NSString *)tkFrameworkImagePath:(NSString*)image;
- (void)_resetAutoreleasePool;
@end
@interface TKApplication(TKEvent)
- (NSEvent *)tkProcessEvent:(NSEvent *)theEvent;
@end
@interface TKApplication(TKMouseEvent)
- (NSEvent *)tkProcessMouseEvent:(NSEvent *)theEvent;
@end

Changes to macosx/tkMacOSXSubwindows.c.

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
...
154
155
156
157
158
159
160

161
162
163
164
165
166
167
...
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
...
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
...
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
...
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
void
XMapWindow(
    Display *display,		/* Display. */
    Window window)		/* Window. */
{
    MacDrawable *macWin = (MacDrawable *) window;
    XEvent event;
    /*
     * This function can be called from outside the AppKit event
     * loop, so it needs its own AutoreleasePool.
     */
    NSAutoreleasePool* pool = [NSAutoreleasePool new];

    /*
     * Under certain situations it's possible for this function to be called
     * before the toplevel window it's associated with has actually been
     * mapped. In that case we need to create the real Macintosh window now as
     * this function as well as other X functions assume that the portPtr is
     * valid.
................................................................................
    if (Tk_IsTopLevel(macWin->winPtr)) {
	if (!Tk_IsEmbedded(macWin->winPtr)) {
	    NSWindow *win = TkMacOSXDrawableWindow(window);
	    [NSApp activateIgnoringOtherApps:YES];
	    if ( [win canBecomeKeyWindow] ) {
		[win makeKeyAndOrderFront:NSApp];
	    }

	    [win windowRef];
	    TkMacOSXApplyWindowAttributes(macWin->winPtr, win);
	}
	TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr);

	/*
	 * We only need to send the MapNotify event for toplevel windows.
................................................................................
     */

    event.xany.send_event = False;
    event.xany.display = display;
    event.xvisibility.type = VisibilityNotify;
    event.xvisibility.state = VisibilityUnobscured;
    NotifyVisibility(macWin->winPtr, &event);
    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * NotifyVisibility --
 *
................................................................................
XResizeWindow(
    Display *display,		/* Display. */
    Window window,		/* Window. */
    unsigned int width,
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;
    NSAutoreleasePool *pool= [NSAutoreleasePool new];
    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    NSRect r = [w contentRectForFrameRect:[w frame]];
	    r.origin.y += r.size.height - height;
................................................................................
	    r.size.width = width;
	    r.size.height = height;
	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
    } else {
	MoveResizeWindow(macWin);
    }
    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * XMoveResizeWindow --
 *
................................................................................
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    NSRect r = NSMakeRect(x + macWin->winPtr->wmInfoPtr->xInParent,
		    tkMacOSXZeroScreenHeight - (y +
		    macWin->winPtr->wmInfoPtr->yInParent + height),
		    width, height);
	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
................................................................................
    int x, int y)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    [w setFrameTopLeftPoint:NSMakePoint(x, tkMacOSXZeroScreenHeight - y)];
	}
    } else {
	MoveResizeWindow(macWin);
    }
}






<
<
<
<
<







 







>







 







<







 







<







 







<







 







<







 







<







127
128
129
130
131
132
133





134
135
136
137
138
139
140
...
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
...
186
187
188
189
190
191
192

193
194
195
196
197
198
199
...
309
310
311
312
313
314
315

316
317
318
319
320
321
322
...
323
324
325
326
327
328
329

330
331
332
333
334
335
336
...
355
356
357
358
359
360
361

362
363
364
365
366
367
368
...
395
396
397
398
399
400
401

402
403
404
405
406
407
408
void
XMapWindow(
    Display *display,		/* Display. */
    Window window)		/* Window. */
{
    MacDrawable *macWin = (MacDrawable *) window;
    XEvent event;






    /*
     * Under certain situations it's possible for this function to be called
     * before the toplevel window it's associated with has actually been
     * mapped. In that case we need to create the real Macintosh window now as
     * this function as well as other X functions assume that the portPtr is
     * valid.
................................................................................
    if (Tk_IsTopLevel(macWin->winPtr)) {
	if (!Tk_IsEmbedded(macWin->winPtr)) {
	    NSWindow *win = TkMacOSXDrawableWindow(window);
	    [NSApp activateIgnoringOtherApps:YES];
	    if ( [win canBecomeKeyWindow] ) {
		[win makeKeyAndOrderFront:NSApp];
	    }
	    /* Why do we need this? (It is used by Carbon)*/
	    [win windowRef];
	    TkMacOSXApplyWindowAttributes(macWin->winPtr, win);
	}
	TkMacOSXInvalClipRgns((Tk_Window) macWin->winPtr);

	/*
	 * We only need to send the MapNotify event for toplevel windows.
................................................................................
     */

    event.xany.send_event = False;
    event.xany.display = display;
    event.xvisibility.type = VisibilityNotify;
    event.xvisibility.state = VisibilityUnobscured;
    NotifyVisibility(macWin->winPtr, &event);

}
 
/*
 *----------------------------------------------------------------------
 *
 * NotifyVisibility --
 *
................................................................................
XResizeWindow(
    Display *display,		/* Display. */
    Window window,		/* Window. */
    unsigned int width,
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    NSRect r = [w contentRectForFrameRect:[w frame]];
	    r.origin.y += r.size.height - height;
................................................................................
	    r.size.width = width;
	    r.size.height = height;
	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
    } else {
	MoveResizeWindow(macWin);
    }

}
 
/*
 *----------------------------------------------------------------------
 *
 * XMoveResizeWindow --
 *
................................................................................
    unsigned int height)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    NSRect r = NSMakeRect(x + macWin->winPtr->wmInfoPtr->xInParent,
		    tkMacOSXZeroScreenHeight - (y +
		    macWin->winPtr->wmInfoPtr->yInParent + height),
		    width, height);
	    [w setFrame:[w frameRectForContentRect:r] display:YES];
	}
................................................................................
    int x, int y)
{
    MacDrawable *macWin = (MacDrawable *) window;

    display->request++;
    if (Tk_IsTopLevel(macWin->winPtr) && !Tk_IsEmbedded(macWin->winPtr)) {
	NSWindow *w = macWin->winPtr->wmInfoPtr->window;

	if (w) {
	    [w setFrameTopLeftPoint:NSMakePoint(x, tkMacOSXZeroScreenHeight - y)];
	}
    } else {
	MoveResizeWindow(macWin);
    }
}

Changes to macosx/tkMacOSXWindowEvent.c.

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
...
840
841
842
843
844
845
846

847
848
849
850
851
852
853
854
855
856
857



858









859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880

881
882
883
884
885
886
887
@implementation TKContentView(TKWindowEvent)

- (void) drawRect: (NSRect) rect
{
    const NSRect *rectsBeingDrawn;
    NSInteger rectsBeingDrawnCount;

    [self getRectsBeingDrawn:&rectsBeingDrawn count:&rectsBeingDrawnCount];

#ifdef TK_MAC_DEBUG_DRAWING
    TKLog(@"-[%@(%p) %s%@]", [self class], self, _cmd, NSStringFromRect(rect));
    [[NSColor colorWithDeviceRed:0.0 green:1.0 blue:0.0 alpha:.1] setFill];
    NSRectFillListUsingOperation(rectsBeingDrawn, rectsBeingDrawnCount,
	    NSCompositeSourceOver);
................................................................................
   
    CFRelease(drawShape);
  
}

-(void) setFrameSize: (NSSize)newsize
{

    if ( [self inLiveResize] ) {
	NSWindow *w = [self window];
	TkWindow *winPtr = TkMacOSXGetTkWindow(w);
	Tk_Window tkwin = (Tk_Window) winPtr;
	unsigned int width = (unsigned int)newsize.width;
	unsigned int height=(unsigned int)newsize.height;
	ClientData oldArg;
    	Tk_RestrictProc *oldProc;

	/* Resize the NSView */
	[super setFrameSize: newsize];













	/* Disable drawing until the window has been completely configured.*/
	TkMacOSXSetDrawingEnabled(winPtr, 0);

	 /* Generate and handle a ConfigureNotify event for the new size.*/
	TkGenWMConfigureEvent(tkwin, Tk_X(tkwin), Tk_Y(tkwin), width, height,
			      TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY);
    	oldProc = Tk_RestrictEvents(ConfigureRestrictProc, NULL, &oldArg);
	while ( Tk_DoOneEvent(TK_X_EVENTS|TK_DONT_WAIT) ) {}
    	Tk_RestrictEvents(oldProc, oldArg, &oldArg);

	/* Now that Tk has configured all subwindows we can create the clip regions. */
	TkMacOSXSetDrawingEnabled(winPtr, 1);
	TkMacOSXInvalClipRgns(tkwin);
	TkMacOSXUpdateClipRgn(winPtr);

	 /* Finally, generate and process expose events to redraw the window. */
	HIRect bounds = NSRectToCGRect([self bounds]);
	HIShapeRef shape = HIShapeCreateWithRect(&bounds);
	[self generateExposeEvents: shape];
	while ( Tk_DoOneEvent(TK_ALL_EVENTS|TK_DONT_WAIT) ) {}
    } else {
        [super setFrameSize: newsize];

    }
}

/*
 * As insurance against bugs that might cause layout glitches during a live
 * resize, we redraw the window one more time at the end of the resize
 * operation.






|







 







>
|








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






|











|
|
|
>







804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
...
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
@implementation TKContentView(TKWindowEvent)

- (void) drawRect: (NSRect) rect
{
    const NSRect *rectsBeingDrawn;
    NSInteger rectsBeingDrawnCount;
    
    [self getRectsBeingDrawn:&rectsBeingDrawn count:&rectsBeingDrawnCount];

#ifdef TK_MAC_DEBUG_DRAWING
    TKLog(@"-[%@(%p) %s%@]", [self class], self, _cmd, NSStringFromRect(rect));
    [[NSColor colorWithDeviceRed:0.0 green:1.0 blue:0.0 alpha:.1] setFill];
    NSRectFillListUsingOperation(rectsBeingDrawn, rectsBeingDrawnCount,
	    NSCompositeSourceOver);
................................................................................
   
    CFRelease(drawShape);
  
}

-(void) setFrameSize: (NSSize)newsize
{
    [super setFrameSize: newsize];
    if ([self inLiveResize]) {
	NSWindow *w = [self window];
	TkWindow *winPtr = TkMacOSXGetTkWindow(w);
	Tk_Window tkwin = (Tk_Window) winPtr;
	unsigned int width = (unsigned int)newsize.width;
	unsigned int height=(unsigned int)newsize.height;
	ClientData oldArg;
    	Tk_RestrictProc *oldProc;

	/* This can be called from outside the Tk event loop.
	 * Since it calls Tcl_DoOneEvent, we need to make sure we
	 * don't clobber the AutoreleasePool set up by the caller.
	 */
	[NSApp setPoolProtected:YES];
	
	/*
	 * Try to prevent flickers and flashes.
	 *
	 * This stops the flickers, but on OSX 10.11 flashes still occur when
	 * the width of the window is 16, 32, 48, 64, 80, 96, 112, 256, 512,
	 * 768, ...
	 */
	[w disableFlushWindow];
	
	/* Disable Tk drawing until the window has been completely configured.*/
	TkMacOSXSetDrawingEnabled(winPtr, 0);

	 /* Generate and handle a ConfigureNotify event for the new size.*/
	TkGenWMConfigureEvent(tkwin, Tk_X(tkwin), Tk_Y(tkwin), width, height,
			      TK_SIZE_CHANGED | TK_MACOSX_HANDLE_EVENT_IMMEDIATELY);
    	oldProc = Tk_RestrictEvents(ConfigureRestrictProc, NULL, &oldArg);
	while (Tk_DoOneEvent(TK_X_EVENTS|TK_DONT_WAIT)) {}
    	Tk_RestrictEvents(oldProc, oldArg, &oldArg);

	/* Now that Tk has configured all subwindows we can create the clip regions. */
	TkMacOSXSetDrawingEnabled(winPtr, 1);
	TkMacOSXInvalClipRgns(tkwin);
	TkMacOSXUpdateClipRgn(winPtr);

	 /* Finally, generate and process expose events to redraw the window. */
	HIRect bounds = NSRectToCGRect([self bounds]);
	HIShapeRef shape = HIShapeCreateWithRect(&bounds);
	[self generateExposeEvents: shape];
	while (Tk_DoOneEvent(TK_ALL_EVENTS|TK_DONT_WAIT)) {}
	[w enableFlushWindow];
	[w flushWindowIfNeeded];
	[NSApp setPoolProtected:NO];
    }
}

/*
 * As insurance against bugs that might cause layout glitches during a live
 * resize, we redraw the window one more time at the end of the resize
 * operation.

Changes to macosx/tkMacOSXWm.c.

404
405
406
407
408
409
410

411

412
413
414
415
416

417
418
419
420
421

422

423
424
425
426
427
428
429
430

431

432
433













434
435
436
437
438
439
440
...
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
...
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883

884
885
886
887
888
889
890
891
892
893




894
895

896
897
898
899
900
901
902
....
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
....
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
....
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
....
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
- (id) retain
{
    id result = [super retain];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }

    printf("Retained <%s>. Count is: %lu\n", title, [self retainCount]);

    return result;
}

- (id) autorelease
{

    id result = [super autorelease];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }

    printf("Autoreleased <%s>. Count is %lu\n", title, [self retainCount]);

    return result;
}

- (oneway void) release {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }

    printf("Releasing <%s>. Count is %lu\n", title, [self retainCount]);

    [super release];
}













#endif
@end

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

static TkWindow*
FrontWindowAtPoint(
    int x, int y)
{
    NSPoint p = NSMakePoint(x, tkMacOSXZeroScreenHeight - y);
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    NSArray *windows = [NSApp orderedWindows];
    TkWindow *front = NULL;

    for (NSWindow *w in windows) {
	    if (w && NSMouseInRect(p, [w frame], NO)) {
		front = TkMacOSXGetTkWindow(w);
		break;
	    }
	}
    [pool drain];
    return front;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkWmNewWindow --
................................................................................
     * 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) ) {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	NSWindow *parent = [window parentWindow];
	if (parent) {
	    [parent removeChildWindow:window];
	}
	[window close];
	TkMacOSXUnregisterMacWindow(window);
        if (winPtr->window) {
            ((MacDrawable *) winPtr->window)->view = nil;
        }
#if DEBUG_ZOMBIES
	{
	    const char *title = [[window title] UTF8String];
	    if (title == nil) {
		title = "unnamed window";
	    }
	    printf("Closing <%s>. Count is: %lu\n", title, [window retainCount]);
	}
#endif
        [window release];
	wmPtr->window = NULL;

       /* Activate the highest window left on the screen. */
       NSArray *windows = [NSApp orderedWindows];
       if ( [windows count] > 0 ) {
	   NSWindow *front = [windows objectAtIndex:0];
	   if ( front && [front canBecomeKeyWindow] ) {
               [front makeKeyAndOrderFront:NSApp];
           }
       }
       [pool drain];
    }




    ckfree((char *)wmPtr);
    winPtr->wmInfoPtr = NULL;

}
 
/*
 *----------------------------------------------------------------------
 *
 * TkWmSetClass --
 *
................................................................................
	}
	return;

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

    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    WindowClass macClass = wmPtr->macClass;
    wmPtr->attributes &= (tkAlwaysValidAttributes |
	    macClassAttrs[macClass].validAttrs);
    wmPtr->flags |= macClassAttrs[macClass].flags |
	    ((wmPtr->attributes & kWindowResizableAttribute) ? 0 :
	    WM_WIDTH_NOT_RESIZABLE|WM_HEIGHT_NOT_RESIZABLE);
    UInt64 attributes = (wmPtr->attributes &
................................................................................
	    styleMask:styleMask];
    NSRect contentRect = NSMakeRect(5 - structureRect.origin.x,
	    tkMacOSXZeroScreenHeight - (tkMacOSXZeroScreenTop + 5 +
	    structureRect.origin.y + structureRect.size.height + 200), 200, 200);
    NSWindow *window = [[winClass alloc] initWithContentRect:contentRect
	    styleMask:styleMask backing:NSBackingStoreBuffered defer:YES];
    if (!window) {
	Tcl_Panic("couldn't allocate new Mac window");
    }
    TKContentView *contentView = [[TKContentView alloc]
	    initWithFrame:NSZeroRect];
    [window setContentView:contentView];
    [contentView release];
    [window setDelegate:NSApp];
    [window setAcceptsMouseMovedEvents:YES];
    [window setReleasedWhenClosed:NO];
    [window setAutodisplay:NO];
    if (styleMask & NSUtilityWindowMask) {
................................................................................
#else
	[window setOpaque: YES];
#endif
    }

    [window setDocumentEdited:NO];
    wmPtr->window = window;
    macWin->view = 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:NO];

    TkMacOSXRegisterOffScreenWindow((Window) macWin, window);
    macWin->flags |= TK_HOST_EXISTS;

    [pool drain];
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXRegisterOffScreenWindow --
 *
................................................................................
{
    if (winPtr->atts.override_redirect) {
	return 0;
    }

    if (Tk_IsTopLevel(winPtr) && !Tk_IsEmbedded(winPtr) ){
    	NSWindow *win = TkMacOSXDrawableWindow(winPtr->window);
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
    	TkWmRestackToplevel(winPtr, Above, NULL);
    	if (force ) {
    	    [NSApp activateIgnoringOtherApps:YES];
    	}
	if ( win && [win canBecomeKeyWindow] ) {
	    [win makeKeyAndOrderFront:NSApp];
	}
	[pool drain];
    }
	
    /*
     * 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,
     * so we can distinguish FocusIn and FocusOut events on either side of the
     * mark.






>
|
>





>





>
|
>








>
|
>


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







 







<









<







 







<









|





|




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


>







 







<
<
<







 







|


|







 







|








<


<
<







 







<







<







404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
...
560
561
562
563
564
565
566

567
568
569
570
571
572
573
574
575

576
577
578
579
580
581
582
...
874
875
876
877
878
879
880

881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909


910
911
912
913
914
915
916
917
918
919
920
921
922
923
....
5495
5496
5497
5498
5499
5500
5501



5502
5503
5504
5505
5506
5507
5508
....
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
....
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581

5582
5583


5584
5585
5586
5587
5588
5589
5590
....
5969
5970
5971
5972
5973
5974
5975

5976
5977
5978
5979
5980
5981
5982

5983
5984
5985
5986
5987
5988
5989
- (id) retain
{
    id result = [super retain];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1){
	printf("Retained <%s>. Count is: %lu\n", title, [self retainCount]);
    }
    return result;
}

- (id) autorelease
{
    static int xcount = 0;
    id result = [super autorelease];
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1){
	printf("Autoreleased <%s>. Count is %lu\n", title, [self retainCount]);
    }
    return result;
}

- (oneway void) release {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 1){
	printf("Releasing <%s>. Count is %lu\n", title, [self retainCount]);
    }
    [super release];
}

- (void) dealloc {
    const char *title = [[self title] UTF8String];
    if (title == nil) {
	title = "unnamed window";
    }
    if (DEBUG_ZOMBIES > 0){
	printf(">>>> Freeing <%s>. Count is %lu\n", title, [self retainCount]);
    }
    [super dealloc];
}


#endif
@end

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

static TkWindow*
FrontWindowAtPoint(
    int x, int y)
{
    NSPoint p = NSMakePoint(x, tkMacOSXZeroScreenHeight - y);

    NSArray *windows = [NSApp orderedWindows];
    TkWindow *front = NULL;

    for (NSWindow *w in windows) {
	    if (w && NSMouseInRect(p, [w frame], NO)) {
		front = TkMacOSXGetTkWindow(w);
		break;
	    }
	}

    return front;
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkWmNewWindow --
................................................................................
     * 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];
	}
	[window close];
	TkMacOSXUnregisterMacWindow(window);
        if (winPtr->window) {
            ((MacDrawable *) winPtr->window)->view = nil;
        }
#if DEBUG_ZOMBIES > 0
	{
	    const char *title = [[window title] UTF8String];
	    if (title == nil) {
		title = "unnamed window";
	    }
	    printf(">>>> Closing <%s>. Count is: %lu\n", title, [window retainCount]);
	}
#endif
        [window release];
	wmPtr->window = NULL;

	/* Activate the highest window left on the screen. */
	NSArray *windows = [NSApp orderedWindows];
	if ( [windows count] > 0 ) {
	    NSWindow *front = [windows objectAtIndex:0];
	    if ( front && [front canBecomeKeyWindow] ) {
		[front makeKeyAndOrderFront:NSApp];
	    }
	}


#if DEBUG_ZOMBIES > 0
	fprintf(stderr, "================= Pool dump ===================\n");
	[NSAutoreleasePool showPools];
#endif
    ckfree((char *)wmPtr);
    winPtr->wmInfoPtr = NULL;
    }
}
 
/*
 *----------------------------------------------------------------------
 *
 * TkWmSetClass --
 *
................................................................................
	}
	return;

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



    WindowClass macClass = wmPtr->macClass;
    wmPtr->attributes &= (tkAlwaysValidAttributes |
	    macClassAttrs[macClass].validAttrs);
    wmPtr->flags |= macClassAttrs[macClass].flags |
	    ((wmPtr->attributes & kWindowResizableAttribute) ? 0 :
	    WM_WIDTH_NOT_RESIZABLE|WM_HEIGHT_NOT_RESIZABLE);
    UInt64 attributes = (wmPtr->attributes &
................................................................................
	    styleMask:styleMask];
    NSRect contentRect = NSMakeRect(5 - structureRect.origin.x,
	    tkMacOSXZeroScreenHeight - (tkMacOSXZeroScreenTop + 5 +
	    structureRect.origin.y + structureRect.size.height + 200), 200, 200);
    NSWindow *window = [[winClass alloc] initWithContentRect:contentRect
	    styleMask:styleMask backing:NSBackingStoreBuffered defer:YES];
    if (!window) {
    	Tcl_Panic("couldn't allocate new Mac window");
    }
    TKContentView *contentView = [[TKContentView alloc]
				     initWithFrame:NSZeroRect];
    [window setContentView:contentView];
    [contentView release];
    [window setDelegate:NSApp];
    [window setAcceptsMouseMovedEvents:YES];
    [window setReleasedWhenClosed:NO];
    [window setAutodisplay:NO];
    if (styleMask & NSUtilityWindowMask) {
................................................................................
#else
	[window setOpaque: YES];
#endif
    }

    [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:NO];

    TkMacOSXRegisterOffScreenWindow((Window) macWin, window);
    macWin->flags |= TK_HOST_EXISTS;


}
 
/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXRegisterOffScreenWindow --
 *
................................................................................
{
    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,
     * so we can distinguish FocusIn and FocusOut events on either side of the
     * mark.

Changes to macosx/tkMacOSXXStubs.c.

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
{
    Display *display;
    Screen *screen;
    int fd = 0;
    static NSRect maxBounds = {{0, 0}, {0, 0}};
    static char vendor[25] = "";
    NSArray *cgVers;


    if (gMacDisplay != NULL) {
	if (strcmp(gMacDisplay->display->display_name, display_name) == 0) {
	    return gMacDisplay;
	} else {
	    return NULL;
	}
    }

    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    display = (Display *) ckalloc(sizeof(Display));
    screen  = (Screen *) ckalloc(sizeof(Screen));
    bzero(display, sizeof(Display));
    bzero(screen, sizeof(Screen));

    display->resource_alloc = MacXIdAlloc;
    display->request	    = 0;






>









<
<







138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154


155
156
157
158
159
160
161
{
    Display *display;
    Screen *screen;
    int fd = 0;
    static NSRect maxBounds = {{0, 0}, {0, 0}};
    static char vendor[25] = "";
    NSArray *cgVers;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    if (gMacDisplay != NULL) {
	if (strcmp(gMacDisplay->display->display_name, display_name) == 0) {
	    return gMacDisplay;
	} else {
	    return NULL;
	}
    }



    display = (Display *) ckalloc(sizeof(Display));
    screen  = (Screen *) ckalloc(sizeof(Screen));
    bzero(display, sizeof(Display));
    bzero(screen, sizeof(Screen));

    display->resource_alloc = MacXIdAlloc;
    display->request	    = 0;

Changes to tests/entry.test.

1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628


1629
1630

















1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
} {1 1 345}

test entry-22.1 {lost namespaced textvar} {
    destroy .e
    namespace eval test { variable foo {a b} }
    entry .e -textvariable ::test::foo
    namespace delete test
    .e insert end "more stuff"
    .e delete 5 end
    catch {set ::test::foo} result
    list [.e get] [.e cget -textvar] $result
} [list "a bmo" ::test::foo \


	{can't read "::test::foo": no such variable}]


















destroy .e

# XXX Still need to write tests for EntryBlinkProc, EntryFocusProc,
# and EntryTextVarProc.

option clear

# cleanup
cleanupTests
return






|
|
|
|

>
>


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










1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
} {1 1 345}

test entry-22.1 {lost namespaced textvar} {
    destroy .e
    namespace eval test { variable foo {a b} }
    entry .e -textvariable ::test::foo
    namespace delete test
    catch {.e insert end "more stuff"} result1
    catch {.e delete 5 end} result2
    catch {set ::test::foo} result3
    list [.e get] [.e cget -textvar] $result1 $result2 $result3
} [list "a bmo" ::test::foo \
	{can't set "::test::foo": parent namespace doesn't exist} \
	{can't set "::test::foo": parent namespace doesn't exist} \
	{can't read "::test::foo": no such variable}]

test entry-23.1 {error in trace proc attached to the textvariable} {
    destroy .e
    trace variable myvar w traceit
    proc traceit args {error "Intentional error here!"}
    entry .e -textvariable myvar
    catch {.e insert end mystring} result1
    catch {.e delete 0} result2
    list $result1 $result2
} [list {can't set "myvar": Intentional error here!} \
    {can't set "myvar": Intentional error here!}]

test entry-24.1 {textvariable lives in a non-existing namespace} {
    destroy .e
    catch {entry .e -textvariable thisnsdoesntexist::myvar} result1
    set result1
} {can't trace "thisnsdoesntexist::myvar": parent namespace doesn't exist}

destroy .e

# XXX Still need to write tests for EntryBlinkProc, EntryFocusProc,
# and EntryTextVarProc.

option clear

# cleanup
cleanupTests
return

Changes to tests/spinbox.test.

1579
1580
1581
1582
1583
1584
1585






















1586
1587
1588
1589
1590
1591
1592
    # still return 1 when disabled, because 'selection get' will work,
    # but selection cannot be changed (new behavior since 8.4)
    .e select to 9
    lappend out [.e selection present] [selection get]
} {1 1 345}

destroy .e






















catch {unset ::e ::vVals}

##
## End validation tests
##

# XXX Still need to write tests for SpinboxBlinkProc, SpinboxFocusProc,






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







1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
    # still return 1 when disabled, because 'selection get' will work,
    # but selection cannot be changed (new behavior since 8.4)
    .e select to 9
    lappend out [.e selection present] [selection get]
} {1 1 345}

destroy .e

test spinbox-24.1 {error in trace proc attached to the textvariable} {
    destroy .s
    trace variable myvar w traceit
    proc traceit args {error "Intentional error here!"}
    spinbox .s -textvariable myvar -from 1 -to 10
    catch {.s set mystring} result1
    catch {.s insert 0 mystring} result2
    catch {.s delete 0} result3
    catch {.s invoke buttonup} result4
    list $result1 $result2 $result3 $result4
} [list {can't set "myvar": Intentional error here!} \
    {can't set "myvar": Intentional error here!} \
    {can't set "myvar": Intentional error here!} \
    {can't set "myvar": Intentional error here!}]

test spinbox-25.1 {textvariable lives in a non-existing namespace} {
    destroy .s
    catch {spinbox .s -textvariable thisnsdoesntexist::myvar} result1
    set result1
} {can't trace "thisnsdoesntexist::myvar": parent namespace doesn't exist}

catch {unset ::e ::vVals}

##
## End validation tests
##

# XXX Still need to write tests for SpinboxBlinkProc, SpinboxFocusProc,