1 /*
2  * tkConsole.c --
3  *
4  *	This file implements a Tcl console for systems that may not otherwise
5  *	have access to a console. It uses the Text widget and provides special
6  *	access via a console command.
7  *
8  * Copyright (c) 1995-1996 Sun Microsystems, Inc.
9  *
10  * See the file "license.terms" for information on usage and redistribution of
11  * this file, and for a DISCLAIMER OF ALL WARRANTIES.
12  */
13 
14 #include "tkInt.h"
15 
16 /*
17  * Each console is associated with an instance of the ConsoleInfo struct.
18  * It keeps track of what interp holds the Tk application that displays
19  * the console, and what interp is controlled by the interactions in that
20  * console.  A refCount permits the struct to be shared as instance data
21  * by commands and by channels.
22  */
23 
24 typedef struct ConsoleInfo {
25     Tcl_Interp *consoleInterp;	/* Interpreter displaying the console. */
26     Tcl_Interp *interp;		/* Interpreter controlled by console. */
27     int refCount;
28 } ConsoleInfo;
29 
30 /*
31  * Each console channel holds an instance of the ChannelData struct as
32  * its instance data.  It contains ConsoleInfo, so the channel can work
33  * with the appropriate console window, and a type value to distinguish
34  * the stdout channel from the stderr channel.
35  */
36 
37 typedef struct ChannelData {
38     ConsoleInfo *info;
39     int type;			/* TCL_STDOUT or TCL_STDERR */
40 } ChannelData;
41 
42 /*
43  * Prototypes for local procedures defined in this file:
44  */
45 
46 static int	ConsoleClose(ClientData instanceData, Tcl_Interp *interp);
47 static int	Console2Close(ClientData instanceData, Tcl_Interp *interp, int flags);
48 static void	ConsoleDeleteProc(ClientData clientData);
49 static void	ConsoleEventProc(ClientData clientData, XEvent *eventPtr);
50 static int	ConsoleHandle(ClientData instanceData, int direction,
51 		    ClientData *handlePtr);
52 static int	ConsoleInput(ClientData instanceData, char *buf, int toRead,
53 		    int *errorCode);
54 static int	ConsoleObjCmd(ClientData clientData, Tcl_Interp *interp,
55 		    int objc, Tcl_Obj *const objv[]);
56 static int	ConsoleOutput(ClientData instanceData, const char *buf,
57 		    int toWrite, int *errorCode);
58 static void	ConsoleWatch(ClientData instanceData, int mask);
59 static void	DeleteConsoleInterp(ClientData clientData);
60 static void	InterpDeleteProc(ClientData clientData, Tcl_Interp *interp);
61 static int	InterpreterObjCmd(ClientData clientData, Tcl_Interp *interp,
62 		    int objc, Tcl_Obj *const objv[]);
63 
64 /*
65  * This structure describes the channel type structure for file based IO:
66  */
67 
68 static const Tcl_ChannelType consoleChannelType = {
69     "console",			/* Type name. */
70     TCL_CHANNEL_VERSION_5,	/* v5 channel */
71     ConsoleClose,		/* Close proc. */
72     ConsoleInput,		/* Input proc. */
73     ConsoleOutput,		/* Output proc. */
74     NULL,			/* Seek proc. */
75     NULL,			/* Set option proc. */
76     NULL,			/* Get option proc. */
77     ConsoleWatch,		/* Watch for events on console. */
78     ConsoleHandle,		/* Get a handle from the device. */
79     Console2Close,			/* close2proc. */
80     NULL,			/* Always non-blocking.*/
81     NULL,			/* flush proc. */
82     NULL,			/* handler proc. */
83     NULL,			/* wide seek proc */
84     NULL,			/* thread action proc */
85     NULL
86 };
87 
88 #ifdef _WIN32
89 #include <windows.h>
90 
91 /*
92  *----------------------------------------------------------------------
93  *
94  * ShouldUseConsoleChannel
95  *
96  *	Check to see if console window should be used for a given standard
97  *	channel.
98  *
99  * Results:
100  *	None.
101  *
102  * Side effects:
103  *	Creates the console channel and installs it as the standard channels.
104  *
105  *----------------------------------------------------------------------
106  */
107 
108 static int
ShouldUseConsoleChannel(int type)109 ShouldUseConsoleChannel(
110     int type)
111 {
112     DWORD handleId;		/* Standard handle to retrieve. */
113     DCB dcb;
114     DWORD consoleParams;
115     DWORD fileType;
116     HANDLE handle;
117 
118     switch (type) {
119     case TCL_STDIN:
120 	handleId = STD_INPUT_HANDLE;
121 	break;
122     case TCL_STDOUT:
123 	handleId = STD_OUTPUT_HANDLE;
124 	break;
125     case TCL_STDERR:
126 	handleId = STD_ERROR_HANDLE;
127 	break;
128     default:
129 	return 0;
130 	break;
131     }
132 
133     handle = GetStdHandle(handleId);
134 
135     /*
136      * Note that we need to check for 0 because Windows will return 0 if this
137      * is not a console mode application, even though this is not a valid
138      * handle.
139      */
140 
141     if ((handle == INVALID_HANDLE_VALUE) || (handle == 0)) {
142 	return 1;
143     }
144 
145     /*
146      * Win2K BUG: GetStdHandle(STD_OUTPUT_HANDLE) can return what appears to
147      * be a valid handle. See TclpGetDefaultStdChannel() for this change
148      * implemented. We didn't change it here because GetFileType() [below]
149      * will catch this with FILE_TYPE_UNKNOWN and appropriately return a value
150      * of 1, anyways.
151      *
152      *    char dummyBuff[1];
153      *    DWORD dummyWritten;
154      *
155      *    if ((type == TCL_STDOUT)
156      *		&& !WriteFile(handle, dummyBuff, 0, &dummyWritten, NULL)) {
157      *	     return 1;
158      *    }
159      */
160 
161     fileType = GetFileType(handle);
162 
163     /*
164      * If the file is a character device, we need to try to figure out whether
165      * it is a serial port, a console, or something else. We test for the
166      * console case first because this is more common.
167      */
168 
169     if (fileType == FILE_TYPE_CHAR) {
170 	dcb.DCBlength = sizeof(DCB);
171 	if (!GetConsoleMode(handle, &consoleParams) &&
172 		!GetCommState(handle, &dcb)) {
173 	    /*
174 	     * Don't use a CHAR type channel for stdio, otherwise Tk runs into
175 	     * trouble with the MS DevStudio debugger.
176 	     */
177 
178 	    return 1;
179 	}
180     } else if (fileType == FILE_TYPE_UNKNOWN) {
181 	return 1;
182     } else if (Tcl_GetStdChannel(type) == NULL) {
183 	return 1;
184     }
185 
186     return 0;
187 }
188 #else
189 /*
190  * Mac should always use a console channel, Unix should if it's trying to
191  */
192 
193 #define ShouldUseConsoleChannel(chan) (1)
194 #endif
195 
196 /*
197  *----------------------------------------------------------------------
198  *
199  * Tk_InitConsoleChannels --
200  *
201  * 	Create the console channels and install them as the standard channels.
202  * 	All I/O will be discarded until Tk_CreateConsoleWindow is called to
203  * 	attach the console to a text widget.
204  *
205  * Results:
206  *	None.
207  *
208  * Side effects:
209  *	Creates the console channel and installs it as the standard channels.
210  *
211  *----------------------------------------------------------------------
212  */
213 
214 void
Tk_InitConsoleChannels(Tcl_Interp * interp)215 Tk_InitConsoleChannels(
216     Tcl_Interp *interp)
217 {
218     static Tcl_ThreadDataKey consoleInitKey;
219     int *consoleInitPtr, doIn, doOut, doErr;
220     ConsoleInfo *info;
221     Tcl_Channel consoleChannel;
222 
223     /*
224      * Ensure that we are getting a compatible version of Tcl.
225      */
226 
227     if (Tcl_InitStubs(interp, "8.6", 0) == NULL) {
228         return;
229     }
230 
231     consoleInitPtr = (int *)Tcl_GetThreadData(&consoleInitKey, (int) sizeof(int));
232     if (*consoleInitPtr) {
233 	/*
234 	 * We've already initialized console channels in this thread.
235 	 */
236 
237 	return;
238     }
239     *consoleInitPtr = 1;
240 
241     doIn = ShouldUseConsoleChannel(TCL_STDIN);
242     doOut = ShouldUseConsoleChannel(TCL_STDOUT);
243     doErr = ShouldUseConsoleChannel(TCL_STDERR);
244 
245     if (!(doIn || doOut || doErr)) {
246 	/*
247 	 * No std channels should be tied to the console; thus, no need to
248 	 * create the console.
249 	 */
250 
251 	return;
252     }
253 
254     /*
255      * At least one std channel wants to be tied to the console, so create the
256      * interp for it to live in.
257      */
258 
259     info = (ConsoleInfo *) ckalloc(sizeof(ConsoleInfo));
260     info->consoleInterp = NULL;
261     info->interp = NULL;
262     info->refCount = 0;
263 
264     if (doIn) {
265 	ChannelData *data = (ChannelData *)ckalloc(sizeof(ChannelData));
266 
267 	data->info = info;
268 	data->info->refCount++;
269 	data->type = TCL_STDIN;
270 	consoleChannel = Tcl_CreateChannel(&consoleChannelType, "console0",
271 		data, TCL_READABLE);
272 	if (consoleChannel != NULL) {
273 	    Tcl_SetChannelOption(NULL, consoleChannel, "-translation", "lf");
274 	    Tcl_SetChannelOption(NULL, consoleChannel, "-buffering", "none");
275 	    Tcl_SetChannelOption(NULL, consoleChannel, "-encoding", "utf-8");
276 	}
277 	Tcl_SetStdChannel(consoleChannel, TCL_STDIN);
278 	Tcl_RegisterChannel(NULL, consoleChannel);
279     }
280 
281     if (doOut) {
282 	ChannelData *data = (ChannelData *)ckalloc(sizeof(ChannelData));
283 
284 	data->info = info;
285 	data->info->refCount++;
286 	data->type = TCL_STDOUT;
287 	consoleChannel = Tcl_CreateChannel(&consoleChannelType, "console1",
288 		data, TCL_WRITABLE);
289 	if (consoleChannel != NULL) {
290 	    Tcl_SetChannelOption(NULL, consoleChannel, "-translation", "lf");
291 	    Tcl_SetChannelOption(NULL, consoleChannel, "-buffering", "none");
292 	    Tcl_SetChannelOption(NULL, consoleChannel, "-encoding", "utf-8");
293 	}
294 	Tcl_SetStdChannel(consoleChannel, TCL_STDOUT);
295 	Tcl_RegisterChannel(NULL, consoleChannel);
296     }
297 
298     if (doErr) {
299 	ChannelData *data = (ChannelData *)ckalloc(sizeof(ChannelData));
300 
301 	data->info = info;
302 	data->info->refCount++;
303 	data->type = TCL_STDERR;
304 	consoleChannel = Tcl_CreateChannel(&consoleChannelType, "console2",
305 		data, TCL_WRITABLE);
306 	if (consoleChannel != NULL) {
307 	    Tcl_SetChannelOption(NULL, consoleChannel, "-translation", "lf");
308 	    Tcl_SetChannelOption(NULL, consoleChannel, "-buffering", "none");
309 	    Tcl_SetChannelOption(NULL, consoleChannel, "-encoding", "utf-8");
310 	}
311 	Tcl_SetStdChannel(consoleChannel, TCL_STDERR);
312 	Tcl_RegisterChannel(NULL, consoleChannel);
313     }
314 }
315 
316 /*
317  *----------------------------------------------------------------------
318  *
319  * Tk_CreateConsoleWindow --
320  *
321  *	Initialize the console. This code actually creates a new application
322  *	and associated interpreter. This effectively hides the implementation
323  *	from the main application.
324  *
325  * Results:
326  *	None.
327  *
328  * Side effects:
329  *	A new console it created.
330  *
331  *----------------------------------------------------------------------
332  */
333 
334 int
Tk_CreateConsoleWindow(Tcl_Interp * interp)335 Tk_CreateConsoleWindow(
336     Tcl_Interp *interp)		/* Interpreter to use for prompting. */
337 {
338     Tcl_Channel chan;
339     ConsoleInfo *info;
340     Tk_Window mainWindow;
341     Tcl_Command token;
342     int result = TCL_OK;
343     int haveConsoleChannel = 1;
344 
345     /* Init an interp with Tcl and Tk */
346     Tcl_Interp *consoleInterp = Tcl_CreateInterp();
347     if (Tcl_Init(consoleInterp) != TCL_OK) {
348 	Tcl_Obj *result_obj = Tcl_GetObjResult(consoleInterp);
349 	Tcl_SetObjResult(interp, result_obj);
350 	goto error;
351     }
352     if (Tk_Init(consoleInterp) != TCL_OK) {
353 	Tcl_Obj *result_obj = Tcl_GetObjResult(consoleInterp);
354 	Tcl_SetObjResult(interp, result_obj);
355 	goto error;
356     }
357 
358     /*
359      * Fetch the instance data from whatever std channel is a
360      * console channel.  If none, create fresh instance data.
361      */
362 
363     if (Tcl_GetChannelType(chan = Tcl_GetStdChannel(TCL_STDIN))
364 	    == &consoleChannelType) {
365     } else if (Tcl_GetChannelType(chan = Tcl_GetStdChannel(TCL_STDOUT))
366 	    == &consoleChannelType) {
367     } else if (Tcl_GetChannelType(chan = Tcl_GetStdChannel(TCL_STDERR))
368 	    == &consoleChannelType) {
369     } else {
370 	haveConsoleChannel = 0;
371     }
372 
373     if (haveConsoleChannel) {
374 	ChannelData *data = (ChannelData *) Tcl_GetChannelInstanceData(chan);
375 	info = data->info;
376 	if (info->consoleInterp) {
377 	    /*
378 	     * New ConsoleInfo for a new console window.
379 	     */
380 
381 	    info = (ConsoleInfo *)ckalloc(sizeof(ConsoleInfo));
382 	    info->refCount = 0;
383 
384 	    /*
385 	     * Update any console channels to make use of the new console.
386 	     */
387 
388 	    if (Tcl_GetChannelType(chan = Tcl_GetStdChannel(TCL_STDIN))
389 		    == &consoleChannelType) {
390 		data = (ChannelData *) Tcl_GetChannelInstanceData(chan);
391 		data->info->refCount--;
392 		data->info = info;
393 		data->info->refCount++;
394 	    }
395 	    if (Tcl_GetChannelType(chan = Tcl_GetStdChannel(TCL_STDOUT))
396 		    == &consoleChannelType) {
397 		data = (ChannelData *) Tcl_GetChannelInstanceData(chan);
398 		data->info->refCount--;
399 		data->info = info;
400 		data->info->refCount++;
401 	    }
402 	    if (Tcl_GetChannelType(chan = Tcl_GetStdChannel(TCL_STDERR))
403 		    == &consoleChannelType) {
404 		data = (ChannelData *) Tcl_GetChannelInstanceData(chan);
405 		data->info->refCount--;
406 		data->info = info;
407 		data->info->refCount++;
408 	    }
409 	}
410     } else {
411 	info = (ConsoleInfo *)ckalloc(sizeof(ConsoleInfo));
412 	info->refCount = 0;
413     }
414 
415     info->consoleInterp = consoleInterp;
416     info->interp = interp;
417 
418     Tcl_CallWhenDeleted(consoleInterp, InterpDeleteProc, info);
419     info->refCount++;
420     Tcl_CreateThreadExitHandler(DeleteConsoleInterp, consoleInterp);
421 
422     /*
423      * Add console commands to the interp
424      */
425 
426     token = Tcl_CreateObjCommand(interp, "console", ConsoleObjCmd, info,
427 	    ConsoleDeleteProc);
428     info->refCount++;
429 
430     /*
431      * We don't have to count the ref held by the [consoleinterp] command
432      * in the consoleInterp.  The ref held by the consoleInterp delete
433      * handler takes care of us.
434      */
435     Tcl_CreateObjCommand(consoleInterp, "consoleinterp", InterpreterObjCmd,
436 	    info, NULL);
437 
438     mainWindow = Tk_MainWindow(interp);
439     if (mainWindow) {
440 	Tk_CreateEventHandler(mainWindow, StructureNotifyMask,
441 		ConsoleEventProc, info);
442 	info->refCount++;
443     }
444 
445     Tcl_Preserve(consoleInterp);
446     result = Tcl_EvalEx(consoleInterp, "source $tk_library/console.tcl",
447 	    -1, TCL_EVAL_GLOBAL);
448     if (result == TCL_ERROR) {
449 	Tcl_SetReturnOptions(interp,
450 		Tcl_GetReturnOptions(consoleInterp, result));
451 	Tcl_SetObjResult(interp, Tcl_GetObjResult(consoleInterp));
452     }
453     Tcl_Release(consoleInterp);
454     if (result == TCL_ERROR) {
455 	Tcl_DeleteCommandFromToken(interp, token);
456 	mainWindow = Tk_MainWindow(interp);
457 	if (mainWindow) {
458 	    Tk_DeleteEventHandler(mainWindow, StructureNotifyMask,
459 		    ConsoleEventProc, info);
460 	    if (info->refCount-- <= 1) {
461 		ckfree(info);
462 	    }
463 	}
464 	goto error;
465     }
466     return TCL_OK;
467 
468   error:
469     Tcl_AddErrorInfo(interp, "\n    (creating console window)");
470     if (!Tcl_InterpDeleted(consoleInterp)) {
471 	Tcl_DeleteInterp(consoleInterp);
472     }
473     return TCL_ERROR;
474 }
475 
476 /*
477  *----------------------------------------------------------------------
478  *
479  * ConsoleOutput--
480  *
481  *	Writes the given output on the IO channel. Returns count of how many
482  *	characters were actually written, and an error indication.
483  *
484  * Results:
485  *	A count of how many characters were written is returned and an error
486  *	indication is returned in an output argument.
487  *
488  * Side effects:
489  *	Writes output on the actual channel.
490  *
491  *----------------------------------------------------------------------
492  */
493 
494 static int
ConsoleOutput(ClientData instanceData,const char * buf,int toWrite,int * errorCode)495 ConsoleOutput(
496     ClientData instanceData,	/* Indicates which device to use. */
497     const char *buf,		/* The data buffer. */
498     int toWrite,		/* How many bytes to write? */
499     int *errorCode)		/* Where to store error code. */
500 {
501     ChannelData *data = (ChannelData *)instanceData;
502     ConsoleInfo *info = data->info;
503 
504     *errorCode = 0;
505     Tcl_SetErrno(0);
506 
507     if (info) {
508 	Tcl_Interp *consoleInterp = info->consoleInterp;
509 
510 	if (consoleInterp && !Tcl_InterpDeleted(consoleInterp)) {
511 	    Tcl_DString ds;
512 	    Tcl_Encoding utf8 = Tcl_GetEncoding(NULL, "utf-8");
513 
514 	    /*
515 	     * Not checking for utf8 == NULL.  Did not check for TCL_ERROR
516 	     * from Tcl_SetChannelOption() in Tk_InitConsoleChannels() either.
517 	     * Assumption is utf-8 Tcl_Encoding is reliably present.
518 	     */
519 
520 	    const char *bytes
521 		    = Tcl_ExternalToUtfDString(utf8, buf, toWrite, &ds);
522 	    int numBytes = Tcl_DStringLength(&ds);
523 	    Tcl_Obj *cmd = Tcl_NewStringObj("tk::ConsoleOutput", -1);
524 
525 	    Tcl_FreeEncoding(utf8);
526 
527 	    if (data->type == TCL_STDERR) {
528 		Tcl_ListObjAppendElement(NULL, cmd,
529 			Tcl_NewStringObj("stderr", -1));
530 	    } else {
531 		Tcl_ListObjAppendElement(NULL, cmd,
532 			Tcl_NewStringObj("stdout", -1));
533 	    }
534 	    Tcl_ListObjAppendElement(NULL, cmd,
535 		    Tcl_NewStringObj(bytes, numBytes));
536 
537 	    Tcl_DStringFree(&ds);
538 	    Tcl_IncrRefCount(cmd);
539 	    Tcl_EvalObjEx(consoleInterp, cmd, TCL_EVAL_GLOBAL);
540 	    Tcl_DecrRefCount(cmd);
541 	}
542     }
543     return toWrite;
544 }
545 
546 /*
547  *----------------------------------------------------------------------
548  *
549  * ConsoleInput --
550  *
551  *	Read input from the console. Not currently implemented.
552  *
553  * Results:
554  *	Always returns EOF.
555  *
556  * Side effects:
557  *	None.
558  *
559  *----------------------------------------------------------------------
560  */
561 
562 static int
ConsoleInput(TCL_UNUSED (void *),TCL_UNUSED (char *),TCL_UNUSED (int),TCL_UNUSED (int *))563 ConsoleInput(
564     TCL_UNUSED(void *),
565     TCL_UNUSED(char *),			/* Where to store data read. */
566     TCL_UNUSED(int),		/* How much space is available in the
567 				 * buffer? */
568     TCL_UNUSED(int *))		/* Where to store error code. */
569 {
570     return 0;			/* Always return EOF. */
571 }
572 
573 /*
574  *----------------------------------------------------------------------
575  *
576  * ConsoleClose/Console2Close --
577  *
578  *	Closes the IO channel.
579  *
580  * Results:
581  *	Always returns 0 (success).
582  *
583  * Side effects:
584  *	Frees the dummy file associated with the channel.
585  *
586  *----------------------------------------------------------------------
587  */
588 
589 static int
ConsoleClose(ClientData instanceData,TCL_UNUSED (Tcl_Interp *))590 ConsoleClose(
591     ClientData instanceData,
592     TCL_UNUSED(Tcl_Interp *))
593 {
594     ChannelData *data = (ChannelData *)instanceData;
595     ConsoleInfo *info = data->info;
596 
597     if (info) {
598 	if (info->refCount-- <= 1) {
599 	    /*
600 	     * Assuming the Tcl_Interp * fields must already be NULL.
601 	     */
602 
603 	    ckfree(info);
604 	}
605     }
606     ckfree(data);
607     return 0;
608 }
609 
610 static int
Console2Close(ClientData instanceData,Tcl_Interp * interp,int flags)611 Console2Close(
612     ClientData instanceData,	/* Unused. */
613     Tcl_Interp *interp,		/* Unused. */
614     int flags)
615 {
616     if ((flags&(TCL_CLOSE_READ|TCL_CLOSE_WRITE))==0) {
617 	return ConsoleClose(instanceData, interp);
618     }
619     return EINVAL;
620 }
621 
622 /*
623  *----------------------------------------------------------------------
624  *
625  * ConsoleWatch --
626  *
627  *	Called by the notifier to set up the console device so that events
628  *	will be noticed. Since there are no events on the console, this
629  *	routine just returns without doing anything.
630  *
631  * Results:
632  *	None.
633  *
634  * Side effects:
635  *	None.
636  *
637  *----------------------------------------------------------------------
638  */
639 
640 static void
ConsoleWatch(TCL_UNUSED (void *),TCL_UNUSED (int))641 ConsoleWatch(
642     TCL_UNUSED(void *),	/* Device ID for the channel. */
643     TCL_UNUSED(int))			/* OR-ed combination of TCL_READABLE,
644 				 * TCL_WRITABLE and TCL_EXCEPTION, for the
645 				 * events we are interested in. */
646 {
647 }
648 
649 /*
650  *----------------------------------------------------------------------
651  *
652  * ConsoleHandle --
653  *
654  *	Invoked by the generic IO layer to get a handle from a channel.
655  *	Because console channels are not devices, this function always fails.
656  *
657  * Results:
658  *	Always returns TCL_ERROR.
659  *
660  * Side effects:
661  *	None.
662  *
663  *----------------------------------------------------------------------
664  */
665 
666 static int
ConsoleHandle(TCL_UNUSED (void *),TCL_UNUSED (int),TCL_UNUSED (void **))667 ConsoleHandle(
668     TCL_UNUSED(void *),	/* Device ID for the channel. */
669     TCL_UNUSED(int),		/* TCL_READABLE or TCL_WRITABLE to indicate
670 				 * which direction of the channel is being
671 				 * requested. */
672     TCL_UNUSED(void **))	/* Where to store handle */
673 {
674     return TCL_ERROR;
675 }
676 
677 /*
678  *----------------------------------------------------------------------
679  *
680  * ConsoleObjCmd --
681  *
682  *	The console command implements a Tcl interface to the various console
683  *	options.
684  *
685  * Results:
686  *	A standard Tcl result.
687  *
688  * Side effects:
689  *	See the user documentation.
690  *
691  *----------------------------------------------------------------------
692  */
693 
694 static int
ConsoleObjCmd(ClientData clientData,Tcl_Interp * interp,int objc,Tcl_Obj * const objv[])695 ConsoleObjCmd(
696     ClientData clientData,	/* Access to the console interp */
697     Tcl_Interp *interp,		/* Current interpreter */
698     int objc,			/* Number of arguments */
699     Tcl_Obj *const objv[])	/* Argument objects */
700 {
701     int index, result;
702     static const char *const options[] = {
703 	"eval", "hide", "show", "title", NULL};
704     enum option {CON_EVAL, CON_HIDE, CON_SHOW, CON_TITLE};
705     Tcl_Obj *cmd = NULL;
706     ConsoleInfo *info = (ConsoleInfo *)clientData;
707     Tcl_Interp *consoleInterp = info->consoleInterp;
708 
709     if (objc < 2) {
710 	Tcl_WrongNumArgs(interp, 1, objv, "option ?arg?");
711 	return TCL_ERROR;
712     }
713     if (Tcl_GetIndexFromObjStruct(interp, objv[1], options,
714 	    sizeof(char *), "option", 0, &index) != TCL_OK) {
715 	return TCL_ERROR;
716     }
717 
718     switch ((enum option) index) {
719     case CON_EVAL:
720 	if (objc != 3) {
721 	    Tcl_WrongNumArgs(interp, 2, objv, "script");
722 	    return TCL_ERROR;
723 	}
724 	cmd = objv[2];
725 	break;
726     case CON_HIDE:
727 	if (objc != 2) {
728 	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
729 	    return TCL_ERROR;
730 	}
731 	cmd = Tcl_NewStringObj("wm withdraw .", -1);
732 	break;
733     case CON_SHOW:
734 	if (objc != 2) {
735 	    Tcl_WrongNumArgs(interp, 2, objv, NULL);
736 	    return TCL_ERROR;
737 	}
738 	cmd = Tcl_NewStringObj("wm deiconify .", -1);
739 	break;
740     case CON_TITLE:
741 	if (objc > 3) {
742 	    Tcl_WrongNumArgs(interp, 2, objv, "?title?");
743 	    return TCL_ERROR;
744 	}
745 	cmd = Tcl_NewStringObj("wm title .", -1);
746 	if (objc == 3) {
747 	    Tcl_ListObjAppendElement(NULL, cmd, objv[2]);
748 	}
749 	break;
750     default:
751 	CLANG_ASSERT(0);
752     }
753 
754     Tcl_IncrRefCount(cmd);
755     if (consoleInterp && !Tcl_InterpDeleted(consoleInterp)) {
756 	Tcl_Preserve(consoleInterp);
757 	result = Tcl_EvalObjEx(consoleInterp, cmd, TCL_EVAL_GLOBAL);
758 	Tcl_SetReturnOptions(interp,
759 		Tcl_GetReturnOptions(consoleInterp, result));
760 	Tcl_SetObjResult(interp, Tcl_GetObjResult(consoleInterp));
761 	Tcl_Release(consoleInterp);
762     } else {
763 	Tcl_SetObjResult(interp, Tcl_NewStringObj(
764 		"no active console interp", -1));
765 	Tcl_SetErrorCode(interp, "TK", "CONSOLE", "NONE", NULL);
766 	result = TCL_ERROR;
767     }
768     Tcl_DecrRefCount(cmd);
769     return result;
770 }
771 
772 /*
773  *----------------------------------------------------------------------
774  *
775  * InterpreterObjCmd --
776  *
777  *	This command allows the console interp to communicate with the main
778  *	interpreter.
779  *
780  * Results:
781  *	A standard Tcl result.
782  *
783  *----------------------------------------------------------------------
784  */
785 
786 static int
InterpreterObjCmd(ClientData clientData,Tcl_Interp * interp,int objc,Tcl_Obj * const objv[])787 InterpreterObjCmd(
788     ClientData clientData,	/* */
789     Tcl_Interp *interp,		/* Current interpreter */
790     int objc,			/* Number of arguments */
791     Tcl_Obj *const objv[])	/* Argument objects */
792 {
793     int index, result = TCL_OK;
794     static const char *const options[] = {"eval", "record", NULL};
795     enum option {OTHER_EVAL, OTHER_RECORD};
796     ConsoleInfo *info = (ConsoleInfo *)clientData;
797     Tcl_Interp *otherInterp = info->interp;
798 
799     if (objc < 2) {
800 	Tcl_WrongNumArgs(interp, 1, objv, "option arg");
801 	return TCL_ERROR;
802     }
803     if (Tcl_GetIndexFromObjStruct(interp, objv[1], options,
804 	    sizeof(char *), "option", 0, &index) != TCL_OK) {
805 	return TCL_ERROR;
806     }
807 
808     if (objc != 3) {
809 	Tcl_WrongNumArgs(interp, 2, objv, "script");
810 	return TCL_ERROR;
811     }
812 
813     if ((otherInterp == NULL) || Tcl_InterpDeleted(otherInterp)) {
814 	Tcl_SetObjResult(interp, Tcl_NewStringObj(
815 		"no active parent interp", -1));
816 	Tcl_SetErrorCode(interp, "TK", "CONSOLE", "NO_INTERP", NULL);
817 	return TCL_ERROR;
818     }
819 
820     Tcl_Preserve(otherInterp);
821     switch ((enum option) index) {
822     case OTHER_EVAL:
823    	result = Tcl_EvalObjEx(otherInterp, objv[2], TCL_EVAL_GLOBAL);
824 
825 	/*
826 	 * TODO: Should exceptions be filtered here?
827 	 */
828 
829 	Tcl_SetReturnOptions(interp,
830 		Tcl_GetReturnOptions(otherInterp, result));
831 	Tcl_SetObjResult(interp, Tcl_GetObjResult(otherInterp));
832 	break;
833     case OTHER_RECORD:
834    	Tcl_RecordAndEvalObj(otherInterp, objv[2], TCL_EVAL_GLOBAL);
835 
836 	/*
837 	 * By not setting result, we discard any exceptions or errors here and
838 	 * always return TCL_OK. All the caller wants is the interp result to
839 	 * display, whether that's result or error message.
840 	 */
841 
842 	Tcl_SetObjResult(interp, Tcl_GetObjResult(otherInterp));
843 	break;
844     }
845     Tcl_Release(otherInterp);
846     return result;
847 }
848 
849 /*
850  *----------------------------------------------------------------------
851  *
852  * DeleteConsoleInterp --
853  *
854  *	Thread exit handler to destroy a console interp when the thread it
855  *	lives in gets torn down.
856  *
857  *----------------------------------------------------------------------
858  */
859 
860 static void
DeleteConsoleInterp(ClientData clientData)861 DeleteConsoleInterp(
862     ClientData clientData)
863 {
864     Tcl_Interp *interp = (Tcl_Interp *)clientData;
865 
866     Tcl_DeleteInterp(interp);
867 }
868 
869 /*
870  *----------------------------------------------------------------------
871  *
872  * InterpDeleteProc --
873  *
874  *	React when the interp in which the console is displayed is deleted for
875  *	any reason.
876  *
877  * Results:
878  *	None.
879  *
880  * Side effects:
881  *	A new console it created.
882  *
883  *----------------------------------------------------------------------
884  */
885 
886 static void
InterpDeleteProc(ClientData clientData,Tcl_Interp * interp)887 InterpDeleteProc(
888     ClientData clientData,
889     Tcl_Interp *interp)
890 {
891     ConsoleInfo *info = (ConsoleInfo *)clientData;
892 
893     if (info->consoleInterp == interp) {
894 	Tcl_DeleteThreadExitHandler(DeleteConsoleInterp, info->consoleInterp);
895 	info->consoleInterp = NULL;
896     }
897     if (info->refCount-- <= 1) {
898 	ckfree(info);
899     }
900 }
901 
902 /*
903  *----------------------------------------------------------------------
904  *
905  * ConsoleDeleteProc --
906  *
907  *	If the console command is deleted we destroy the console window and
908  *	all associated data structures.
909  *
910  * Results:
911  *	None.
912  *
913  * Side effects:
914  *	A new console it created.
915  *
916  *----------------------------------------------------------------------
917  */
918 
919 static void
ConsoleDeleteProc(ClientData clientData)920 ConsoleDeleteProc(
921     ClientData clientData)
922 {
923     ConsoleInfo *info = (ConsoleInfo *)clientData;
924 
925     if (info->consoleInterp) {
926 	Tcl_DeleteInterp(info->consoleInterp);
927     }
928     if (info->refCount-- <= 1) {
929 	ckfree(info);
930     }
931 }
932 
933 /*
934  *----------------------------------------------------------------------
935  *
936  * ConsoleEventProc --
937  *
938  *	This event function is registered on the main window of the child
939  *	interpreter. If the user or a running script causes the main window to
940  *	be destroyed, then we need to inform the console interpreter by
941  *	invoking "::tk::ConsoleExit".
942  *
943  * Results:
944  *	None.
945  *
946  * Side effects:
947  *	Invokes the "::tk::ConsoleExit" command in the console interp.
948  *
949  *----------------------------------------------------------------------
950  */
951 
952 static void
ConsoleEventProc(ClientData clientData,XEvent * eventPtr)953 ConsoleEventProc(
954     ClientData clientData,
955     XEvent *eventPtr)
956 {
957     if (eventPtr->type == DestroyNotify) {
958 	ConsoleInfo *info = (ConsoleInfo *)clientData;
959 	Tcl_Interp *consoleInterp = info->consoleInterp;
960 
961 	if (consoleInterp && !Tcl_InterpDeleted(consoleInterp)) {
962 	    Tcl_EvalEx(consoleInterp, "tk::ConsoleExit", -1, TCL_EVAL_GLOBAL);
963 	}
964 
965 	if (info->refCount-- <= 1) {
966 	    ckfree(info);
967 	}
968     }
969 }
970 
971 /*
972  * Local Variables:
973  * mode: c
974  * c-basic-offset: 4
975  * fill-column: 78
976  * End:
977  */
978