home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / py2s152.zip / Modules / _tkinter.c < prev    next >
C/C++ Source or Header  |  1999-06-27  |  49KB  |  2,228 lines

  1. /***********************************************************
  2. Copyright (C) 1994 Steen Lumholt.
  3. Copyright 1994-1995 by Stichting Mathematisch Centrum, Amsterdam,
  4. The Netherlands.
  5.  
  6.                         All Rights Reserved
  7.  
  8. Permission to use, copy, modify, and distribute this software and its
  9. documentation for any purpose and without fee is hereby granted,
  10. provided that the above copyright notice appear in all copies and that
  11. both that copyright notice and this permission notice appear in
  12. supporting documentation, and that the names of Stichting Mathematisch
  13. Centrum or CWI or Corporation for National Research Initiatives or
  14. CNRI not be used in advertising or publicity pertaining to
  15. distribution of the software without specific, written prior
  16. permission.
  17.  
  18. While CWI is the initial source for this software, a modified version
  19. is made available by the Corporation for National Research Initiatives
  20. (CNRI) at the Internet address ftp://ftp.python.org.
  21.  
  22. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  23. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  24. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  25. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  26. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  27. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  28. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  29. PERFORMANCE OF THIS SOFTWARE.
  30.  
  31. ******************************************************************/
  32.  
  33. /* _tkinter.c -- Interface to libtk.a and libtcl.a. */
  34.  
  35. /* TCL/TK VERSION INFO:
  36.  
  37.    Unix:
  38.     Tcl/Tk 8.0 (even alpha or beta) or 7.6/4.2 are recommended.
  39.     Versions 7.5/4.1 are the earliest versions still supported.
  40.     Versions 7.4/4.0 or Tk 3.x are no longer supported.
  41.  
  42.    Mac and Windows:
  43.     Use Tcl 8.0 if available (even alpha or beta).
  44.     The oldest usable version is 4.1p1/7.5p1.
  45.  
  46.    XXX Further speed-up ideas, involving Tcl 8.0 features:
  47.  
  48.    - In Tcl_Call(), create Tcl objects from the arguments, possibly using
  49.    intelligent mappings between Python objects and Tcl objects (e.g. ints,
  50.    floats and Tcl window pointers could be handled specially).
  51.  
  52.    - Register a new Tcl type, "Python callable", which can be called more
  53.    efficiently and passed to Tcl_EvalObj() directly (if this is possible).
  54.  
  55. */
  56.  
  57.  
  58. #include "Python.h"
  59. #include <ctype.h>
  60.  
  61. #ifdef WITH_THREAD
  62. #include "pythread.h"
  63. #endif
  64.  
  65. #ifdef MS_WINDOWS
  66. #include <windows.h>
  67. #endif
  68.  
  69. #ifdef macintosh
  70. #define MAC_TCL
  71. #include "myselect.h"
  72. #endif
  73.  
  74. #ifdef PYOS_OS2
  75. #include "myselect.h"
  76. #endif
  77.  
  78. #include <tcl.h>
  79. #include <tk.h>
  80.  
  81. #define TKMAJORMINOR (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION)
  82.  
  83. #if TKMAJORMINOR < 4001
  84.     #error "Tk 4.0 or 3.x are not supported -- use 4.1 or higher"
  85. #endif
  86.  
  87. #if TKMAJORMINOR >= 8000 && defined(macintosh)
  88. /* Sigh, we have to include this to get at the tcl qd pointer */
  89. #include <tkMac.h>
  90. /* And this one we need to clear the menu bar */
  91. #include <Menus.h>
  92. #endif
  93.  
  94. #if TKMAJORMINOR < 8000 || !defined(MS_WINDOWS)
  95. #define HAVE_CREATEFILEHANDLER
  96. #endif
  97.  
  98. #ifdef HAVE_CREATEFILEHANDLER
  99.  
  100. /* Tcl_CreateFileHandler() changed several times; these macros deal with the
  101.    messiness.  In Tcl 8.0 and later, it is not available on Windows (and on
  102.    Unix, only because Jack added it back); when available on Windows, it only
  103.    applies to sockets. */
  104.  
  105. #ifdef MS_WINDOWS
  106. #define FHANDLETYPE TCL_WIN_SOCKET
  107. #else
  108. #define FHANDLETYPE TCL_UNIX_FD
  109. #endif
  110.  
  111. #if TKMAJORMINOR < 8000
  112. #define FHANDLE Tcl_File
  113. #define MAKEFHANDLE(fd) Tcl_GetFile((ClientData)(fd), FHANDLETYPE)
  114. #else
  115. #define FHANDLE int
  116. #define MAKEFHANDLE(fd) (fd)
  117. #endif
  118.  
  119. /* If Tcl can wait for a Unix file descriptor, define the EventHook() routine
  120.    which uses this to handle Tcl events while the user is typing commands. */
  121.  
  122. #if FHANDLETYPE == TCL_UNIX_FD
  123. #define WAIT_FOR_STDIN
  124. #endif
  125.  
  126. #endif /* HAVE_CREATEFILEHANDLER */
  127.  
  128. #ifdef MS_WINDOWS
  129. #include <conio.h>
  130. #define WAIT_FOR_STDIN
  131. #endif
  132.  
  133. #ifdef WITH_THREAD
  134.  
  135. /* The threading situation is complicated.  Tcl is not thread-safe, except for
  136.    Tcl 8.1, which will probably remain in alpha status for another 6 months
  137.    (and the README says that Tk will probably remain thread-unsafe forever).
  138.    So we need to use a lock around all uses of Tcl.  Previously, the Python
  139.    interpreter lock was used for this.  However, this causes problems when
  140.    other Python threads need to run while Tcl is blocked waiting for events.
  141.  
  142.    To solve this problem, a separate lock for Tcl is introduced.  Holding it
  143.    is incompatible with holding Python's interpreter lock.  The following four
  144.    macros manipulate both locks together.
  145.  
  146.    ENTER_TCL and LEAVE_TCL are brackets, just like Py_BEGIN_ALLOW_THREADS and
  147.    Py_END_ALLOW_THREADS.  They should be used whenever a call into Tcl is made
  148.    that could call an event handler, or otherwise affect the state of a Tcl
  149.    interpreter.  These assume that the surrounding code has the Python
  150.    interpreter lock; inside the brackets, the Python interpreter lock has been 
  151.    released and the lock for Tcl has been acquired.
  152.  
  153.    Sometimes, it is necessary to have both the Python lock and the Tcl lock.
  154.    (For example, when transferring data from the Tcl interpreter result to a
  155.    Python string object.)  This can be done by using different macros to close
  156.    the ENTER_TCL block: ENTER_OVERLAP reacquires the Python lock (and restores
  157.    the thread state) but doesn't release the Tcl lock; LEAVE_OVERLAP_TCL
  158.    releases the Tcl lock.
  159.  
  160.    By contrast, ENTER_PYTHON and LEAVE_PYTHON are used in Tcl event
  161.    handlers when the handler needs to use Python.  Such event handlers are
  162.    entered while the lock for Tcl is held; the event handler presumably needs
  163.    to use Python.  ENTER_PYTHON releases the lock for Tcl and acquires
  164.    the Python interpreter lock, restoring the appropriate thread state, and
  165.    LEAVE_PYTHON releases the Python interpreter lock and re-acquires the lock
  166.    for Tcl.  It is okay for ENTER_TCL/LEAVE_TCL pairs to be contained inside
  167.    the code between ENTER_PYTHON and LEAVE_PYTHON.
  168.  
  169.    These locks expand to several statements and brackets; they should not be
  170.    used in branches of if statements and the like.
  171.  
  172. */
  173.  
  174. static PyThread_type_lock tcl_lock = 0;
  175. static PyThreadState *tcl_tstate = NULL;
  176.  
  177. #define ENTER_TCL \
  178.     { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
  179.         PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
  180.  
  181. #define LEAVE_TCL \
  182.     tcl_tstate = NULL; PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS}
  183.  
  184. #define ENTER_OVERLAP \
  185.     Py_END_ALLOW_THREADS
  186.  
  187. #define LEAVE_OVERLAP_TCL \
  188.     tcl_tstate = NULL; PyThread_release_lock(tcl_lock); }
  189.  
  190. #define ENTER_PYTHON \
  191.     { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
  192.             PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
  193.  
  194. #define LEAVE_PYTHON \
  195.     { PyThreadState *tstate = PyEval_SaveThread(); \
  196.             PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
  197.  
  198. #else
  199.  
  200. #define ENTER_TCL
  201. #define LEAVE_TCL
  202. #define ENTER_OVERLAP
  203. #define LEAVE_OVERLAP_TCL
  204. #define ENTER_PYTHON
  205. #define LEAVE_PYTHON
  206.  
  207. #endif
  208.  
  209. #ifdef macintosh
  210.  
  211. /*
  212. ** Additional cruft needed by Tcl/Tk on the Mac.
  213. ** This is for Tcl 7.5 and Tk 4.1 (patch release 1).
  214. */
  215.  
  216. /* ckfree() expects a char* */
  217. #define FREECAST (char *)
  218.  
  219. #include <Events.h> /* For EventRecord */
  220.  
  221. typedef int (*TclMacConvertEventPtr) Py_PROTO((EventRecord *eventPtr));
  222. /* They changed the name... */
  223. #if TKMAJORMINOR < 8000
  224. #define Tcl_MacSetEventProc TclMacSetEventProc
  225. #endif
  226. void Tcl_MacSetEventProc Py_PROTO((TclMacConvertEventPtr procPtr));
  227. int TkMacConvertEvent Py_PROTO((EventRecord *eventPtr));
  228.  
  229. staticforward int PyMacConvertEvent Py_PROTO((EventRecord *eventPtr));
  230.  
  231. #if defined(__CFM68K__) && !defined(__USING_STATIC_LIBS__)
  232.     #pragma import on
  233. #endif
  234.  
  235. #include <SIOUX.h>
  236. extern int SIOUXIsAppWindow(WindowPtr);
  237.  
  238. #if defined(__CFM68K__) && !defined(__USING_STATIC_LIBS__)
  239.     #pragma import reset
  240. #endif
  241. #endif /* macintosh */
  242.  
  243. #ifndef FREECAST
  244. #define FREECAST (char *)
  245. #endif
  246.  
  247. /**** Tkapp Object Declaration ****/
  248.  
  249. staticforward PyTypeObject Tkapp_Type;
  250.  
  251. typedef struct {
  252.     PyObject_HEAD
  253.     Tcl_Interp *interp;
  254. } TkappObject;
  255.  
  256. #define Tkapp_Check(v) ((v)->ob_type == &Tkapp_Type)
  257. #define Tkapp_Interp(v) (((TkappObject *) (v))->interp)
  258. #define Tkapp_Result(v) (((TkappObject *) (v))->interp->result)
  259.  
  260. #define DEBUG_REFCNT(v) (printf("DEBUG: id=%p, refcnt=%i\n", \
  261. (void *) v, ((PyObject *) v)->ob_refcnt))
  262.  
  263.  
  264.  
  265. /**** Error Handling ****/
  266.  
  267. static PyObject *Tkinter_TclError;
  268. static int quitMainLoop = 0;
  269. static int errorInCmd = 0;
  270. static PyObject *excInCmd;
  271. static PyObject *valInCmd;
  272. static PyObject *trbInCmd;
  273.  
  274.  
  275.  
  276. static PyObject *
  277. Tkinter_Error(v)
  278.     PyObject *v;
  279. {
  280.     PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
  281.     return NULL;
  282. }
  283.  
  284.  
  285.  
  286. /**** Utils ****/
  287.  
  288. #ifdef WITH_THREAD
  289. #ifndef MS_WINDOWS
  290. #include "mytime.h"
  291. #include "myselect.h"
  292.  
  293. /* Millisecond sleep() for Unix platforms. */
  294.  
  295. static void
  296. Sleep(milli)
  297.     int milli;
  298. {
  299.     /* XXX Too bad if you don't have select(). */
  300.     struct timeval t;
  301.     double frac;
  302.     t.tv_sec = milli/1000;
  303.     t.tv_usec = (milli%1000) * 1000;
  304.     select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
  305. }
  306. #endif /* MS_WINDOWS */
  307. #endif /* WITH_THREAD */
  308.  
  309.  
  310. static char *
  311. AsString(value, tmp)
  312.     PyObject *value;
  313.     PyObject *tmp;
  314. {
  315.     if (PyString_Check(value))
  316.         return PyString_AsString(value);
  317.     else {
  318.         PyObject *v = PyObject_Str(value);
  319.         PyList_Append(tmp, v);
  320.         Py_DECREF(v);
  321.         return PyString_AsString(v);
  322.     }
  323. }
  324.  
  325.  
  326.  
  327. #define ARGSZ 64
  328.  
  329. static char *
  330. Merge(args)
  331.     PyObject *args;
  332. {
  333.     PyObject *tmp = NULL;
  334.     char *argvStore[ARGSZ];
  335.     char **argv = NULL;
  336.     int fvStore[ARGSZ];
  337.     int *fv = NULL;
  338.     int argc = 0, i;
  339.     char *res = NULL;
  340.  
  341.     if (!(tmp = PyList_New(0)))
  342.         return NULL;
  343.  
  344.     argv = argvStore;
  345.     fv = fvStore;
  346.  
  347.     if (args == NULL)
  348.         argc = 0;
  349.  
  350.     else if (!PyTuple_Check(args)) {
  351.         argc = 1;
  352.         fv[0] = 0;
  353.         argv[0] = AsString(args, tmp);
  354.     }
  355.     else {
  356.         argc = PyTuple_Size(args);
  357.  
  358.         if (argc > ARGSZ) {
  359.             argv = (char **)ckalloc(argc * sizeof(char *));
  360.             fv = (int *)ckalloc(argc * sizeof(int));
  361.             if (argv == NULL || fv == NULL) {
  362.                 PyErr_NoMemory();
  363.                 goto finally;
  364.             }
  365.         }
  366.  
  367.         for (i = 0; i < argc; i++) {
  368.             PyObject *v = PyTuple_GetItem(args, i);
  369.             if (PyTuple_Check(v)) {
  370.                 fv[i] = 1;
  371.                 if (!(argv[i] = Merge(v)))
  372.                     goto finally;
  373.             }
  374.             else if (v == Py_None) {
  375.                 argc = i;
  376.                 break;
  377.             }
  378.             else {
  379.                 fv[i] = 0;
  380.                 argv[i] = AsString(v, tmp);
  381.             }
  382.         }
  383.     }
  384.     res = Tcl_Merge(argc, argv);
  385.  
  386.   finally:
  387.     for (i = 0; i < argc; i++)
  388.         if (fv[i]) {
  389.             ckfree(argv[i]);
  390.         }
  391.     if (argv != argvStore)
  392.         ckfree(FREECAST argv);
  393.     if (fv != fvStore)
  394.         ckfree(FREECAST fv);
  395.  
  396.     Py_DECREF(tmp);
  397.     return res;
  398. }
  399.  
  400.  
  401.  
  402. static PyObject *
  403. Split(list)
  404.     char *list;
  405. {
  406.     int argc;
  407.     char **argv;
  408.     PyObject *v;
  409.  
  410.     if (list == NULL) {
  411.         Py_INCREF(Py_None);
  412.         return Py_None;
  413.     }
  414.  
  415.     if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
  416.         /* Not a list.
  417.          * Could be a quoted string containing funnies, e.g. {"}.
  418.          * Return the string itself.
  419.          */
  420.         return PyString_FromString(list);
  421.     }
  422.  
  423.     if (argc == 0)
  424.         v = PyString_FromString("");
  425.     else if (argc == 1)
  426.         v = PyString_FromString(argv[0]);
  427.     else if ((v = PyTuple_New(argc)) != NULL) {
  428.         int i;
  429.         PyObject *w;
  430.  
  431.         for (i = 0; i < argc; i++) {
  432.             if ((w = Split(argv[i])) == NULL) {
  433.                 Py_DECREF(v);
  434.                 v = NULL;
  435.                 break;
  436.             }
  437.             PyTuple_SetItem(v, i, w);
  438.         }
  439.     }
  440.     Tcl_Free(FREECAST argv);
  441.     return v;
  442. }
  443.  
  444.  
  445.  
  446. /**** Tkapp Object ****/
  447.  
  448. #ifndef WITH_APPINIT
  449. int
  450. Tcl_AppInit(interp)
  451.     Tcl_Interp *interp;
  452. {
  453.     Tk_Window main;
  454.  
  455.     main = Tk_MainWindow(interp);
  456.     if (Tcl_Init(interp) == TCL_ERROR) {
  457.         PySys_WriteStderr("Tcl_Init error: %s\n", interp->result);
  458.         return TCL_ERROR;
  459.     }
  460.     if (Tk_Init(interp) == TCL_ERROR) {
  461.         PySys_WriteStderr("Tk_Init error: %s\n", interp->result);
  462.         return TCL_ERROR;
  463.     }
  464.     return TCL_OK;
  465. }
  466. #endif /* !WITH_APPINIT */
  467.  
  468.  
  469.  
  470.  
  471. /* Initialize the Tk application; see the `main' function in
  472.  * `tkMain.c'.
  473.  */
  474.  
  475. static void EnableEventHook(); /* Forward */
  476. static void DisableEventHook(); /* Forward */
  477.  
  478. static TkappObject *
  479. Tkapp_New(screenName, baseName, className, interactive)
  480.     char *screenName;
  481.     char *baseName;
  482.     char *className;
  483.     int interactive;
  484. {
  485.     TkappObject *v;
  486.     char *argv0;
  487.   
  488.     v = PyObject_NEW(TkappObject, &Tkapp_Type);
  489.     if (v == NULL)
  490.         return NULL;
  491.  
  492.     v->interp = Tcl_CreateInterp();
  493.  
  494. #if defined(macintosh) && TKMAJORMINOR >= 8000
  495.     /* This seems to be needed since Tk 8.0 */
  496.     ClearMenuBar();
  497.     TkMacInitMenus(v->interp);
  498. #endif
  499.     /* Delete the 'exit' command, which can screw things up */
  500.     Tcl_DeleteCommand(v->interp, "exit");
  501.  
  502.     if (screenName != NULL)
  503.         Tcl_SetVar2(v->interp, "env", "DISPLAY",
  504.                 screenName, TCL_GLOBAL_ONLY);
  505.  
  506.     if (interactive)
  507.         Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
  508.     else
  509.         Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
  510.  
  511.     /* This is used to get the application class for Tk 4.1 and up */
  512.     argv0 = (char*)ckalloc(strlen(className) + 1);
  513.     if (!argv0) {
  514.         PyErr_NoMemory();
  515.         Py_DECREF(v);
  516.         return NULL;
  517.     }
  518.  
  519.     strcpy(argv0, className);
  520.     if (isupper((int)(argv0[0])))
  521.         argv0[0] = tolower(argv0[0]);
  522.     Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
  523.     ckfree(argv0);
  524.  
  525.     if (Tcl_AppInit(v->interp) != TCL_OK)
  526.         return (TkappObject *)Tkinter_Error((PyObject *)v);
  527.  
  528.     EnableEventHook();
  529.  
  530.     return v;
  531. }
  532.  
  533.  
  534.  
  535. /** Tcl Eval **/
  536.  
  537. static PyObject *
  538. Tkapp_Call(self, args)
  539.     PyObject *self;
  540.     PyObject *args;
  541. {
  542.     /* This is copied from Merge() */
  543.     PyObject *tmp = NULL;
  544.     char *argvStore[ARGSZ];
  545.     char **argv = NULL;
  546.     int fvStore[ARGSZ];
  547.     int *fv = NULL;
  548.     int argc = 0, i;
  549.     PyObject *res = NULL; /* except this has a different type */
  550.     Tcl_CmdInfo info; /* and this is added */
  551.     Tcl_Interp *interp = Tkapp_Interp(self); /* and this too */
  552.  
  553.     if (!(tmp = PyList_New(0)))
  554.         return NULL;
  555.  
  556.     argv = argvStore;
  557.     fv = fvStore;
  558.  
  559.     if (args == NULL)
  560.         argc = 0;
  561.  
  562.     else if (!PyTuple_Check(args)) {
  563.         argc = 1;
  564.         fv[0] = 0;
  565.         argv[0] = AsString(args, tmp);
  566.     }
  567.     else {
  568.         argc = PyTuple_Size(args);
  569.  
  570.         if (argc > ARGSZ) {
  571.             argv = (char **)ckalloc(argc * sizeof(char *));
  572.             fv = (int *)ckalloc(argc * sizeof(int));
  573.             if (argv == NULL || fv == NULL) {
  574.                 PyErr_NoMemory();
  575.                 goto finally;
  576.             }
  577.         }
  578.  
  579.         for (i = 0; i < argc; i++) {
  580.             PyObject *v = PyTuple_GetItem(args, i);
  581.             if (PyTuple_Check(v)) {
  582.                 fv[i] = 1;
  583.                 if (!(argv[i] = Merge(v)))
  584.                     goto finally;
  585.             }
  586.             else if (v == Py_None) {
  587.                 argc = i;
  588.                 break;
  589.             }
  590.             else {
  591.                 fv[i] = 0;
  592.                 argv[i] = AsString(v, tmp);
  593.             }
  594.         }
  595.     }
  596.     /* End code copied from Merge() */
  597.  
  598.     /* All this to avoid a call to Tcl_Merge() and the corresponding call
  599.        to Tcl_SplitList() inside Tcl_Eval()...  It can save a bundle! */
  600.     if (Py_VerboseFlag >= 2) {
  601.         for (i = 0; i < argc; i++)
  602.             PySys_WriteStderr("%s ", argv[i]);
  603.     }
  604.     ENTER_TCL
  605.     info.proc = NULL;
  606.     if (argc < 1 ||
  607.         !Tcl_GetCommandInfo(interp, argv[0], &info) ||
  608.         info.proc == NULL)
  609.     {
  610.         char *cmd;
  611.         cmd = Tcl_Merge(argc, argv);
  612.         i = Tcl_Eval(interp, cmd);
  613.         ckfree(cmd);
  614.     }
  615.     else {
  616.         Tcl_ResetResult(interp);
  617.         i = (*info.proc)(info.clientData, interp, argc, argv);
  618.     }
  619.     ENTER_OVERLAP
  620.     if (info.proc == NULL && Py_VerboseFlag >= 2)
  621.         PySys_WriteStderr("... use TclEval ");
  622.     if (i == TCL_ERROR) {
  623.         if (Py_VerboseFlag >= 2)
  624.             PySys_WriteStderr("... error: '%s'\n",
  625.                 interp->result);
  626.         Tkinter_Error(self);
  627.     }
  628.     else {
  629.         if (Py_VerboseFlag >= 2)
  630.             PySys_WriteStderr("-> '%s'\n", interp->result);
  631.         res = PyString_FromString(interp->result);
  632.     }
  633.     LEAVE_OVERLAP_TCL
  634.  
  635.     /* Copied from Merge() again */
  636.   finally:
  637.     for (i = 0; i < argc; i++)
  638.         if (fv[i]) {
  639.             ckfree(argv[i]);
  640.         }
  641.     if (argv != argvStore)
  642.         ckfree(FREECAST argv);
  643.     if (fv != fvStore)
  644.         ckfree(FREECAST fv);
  645.  
  646.     Py_DECREF(tmp);
  647.     return res;
  648. }
  649.  
  650.  
  651. static PyObject *
  652. Tkapp_GlobalCall(self, args)
  653.     PyObject *self;
  654.     PyObject *args;
  655. {
  656.     /* Could do the same here as for Tkapp_Call(), but this is not used
  657.        much, so I can't be bothered.  Unfortunately Tcl doesn't export a
  658.        way for the user to do what all its Global* variants do (save and
  659.        reset the scope pointer, call the local version, restore the saved
  660.        scope pointer). */
  661.  
  662.     char *cmd;
  663.     PyObject *res = NULL;
  664.  
  665.     cmd  = Merge(args);
  666.     if (!cmd)
  667.         PyErr_SetString(Tkinter_TclError, "merge failed");
  668.  
  669.     else {
  670.         int err;
  671.         ENTER_TCL
  672.         err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
  673.         ENTER_OVERLAP
  674.         if (err == TCL_ERROR)
  675.             res = Tkinter_Error(self);
  676.         else
  677.             res = PyString_FromString(Tkapp_Result(self));
  678.         LEAVE_OVERLAP_TCL
  679.     }
  680.  
  681.     if (cmd)
  682.         ckfree(cmd);
  683.  
  684.     return res;
  685. }
  686.  
  687. static PyObject *
  688. Tkapp_Eval(self, args)
  689.     PyObject *self;
  690.     PyObject *args;
  691. {
  692.     char *script;
  693.     PyObject *res = NULL;
  694.     int err;
  695.   
  696.     if (!PyArg_ParseTuple(args, "s", &script))
  697.         return NULL;
  698.  
  699.     ENTER_TCL
  700.     err = Tcl_Eval(Tkapp_Interp(self), script);
  701.     ENTER_OVERLAP
  702.     if (err == TCL_ERROR)
  703.         res = Tkinter_Error(self);
  704.     else
  705.         res = PyString_FromString(Tkapp_Result(self));
  706.     LEAVE_OVERLAP_TCL
  707.     return res;
  708. }
  709.  
  710. static PyObject *
  711. Tkapp_GlobalEval(self, args)
  712.     PyObject *self;
  713.     PyObject *args;
  714. {
  715.     char *script;
  716.     PyObject *res = NULL;
  717.     int err;
  718.  
  719.     if (!PyArg_ParseTuple(args, "s", &script))
  720.         return NULL;
  721.  
  722.     ENTER_TCL
  723.     err = Tcl_GlobalEval(Tkapp_Interp(self), script);
  724.     ENTER_OVERLAP
  725.     if (err == TCL_ERROR)
  726.         res = Tkinter_Error(self);
  727.     else
  728.         res = PyString_FromString(Tkapp_Result(self));
  729.     LEAVE_OVERLAP_TCL
  730.     return res;
  731. }
  732.  
  733. static PyObject *
  734. Tkapp_EvalFile(self, args)
  735.     PyObject *self;
  736.     PyObject *args;
  737. {
  738.     char *fileName;
  739.     PyObject *res = NULL;
  740.     int err;
  741.  
  742.     if (!PyArg_ParseTuple(args, "s", &fileName))
  743.         return NULL;
  744.  
  745.     ENTER_TCL
  746.     err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
  747.     ENTER_OVERLAP
  748.     if (err == TCL_ERROR)
  749.         res = Tkinter_Error(self);
  750.  
  751.     else
  752.         res = PyString_FromString(Tkapp_Result(self));
  753.     LEAVE_OVERLAP_TCL
  754.     return res;
  755. }
  756.  
  757. static PyObject *
  758. Tkapp_Record(self, args)
  759.     PyObject *self;
  760.     PyObject *args;
  761. {
  762.     char *script;
  763.     PyObject *res = NULL;
  764.     int err;
  765.  
  766.     if (!PyArg_ParseTuple(args, "s", &script))
  767.         return NULL;
  768.  
  769.     ENTER_TCL
  770.     err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
  771.     ENTER_OVERLAP
  772.     if (err == TCL_ERROR)
  773.         res = Tkinter_Error(self);
  774.     else
  775.         res = PyString_FromString(Tkapp_Result(self));
  776.     LEAVE_OVERLAP_TCL
  777.     return res;
  778. }
  779.  
  780. static PyObject *
  781. Tkapp_AddErrorInfo(self, args)
  782.     PyObject *self;
  783.     PyObject *args;
  784. {
  785.     char *msg;
  786.  
  787.     if (!PyArg_ParseTuple(args, "s", &msg))
  788.         return NULL;
  789.     ENTER_TCL
  790.     Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
  791.     LEAVE_TCL
  792.  
  793.     Py_INCREF(Py_None);
  794.     return Py_None;
  795. }
  796.  
  797.  
  798.  
  799. /** Tcl Variable **/
  800.  
  801. static PyObject *
  802. SetVar(self, args, flags)
  803.     PyObject *self;
  804.     PyObject *args;
  805.     int flags;
  806. {
  807.     char *name1, *name2, *ok, *s;
  808.     PyObject *newValue;
  809.     PyObject *tmp;
  810.  
  811.     tmp = PyList_New(0);
  812.     if (!tmp)
  813.         return NULL;
  814.  
  815.     if (PyArg_ParseTuple(args, "sO", &name1, &newValue)) {
  816.         /* XXX Merge? */
  817.         s = AsString(newValue, tmp);
  818.         ENTER_TCL
  819.         ok = Tcl_SetVar(Tkapp_Interp(self), name1, s, flags);
  820.         LEAVE_TCL
  821.     }
  822.     else {
  823.         PyErr_Clear();
  824.         if (PyArg_ParseTuple(args, "ssO", &name1, &name2, &newValue)) {
  825.             s = AsString (newValue, tmp);
  826.             ENTER_TCL
  827.             ok = Tcl_SetVar2(Tkapp_Interp(self), name1, name2, 
  828.                      s, flags);
  829.             LEAVE_TCL
  830.         }
  831.         else {
  832.             Py_DECREF(tmp);
  833.             return NULL;
  834.         }
  835.     }
  836.     Py_DECREF(tmp);
  837.  
  838.     if (!ok)
  839.         return Tkinter_Error(self);
  840.  
  841.     Py_INCREF(Py_None);
  842.     return Py_None;
  843. }
  844.  
  845. static PyObject *
  846. Tkapp_SetVar(self, args)
  847.     PyObject *self;
  848.     PyObject *args;
  849. {
  850.     return SetVar(self, args, TCL_LEAVE_ERR_MSG);
  851. }
  852.  
  853. static PyObject *
  854. Tkapp_GlobalSetVar(self, args)
  855.     PyObject *self;
  856.     PyObject *args;
  857. {
  858.     return SetVar(self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  859. }
  860.  
  861.  
  862.  
  863. static PyObject *
  864. GetVar(self, args, flags)
  865.     PyObject *self;
  866.     PyObject *args;
  867.     int flags;
  868. {
  869.     char *name1, *name2=NULL, *s;
  870.     PyObject *res = NULL;
  871.  
  872.     if (!PyArg_ParseTuple(args, "s|s", &name1, &name2))
  873.         return NULL;
  874.     ENTER_TCL
  875.     if (name2 == NULL)
  876.         s = Tcl_GetVar(Tkapp_Interp(self), name1, flags);
  877.  
  878.     else
  879.         s = Tcl_GetVar2(Tkapp_Interp(self), name1, name2, flags);
  880.     ENTER_OVERLAP
  881.  
  882.     if (s == NULL)
  883.         res = Tkinter_Error(self);
  884.     else
  885.         res = PyString_FromString(s);
  886.     LEAVE_OVERLAP_TCL
  887.     return res;
  888. }
  889.  
  890. static PyObject *
  891. Tkapp_GetVar(self, args)
  892.     PyObject *self;
  893.     PyObject *args;
  894. {
  895.     return GetVar(self, args, TCL_LEAVE_ERR_MSG);
  896. }
  897.  
  898. static PyObject *
  899. Tkapp_GlobalGetVar(self, args)
  900.     PyObject *self;
  901.     PyObject *args;
  902. {
  903.     return GetVar(self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  904. }
  905.  
  906.  
  907.  
  908. static PyObject *
  909. UnsetVar(self, args, flags)
  910.     PyObject *self;
  911.     PyObject *args;
  912.     int flags;
  913. {
  914.     char *name1, *name2=NULL;
  915.     PyObject *res = NULL;
  916.     int code;
  917.  
  918.     if (!PyArg_ParseTuple(args, "s|s", &name1, &name2))
  919.         return NULL;
  920.     ENTER_TCL
  921.     if (name2 == NULL)
  922.         code = Tcl_UnsetVar(Tkapp_Interp(self), name1, flags);
  923.  
  924.     else
  925.         code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
  926.     ENTER_OVERLAP
  927.  
  928.     if (code == TCL_ERROR)
  929.         res = Tkinter_Error(self);
  930.     else {
  931.         Py_INCREF(Py_None);
  932.         res = Py_None;
  933.     }
  934.     LEAVE_OVERLAP_TCL
  935.     return res;
  936. }
  937.  
  938. static PyObject *
  939. Tkapp_UnsetVar(self, args)
  940.     PyObject *self;
  941.     PyObject *args;
  942. {
  943.     return UnsetVar(self, args, TCL_LEAVE_ERR_MSG);
  944. }
  945.  
  946. static PyObject *
  947. Tkapp_GlobalUnsetVar(self, args)
  948.     PyObject *self;
  949.     PyObject *args;
  950. {
  951.     return UnsetVar(self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  952. }
  953.  
  954.  
  955.  
  956. /** Tcl to Python **/
  957.  
  958. static PyObject *
  959. Tkapp_GetInt(self, args)
  960.     PyObject *self;
  961.     PyObject *args;
  962. {
  963.     char *s;
  964.     int v;
  965.  
  966.     if (!PyArg_ParseTuple(args, "s", &s))
  967.         return NULL;
  968.     if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  969.         return Tkinter_Error(self);
  970.     return Py_BuildValue("i", v);
  971. }
  972.  
  973. static PyObject *
  974. Tkapp_GetDouble(self, args)
  975.     PyObject *self;
  976.     PyObject *args;
  977. {
  978.     char *s;
  979.     double v;
  980.  
  981.     if (!PyArg_ParseTuple(args, "s", &s))
  982.         return NULL;
  983.     if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  984.         return Tkinter_Error(self);
  985.     return Py_BuildValue("d", v);
  986. }
  987.  
  988. static PyObject *
  989. Tkapp_GetBoolean(self, args)
  990.     PyObject *self;
  991.     PyObject *args;
  992. {
  993.     char *s;
  994.     int v;
  995.  
  996.     if (!PyArg_ParseTuple(args, "s", &s))
  997.         return NULL;
  998.     if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  999.         return Tkinter_Error(self);
  1000.     return Py_BuildValue("i", v);
  1001. }
  1002.  
  1003. static PyObject *
  1004. Tkapp_ExprString(self, args)
  1005.     PyObject *self;
  1006.     PyObject *args;
  1007. {
  1008.     char *s;
  1009.     PyObject *res = NULL;
  1010.     int retval;
  1011.  
  1012.     if (!PyArg_ParseTuple(args, "s", &s))
  1013.         return NULL;
  1014.     ENTER_TCL
  1015.     retval = Tcl_ExprString(Tkapp_Interp(self), s);
  1016.     ENTER_OVERLAP
  1017.     if (retval == TCL_ERROR)
  1018.         res = Tkinter_Error(self);
  1019.     else
  1020.         res = Py_BuildValue("s", Tkapp_Result(self));
  1021.     LEAVE_OVERLAP_TCL
  1022.     return res;
  1023. }
  1024.  
  1025. static PyObject *
  1026. Tkapp_ExprLong(self, args)
  1027.     PyObject *self;
  1028.     PyObject *args;
  1029. {
  1030.     char *s;
  1031.     PyObject *res = NULL;
  1032.     int retval;
  1033.     long v;
  1034.  
  1035.     if (!PyArg_ParseTuple(args, "s", &s))
  1036.         return NULL;
  1037.     ENTER_TCL
  1038.     retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
  1039.     ENTER_OVERLAP
  1040.     if (retval == TCL_ERROR)
  1041.         res = Tkinter_Error(self);
  1042.     else
  1043.         res = Py_BuildValue("l", v);
  1044.     LEAVE_OVERLAP_TCL
  1045.     return res;
  1046. }
  1047.  
  1048. static PyObject *
  1049. Tkapp_ExprDouble(self, args)
  1050.     PyObject *self;
  1051.     PyObject *args;
  1052. {
  1053.     char *s;
  1054.     PyObject *res = NULL;
  1055.     double v;
  1056.     int retval;
  1057.  
  1058.     if (!PyArg_ParseTuple(args, "s", &s))
  1059.         return NULL;
  1060.     PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
  1061.     ENTER_TCL
  1062.     retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
  1063.     ENTER_OVERLAP
  1064.     PyFPE_END_PROTECT(retval)
  1065.     if (retval == TCL_ERROR)
  1066.         res = Tkinter_Error(self);
  1067.     else
  1068.         res = Py_BuildValue("d", v);
  1069.     LEAVE_OVERLAP_TCL
  1070.     return res;
  1071. }
  1072.  
  1073. static PyObject *
  1074. Tkapp_ExprBoolean(self, args)
  1075.     PyObject *self;
  1076.     PyObject *args;
  1077. {
  1078.     char *s;
  1079.     PyObject *res = NULL;
  1080.     int retval;
  1081.     int v;
  1082.  
  1083.     if (!PyArg_ParseTuple(args, "s", &s))
  1084.         return NULL;
  1085.     ENTER_TCL
  1086.     retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
  1087.     ENTER_OVERLAP
  1088.     if (retval == TCL_ERROR)
  1089.         res = Tkinter_Error(self);
  1090.     else
  1091.         res = Py_BuildValue("i", v);
  1092.     LEAVE_OVERLAP_TCL
  1093.     return res;
  1094. }
  1095.  
  1096.  
  1097.  
  1098. static PyObject *
  1099. Tkapp_SplitList(self, args)
  1100.     PyObject *self;
  1101.     PyObject *args;
  1102. {
  1103.     char *list;
  1104.     int argc;
  1105.     char **argv;
  1106.     PyObject *v;
  1107.     int i;
  1108.  
  1109.     if (!PyArg_ParseTuple(args, "s", &list))
  1110.         return NULL;
  1111.  
  1112.     if (Tcl_SplitList(Tkapp_Interp(self), list, &argc, &argv) == TCL_ERROR)
  1113.         return Tkinter_Error(self);
  1114.  
  1115.     if (!(v = PyTuple_New(argc)))
  1116.         return NULL;
  1117.     
  1118.     for (i = 0; i < argc; i++) {
  1119.         PyObject *s = PyString_FromString(argv[i]);
  1120.         if (!s || PyTuple_SetItem(v, i, s)) {
  1121.             Py_DECREF(v);
  1122.             v = NULL;
  1123.             goto finally;
  1124.         }
  1125.     }
  1126.  
  1127.   finally:
  1128.     ckfree(FREECAST argv);
  1129.     return v;
  1130. }
  1131.  
  1132. static PyObject *
  1133. Tkapp_Split(self, args)
  1134.     PyObject *self;
  1135.     PyObject *args;
  1136. {
  1137.     char *list;
  1138.  
  1139.     if (!PyArg_ParseTuple(args, "s", &list))
  1140.         return NULL;
  1141.     return Split(list);
  1142. }
  1143.  
  1144. static PyObject *
  1145. Tkapp_Merge(self, args)
  1146.     PyObject *self;
  1147.     PyObject *args;
  1148. {
  1149.     char *s = Merge(args);
  1150.     PyObject *res = NULL;
  1151.  
  1152.     if (s) {
  1153.         res = PyString_FromString(s);
  1154.         ckfree(s);
  1155.     }
  1156.     else
  1157.         PyErr_SetString(Tkinter_TclError, "merge failed");
  1158.  
  1159.     return res;
  1160. }
  1161.  
  1162.  
  1163.  
  1164. /** Tcl Command **/
  1165.  
  1166. /* Client data struct */
  1167. typedef struct {
  1168.     PyObject *self;
  1169.     PyObject *func;
  1170. } PythonCmd_ClientData;
  1171.  
  1172. static int
  1173. PythonCmd_Error(interp)
  1174.     Tcl_Interp *interp;
  1175. {
  1176.     errorInCmd = 1;
  1177.     PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1178.     LEAVE_PYTHON
  1179.     return TCL_ERROR;
  1180. }
  1181.  
  1182. /* This is the Tcl command that acts as a wrapper for Python
  1183.  * function or method.
  1184.  */
  1185. static int
  1186. PythonCmd(clientData, interp, argc, argv)
  1187.     ClientData clientData;
  1188.     Tcl_Interp *interp;
  1189.     int argc;
  1190.     char *argv[];
  1191. {
  1192.     PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
  1193.     PyObject *self, *func, *arg, *res, *tmp;
  1194.     int i;
  1195.  
  1196.     ENTER_PYTHON
  1197.  
  1198.     /* TBD: no error checking here since we know, via the
  1199.      * Tkapp_CreateCommand() that the client data is a two-tuple
  1200.      */
  1201.     self = data->self;
  1202.     func = data->func;
  1203.  
  1204.     /* Create argument list (argv1, ..., argvN) */
  1205.     if (!(arg = PyTuple_New(argc - 1)))
  1206.         return PythonCmd_Error(interp);
  1207.  
  1208.     for (i = 0; i < (argc - 1); i++) {
  1209.         PyObject *s = PyString_FromString(argv[i + 1]);
  1210.         if (!s || PyTuple_SetItem(arg, i, s)) {
  1211.             Py_DECREF(arg);
  1212.             return PythonCmd_Error(interp);
  1213.         }
  1214.     }
  1215.     res = PyEval_CallObject(func, arg);
  1216.     Py_DECREF(arg);
  1217.  
  1218.     if (res == NULL)
  1219.         return PythonCmd_Error(interp);
  1220.  
  1221.     if (!(tmp = PyList_New(0))) {
  1222.         Py_DECREF(res);
  1223.         return PythonCmd_Error(interp);
  1224.     }
  1225.  
  1226.     Tcl_SetResult(Tkapp_Interp(self), AsString(res, tmp), TCL_VOLATILE);
  1227.     Py_DECREF(res);
  1228.     Py_DECREF(tmp);
  1229.  
  1230.     LEAVE_PYTHON
  1231.  
  1232.     return TCL_OK;
  1233. }
  1234.  
  1235. static void
  1236. PythonCmdDelete(clientData)
  1237.     ClientData clientData;
  1238. {
  1239.     PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
  1240.  
  1241.     ENTER_PYTHON
  1242.     Py_XDECREF(data->self);
  1243.     Py_XDECREF(data->func);
  1244.     PyMem_DEL(data);
  1245.     LEAVE_PYTHON
  1246. }
  1247.  
  1248.  
  1249.  
  1250. static PyObject *
  1251. Tkapp_CreateCommand(self, args)
  1252.     PyObject *self;
  1253.     PyObject *args;
  1254. {
  1255.     PythonCmd_ClientData *data;
  1256.     char *cmdName;
  1257.     PyObject *func;
  1258.     Tcl_Command err;
  1259.  
  1260.     if (!PyArg_ParseTuple(args, "sO", &cmdName, &func))
  1261.         return NULL;
  1262.     if (!PyCallable_Check(func)) {
  1263.         PyErr_SetString(PyExc_TypeError, "command not callable");
  1264.         return NULL;
  1265.     }
  1266.  
  1267.     data = PyMem_NEW(PythonCmd_ClientData, 1);
  1268.     if (!data)
  1269.         return NULL;
  1270.     Py_XINCREF(self);
  1271.     Py_XINCREF(func);
  1272.     data->self = self;
  1273.     data->func = func;
  1274.  
  1275.     ENTER_TCL
  1276.     err = Tcl_CreateCommand(Tkapp_Interp(self), cmdName, PythonCmd,
  1277.                 (ClientData)data, PythonCmdDelete);
  1278.     LEAVE_TCL
  1279.     if (err == NULL) {
  1280.         PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
  1281.         PyMem_DEL(data);
  1282.         return NULL;
  1283.     }
  1284.  
  1285.     Py_INCREF(Py_None);
  1286.     return Py_None;
  1287. }
  1288.  
  1289.  
  1290.  
  1291. static PyObject *
  1292. Tkapp_DeleteCommand(self, args)
  1293.     PyObject *self;
  1294.     PyObject *args;
  1295. {
  1296.     char *cmdName;
  1297.     int err;
  1298.  
  1299.     if (!PyArg_ParseTuple(args, "s", &cmdName))
  1300.         return NULL;
  1301.     ENTER_TCL
  1302.     err = Tcl_DeleteCommand(Tkapp_Interp(self), cmdName);
  1303.     LEAVE_TCL
  1304.     if (err == -1) {
  1305.         PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
  1306.         return NULL;
  1307.     }
  1308.     Py_INCREF(Py_None);
  1309.     return Py_None;
  1310. }
  1311.  
  1312.  
  1313.  
  1314. #ifdef HAVE_CREATEFILEHANDLER
  1315. /** File Handler **/
  1316.  
  1317. typedef struct _fhcdata {
  1318.     PyObject *func;
  1319.     PyObject *file;
  1320.     int id;
  1321.     struct _fhcdata *next;
  1322. } FileHandler_ClientData;
  1323.  
  1324. static FileHandler_ClientData *HeadFHCD;
  1325.  
  1326. static FileHandler_ClientData *
  1327. NewFHCD(func, file, id)
  1328.     PyObject *func;
  1329.     PyObject *file;
  1330.     int id;
  1331. {
  1332.     FileHandler_ClientData *p;
  1333.     p = PyMem_NEW(FileHandler_ClientData, 1);
  1334.     if (p != NULL) {
  1335.         Py_XINCREF(func);
  1336.         Py_XINCREF(file);
  1337.         p->func = func;
  1338.         p->file = file;
  1339.         p->id = id;
  1340.         p->next = HeadFHCD;
  1341.         HeadFHCD = p;
  1342.     }
  1343.     return p;
  1344. }
  1345.  
  1346. static void
  1347. DeleteFHCD(id)
  1348.     int id;
  1349. {
  1350.     FileHandler_ClientData *p, **pp;
  1351.     
  1352.     pp = &HeadFHCD; 
  1353.     while ((p = *pp) != NULL) {
  1354.         if (p->id == id) {
  1355.             *pp = p->next;
  1356.             Py_XDECREF(p->func);
  1357.             Py_XDECREF(p->file);
  1358.             PyMem_DEL(p);
  1359.         }
  1360.         else
  1361.             pp = &p->next;
  1362.     }
  1363. }
  1364.  
  1365. static void
  1366. FileHandler(clientData, mask)
  1367.     ClientData clientData;
  1368.     int mask;
  1369. {
  1370.     FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
  1371.     PyObject *func, *file, *arg, *res;
  1372.  
  1373.     ENTER_PYTHON
  1374.     func = data->func;
  1375.     file = data->file;
  1376.  
  1377.     arg = Py_BuildValue("(Oi)", file, (long) mask);
  1378.     res = PyEval_CallObject(func, arg);
  1379.     Py_DECREF(arg);
  1380.  
  1381.     if (res == NULL) {
  1382.         errorInCmd = 1;
  1383.         PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1384.     }
  1385.     Py_XDECREF(res);
  1386.     LEAVE_PYTHON
  1387. }
  1388.  
  1389. static int
  1390. GetFileNo(file)
  1391.     /* Either an int >= 0 or an object with a
  1392.      *.fileno() method that returns an int >= 0
  1393.      */
  1394.     PyObject *file;
  1395. {
  1396.     PyObject *meth, *args, *res;
  1397.     int id;
  1398.     if (PyInt_Check(file)) {
  1399.         id = PyInt_AsLong(file);
  1400.         if (id < 0)
  1401.             PyErr_SetString(PyExc_ValueError, "invalid file id");
  1402.         return id;
  1403.     }
  1404.     args = PyTuple_New(0);
  1405.     if (args == NULL)
  1406.         return -1;
  1407.  
  1408.     meth = PyObject_GetAttrString(file, "fileno");
  1409.     if (meth == NULL) {
  1410.         Py_DECREF(args);
  1411.         return -1;
  1412.     }
  1413.  
  1414.     res = PyEval_CallObject(meth, args);
  1415.     Py_DECREF(args);
  1416.     Py_DECREF(meth);
  1417.     if (res == NULL)
  1418.         return -1;
  1419.  
  1420.     if (PyInt_Check(res))
  1421.         id = PyInt_AsLong(res);
  1422.     else
  1423.         id = -1;
  1424.  
  1425.     if (id < 0)
  1426.         PyErr_SetString(PyExc_ValueError,
  1427.                 "invalid fileno() return value");
  1428.     Py_DECREF(res);
  1429.     return id;
  1430. }
  1431.  
  1432. static PyObject *
  1433. Tkapp_CreateFileHandler(self, args)
  1434.     PyObject *self;
  1435.     PyObject *args;                 /* Is (file, mask, func) */
  1436. {
  1437.     FileHandler_ClientData *data;
  1438.     PyObject *file, *func;
  1439.     int mask, id;
  1440.     FHANDLE tfile;
  1441.  
  1442.     if (!PyArg_ParseTuple(args, "OiO", &file, &mask, &func))
  1443.         return NULL;
  1444.     id = GetFileNo(file);
  1445.     if (id < 0)
  1446.         return NULL;
  1447.     if (!PyCallable_Check(func)) {
  1448.         PyErr_SetString(PyExc_TypeError, "bad argument list");
  1449.         return NULL;
  1450.     }
  1451.  
  1452.     data = NewFHCD(func, file, id);
  1453.     if (data == NULL)
  1454.         return NULL;
  1455.  
  1456.     tfile = MAKEFHANDLE(id);
  1457.     /* Ought to check for null Tcl_File object... */
  1458.     ENTER_TCL
  1459.     Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
  1460.     LEAVE_TCL
  1461.     Py_INCREF(Py_None);
  1462.     return Py_None;
  1463. }
  1464.  
  1465. static PyObject *
  1466. Tkapp_DeleteFileHandler(self, args)
  1467.     PyObject *self;
  1468.     PyObject *args;                 /* Args: file */
  1469. {
  1470.     PyObject *file;
  1471.     FileHandler_ClientData *data;
  1472.     int id;
  1473.     FHANDLE tfile;
  1474.   
  1475.     if (!PyArg_ParseTuple(args, "O", &file))
  1476.         return NULL;
  1477.     id = GetFileNo(file);
  1478.     if (id < 0)
  1479.         return NULL;
  1480.  
  1481.     DeleteFHCD(id);
  1482.  
  1483.     tfile = MAKEFHANDLE(id);
  1484.     /* Ought to check for null Tcl_File object... */
  1485.     ENTER_TCL
  1486.     Tcl_DeleteFileHandler(tfile);
  1487.     LEAVE_TCL
  1488.     Py_INCREF(Py_None);
  1489.     return Py_None;
  1490. }
  1491. #endif /* HAVE_CREATEFILEHANDLER */
  1492.  
  1493.  
  1494. /**** Tktt Object (timer token) ****/
  1495.  
  1496. staticforward PyTypeObject Tktt_Type;
  1497.  
  1498. typedef struct {
  1499.     PyObject_HEAD
  1500.     Tcl_TimerToken token;
  1501.     PyObject *func;
  1502. } TkttObject;
  1503.  
  1504. static PyObject *
  1505. Tktt_DeleteTimerHandler(self, args)
  1506.     PyObject *self;
  1507.     PyObject *args;
  1508. {
  1509.     TkttObject *v = (TkttObject *)self;
  1510.     PyObject *func = v->func;
  1511.  
  1512.     if (!PyArg_ParseTuple(args, ""))
  1513.         return NULL;
  1514.     if (v->token != NULL) {
  1515.         Tcl_DeleteTimerHandler(v->token);
  1516.         v->token = NULL;
  1517.     }
  1518.     if (func != NULL) {
  1519.         v->func = NULL;
  1520.         Py_DECREF(func);
  1521.         Py_DECREF(v); /* See Tktt_New() */
  1522.     }
  1523.     Py_INCREF(Py_None);
  1524.     return Py_None;
  1525. }
  1526.  
  1527. static PyMethodDef Tktt_methods[] =
  1528. {
  1529.     {"deletetimerhandler", Tktt_DeleteTimerHandler, 1},
  1530.     {NULL, NULL}
  1531. };
  1532.  
  1533. static TkttObject *
  1534. Tktt_New(func)
  1535.     PyObject *func;
  1536. {
  1537.     TkttObject *v;
  1538.   
  1539.     v = PyObject_NEW(TkttObject, &Tktt_Type);
  1540.     if (v == NULL)
  1541.         return NULL;
  1542.  
  1543.     Py_INCREF(func);
  1544.     v->token = NULL;
  1545.     v->func = func;
  1546.  
  1547.     /* Extra reference, deleted when called or when handler is deleted */
  1548.     Py_INCREF(v);
  1549.     return v;
  1550. }
  1551.  
  1552. static void
  1553. Tktt_Dealloc(self)
  1554.     PyObject *self;
  1555. {
  1556.     TkttObject *v = (TkttObject *)self;
  1557.     PyObject *func = v->func;
  1558.  
  1559.     Py_XDECREF(func);
  1560.  
  1561.     PyMem_DEL(self);
  1562. }
  1563.  
  1564. static PyObject *
  1565. Tktt_Repr(self)
  1566.     PyObject *self;
  1567. {
  1568.     TkttObject *v = (TkttObject *)self;
  1569.     char buf[100];
  1570.  
  1571.     sprintf(buf, "<tktimertoken at 0x%lx%s>", (long)v,
  1572.         v->func == NULL ? ", handler deleted" : "");
  1573.     return PyString_FromString(buf);
  1574. }
  1575.  
  1576. static PyObject *
  1577. Tktt_GetAttr(self, name)
  1578.     PyObject *self;
  1579.     char *name;
  1580. {
  1581.     return Py_FindMethod(Tktt_methods, self, name);
  1582. }
  1583.  
  1584. static PyTypeObject Tktt_Type =
  1585. {
  1586.     PyObject_HEAD_INIT(NULL)
  1587.     0,                     /*ob_size */
  1588.     "tktimertoken",                 /*tp_name */
  1589.     sizeof(TkttObject),             /*tp_basicsize */
  1590.     0,                     /*tp_itemsize */
  1591.     Tktt_Dealloc,                 /*tp_dealloc */
  1592.     0,                     /*tp_print */
  1593.     Tktt_GetAttr,                 /*tp_getattr */
  1594.     0,                     /*tp_setattr */
  1595.     0,                     /*tp_compare */
  1596.     Tktt_Repr,                 /*tp_repr */
  1597.     0,                     /*tp_as_number */
  1598.     0,                     /*tp_as_sequence */
  1599.     0,                     /*tp_as_mapping */
  1600.     0,                     /*tp_hash */
  1601. };
  1602.  
  1603.  
  1604.  
  1605. /** Timer Handler **/
  1606.  
  1607. static void
  1608. TimerHandler(clientData)
  1609.     ClientData clientData;
  1610. {
  1611.     TkttObject *v = (TkttObject *)clientData;
  1612.     PyObject *func = v->func;
  1613.     PyObject *res;
  1614.  
  1615.     if (func == NULL)
  1616.         return;
  1617.  
  1618.     v->func = NULL;
  1619.  
  1620.     ENTER_PYTHON
  1621.  
  1622.     res  = PyEval_CallObject(func, NULL);
  1623.     Py_DECREF(func);
  1624.     Py_DECREF(v); /* See Tktt_New() */
  1625.  
  1626.     if (res == NULL) {
  1627.         errorInCmd = 1;
  1628.         PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1629.     }
  1630.     else
  1631.         Py_DECREF(res);
  1632.  
  1633.     LEAVE_PYTHON
  1634. }
  1635.  
  1636. static PyObject *
  1637. Tkapp_CreateTimerHandler(self, args)
  1638.     PyObject *self;
  1639.     PyObject *args;                 /* Is (milliseconds, func) */
  1640. {
  1641.     int milliseconds;
  1642.     PyObject *func;
  1643.     TkttObject *v;
  1644.  
  1645.     if (!PyArg_ParseTuple(args, "iO", &milliseconds, &func))
  1646.         return NULL;
  1647.     if (!PyCallable_Check(func)) {
  1648.         PyErr_SetString(PyExc_TypeError, "bad argument list");
  1649.         return NULL;
  1650.     }
  1651.     v = Tktt_New(func);
  1652.     v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
  1653.                       (ClientData)v);
  1654.  
  1655.     return (PyObject *) v;
  1656. }
  1657.  
  1658.  
  1659. /** Event Loop **/
  1660.  
  1661. static PyObject *
  1662. Tkapp_MainLoop(self, args)
  1663.     PyObject *self;
  1664.     PyObject *args;
  1665. {
  1666.     int threshold = 0;
  1667. #ifdef WITH_THREAD
  1668.     PyThreadState *tstate = PyThreadState_Get();
  1669. #endif
  1670.  
  1671.     if (!PyArg_ParseTuple(args, "|i", &threshold))
  1672.         return NULL;
  1673.  
  1674.     quitMainLoop = 0;
  1675.     while (Tk_GetNumMainWindows() > threshold &&
  1676.            !quitMainLoop &&
  1677.            !errorInCmd)
  1678.     {
  1679.         int result;
  1680.  
  1681. #ifdef WITH_THREAD
  1682.         Py_BEGIN_ALLOW_THREADS
  1683.         PyThread_acquire_lock(tcl_lock, 1);
  1684.         tcl_tstate = tstate;
  1685.         result = Tcl_DoOneEvent(TCL_DONT_WAIT);
  1686.         tcl_tstate = NULL;
  1687.         PyThread_release_lock(tcl_lock);
  1688.         if (result == 0)
  1689.             Sleep(20);
  1690.         Py_END_ALLOW_THREADS
  1691. #else
  1692.         result = Tcl_DoOneEvent(0);
  1693. #endif
  1694.  
  1695.         if (PyErr_CheckSignals() != 0)
  1696.             return NULL;
  1697.         if (result < 0)
  1698.             break;
  1699.     }
  1700.     quitMainLoop = 0;
  1701.  
  1702.     if (errorInCmd) {
  1703.         errorInCmd = 0;
  1704.         PyErr_Restore(excInCmd, valInCmd, trbInCmd);
  1705.         excInCmd = valInCmd = trbInCmd = NULL;
  1706.         return NULL;
  1707.     }
  1708.     Py_INCREF(Py_None);
  1709.     return Py_None;
  1710. }
  1711.  
  1712. static PyObject *
  1713. Tkapp_DoOneEvent(self, args)
  1714.     PyObject *self;
  1715.     PyObject *args;
  1716. {
  1717.     int flags = 0;
  1718.     int rv;
  1719.  
  1720.     if (!PyArg_ParseTuple(args, "|i", &flags))
  1721.         return NULL;
  1722.  
  1723.     ENTER_TCL
  1724.     rv = Tcl_DoOneEvent(flags);
  1725.     LEAVE_TCL
  1726.     return Py_BuildValue("i", rv);
  1727. }
  1728.  
  1729. static PyObject *
  1730. Tkapp_Quit(self, args)
  1731.     PyObject *self;
  1732.     PyObject *args;
  1733. {
  1734.  
  1735.     if (!PyArg_ParseTuple(args, ""))
  1736.         return NULL;
  1737.  
  1738.     quitMainLoop = 1;
  1739.     Py_INCREF(Py_None);
  1740.     return Py_None;
  1741. }
  1742.  
  1743. static PyObject *
  1744. Tkapp_InterpAddr(self, args)
  1745.     PyObject *self;
  1746.     PyObject *args;
  1747. {
  1748.  
  1749.     if (!PyArg_ParseTuple(args, ""))
  1750.         return NULL;
  1751.  
  1752.     return PyInt_FromLong((long)Tkapp_Interp(self));
  1753. }
  1754.  
  1755.  
  1756.  
  1757. /**** Tkapp Method List ****/
  1758.  
  1759. static PyMethodDef Tkapp_methods[] =
  1760. {
  1761.     {"call",            Tkapp_Call, 0},
  1762.     {"globalcall",            Tkapp_GlobalCall, 0},
  1763.     {"eval",            Tkapp_Eval, 1},
  1764.     {"globaleval",            Tkapp_GlobalEval, 1},
  1765.     {"evalfile",            Tkapp_EvalFile, 1},
  1766.     {"record",            Tkapp_Record, 1},
  1767.     {"adderrorinfo",       Tkapp_AddErrorInfo, 1},
  1768.     {"setvar",            Tkapp_SetVar, 1},
  1769.     {"globalsetvar",       Tkapp_GlobalSetVar, 1},
  1770.     {"getvar",            Tkapp_GetVar, 1},
  1771.     {"globalgetvar",       Tkapp_GlobalGetVar, 1},
  1772.     {"unsetvar",            Tkapp_UnsetVar, 1},
  1773.     {"globalunsetvar",     Tkapp_GlobalUnsetVar, 1},
  1774.     {"getint",            Tkapp_GetInt, 1},
  1775.     {"getdouble",            Tkapp_GetDouble, 1},
  1776.     {"getboolean",            Tkapp_GetBoolean, 1},
  1777.     {"exprstring",            Tkapp_ExprString, 1},
  1778.     {"exprlong",            Tkapp_ExprLong, 1},
  1779.     {"exprdouble",            Tkapp_ExprDouble, 1},
  1780.     {"exprboolean",        Tkapp_ExprBoolean, 1},
  1781.     {"splitlist",            Tkapp_SplitList, 1},
  1782.     {"split",            Tkapp_Split, 1},
  1783.     {"merge",            Tkapp_Merge, 0},
  1784.     {"createcommand",      Tkapp_CreateCommand, 1},
  1785.     {"deletecommand",      Tkapp_DeleteCommand, 1},
  1786. #ifdef HAVE_CREATEFILEHANDLER
  1787.     {"createfilehandler",  Tkapp_CreateFileHandler, 1},
  1788.     {"deletefilehandler",  Tkapp_DeleteFileHandler, 1},
  1789. #endif
  1790.     {"createtimerhandler", Tkapp_CreateTimerHandler, 1},
  1791.     {"mainloop",            Tkapp_MainLoop, 1},
  1792.     {"dooneevent",            Tkapp_DoOneEvent, 1},
  1793.     {"quit",            Tkapp_Quit, 1},
  1794.     {"interpaddr",         Tkapp_InterpAddr, 1},
  1795.     {NULL,                NULL}
  1796. };
  1797.  
  1798.  
  1799.  
  1800. /**** Tkapp Type Methods ****/
  1801.  
  1802. static void
  1803. Tkapp_Dealloc(self)
  1804.     PyObject *self;
  1805. {
  1806.     ENTER_TCL
  1807.     Tcl_DeleteInterp(Tkapp_Interp(self));
  1808.     LEAVE_TCL
  1809.     PyMem_DEL(self);
  1810.     DisableEventHook();
  1811. }
  1812.  
  1813. static PyObject *
  1814. Tkapp_GetAttr(self, name)
  1815.     PyObject *self;
  1816.     char *name;
  1817. {
  1818.     return Py_FindMethod(Tkapp_methods, self, name);
  1819. }
  1820.  
  1821. static PyTypeObject Tkapp_Type =
  1822. {
  1823.     PyObject_HEAD_INIT(NULL)
  1824.     0,                     /*ob_size */
  1825.     "tkapp",                 /*tp_name */
  1826.     sizeof(TkappObject),             /*tp_basicsize */
  1827.     0,                     /*tp_itemsize */
  1828.     Tkapp_Dealloc,                 /*tp_dealloc */
  1829.     0,                     /*tp_print */
  1830.     Tkapp_GetAttr,                 /*tp_getattr */
  1831.     0,                     /*tp_setattr */
  1832.     0,                     /*tp_compare */
  1833.     0,                     /*tp_repr */
  1834.     0,                     /*tp_as_number */
  1835.     0,                     /*tp_as_sequence */
  1836.     0,                     /*tp_as_mapping */
  1837.     0,                     /*tp_hash */
  1838. };
  1839.  
  1840.  
  1841.  
  1842. /**** Tkinter Module ****/
  1843.  
  1844. static PyObject *
  1845. Tkinter_Create(self, args)
  1846.     PyObject *self;
  1847.     PyObject *args;
  1848. {
  1849.     char *screenName = NULL;
  1850.     char *baseName = NULL;
  1851.     char *className = NULL;
  1852.     int interactive = 0;
  1853.  
  1854.     baseName = strrchr(Py_GetProgramName(), '/');
  1855.     if (baseName != NULL)
  1856.         baseName++;
  1857.     else
  1858.         baseName = Py_GetProgramName();
  1859.     className = "Tk";
  1860.   
  1861.     if (!PyArg_ParseTuple(args, "|zssi",
  1862.                   &screenName, &baseName, &className,
  1863.                   &interactive))
  1864.         return NULL;
  1865.  
  1866.     return (PyObject *) Tkapp_New(screenName, baseName, className, 
  1867.                       interactive);
  1868. }
  1869.  
  1870. static PyMethodDef moduleMethods[] =
  1871. {
  1872.     {"create",             Tkinter_Create, 1},
  1873. #ifdef HAVE_CREATEFILEHANDLER
  1874.     {"createfilehandler",  Tkapp_CreateFileHandler, 1},
  1875.     {"deletefilehandler",  Tkapp_DeleteFileHandler, 1},
  1876. #endif
  1877.     {"createtimerhandler", Tkapp_CreateTimerHandler, 1},
  1878.     {"mainloop",           Tkapp_MainLoop, 1},
  1879.     {"dooneevent",         Tkapp_DoOneEvent, 1},
  1880.     {"quit",               Tkapp_Quit, 1},
  1881.     {NULL,                 NULL}
  1882. };
  1883.  
  1884. #ifdef WAIT_FOR_STDIN
  1885.  
  1886. static int stdin_ready = 0;
  1887.  
  1888. #ifndef MS_WINDOWS
  1889. static void
  1890. MyFileProc(clientData, mask)
  1891.     void *clientData;
  1892.     int mask;
  1893. {
  1894.     stdin_ready = 1;
  1895. }
  1896. #endif
  1897.  
  1898. static PyThreadState *event_tstate = NULL;
  1899.  
  1900. static int
  1901. EventHook()
  1902. {
  1903. #ifndef MS_WINDOWS
  1904.     FHANDLE tfile;
  1905. #endif
  1906. #ifdef WITH_THREAD
  1907.     PyEval_RestoreThread(event_tstate);
  1908. #endif
  1909.     stdin_ready = 0;
  1910.     errorInCmd = 0;
  1911. #ifndef MS_WINDOWS
  1912.     tfile = MAKEFHANDLE(fileno(stdin));
  1913.     Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
  1914. #endif
  1915.     while (!errorInCmd && !stdin_ready) {
  1916.         int result;
  1917. #ifdef MS_WINDOWS
  1918.         if (_kbhit()) {
  1919.             stdin_ready = 1;
  1920.             break;
  1921.         }
  1922. #endif
  1923. #if defined(WITH_THREAD) || defined(MS_WINDOWS)
  1924.         Py_BEGIN_ALLOW_THREADS
  1925.         PyThread_acquire_lock(tcl_lock, 1);
  1926.         tcl_tstate = event_tstate;
  1927.  
  1928.         result = Tcl_DoOneEvent(TCL_DONT_WAIT);
  1929.  
  1930.         tcl_tstate = NULL;
  1931.         PyThread_release_lock(tcl_lock);
  1932.         if (result == 0)
  1933.             Sleep(20);
  1934.         Py_END_ALLOW_THREADS
  1935. #else
  1936.         result = Tcl_DoOneEvent(0);
  1937. #endif
  1938.  
  1939.         if (result < 0)
  1940.             break;
  1941.     }
  1942. #ifndef MS_WINDOWS
  1943.     Tcl_DeleteFileHandler(tfile);
  1944. #endif
  1945.     if (errorInCmd) {
  1946.         errorInCmd = 0;
  1947.         PyErr_Restore(excInCmd, valInCmd, trbInCmd);
  1948.         excInCmd = valInCmd = trbInCmd = NULL;
  1949.         PyErr_Print();
  1950.     }
  1951. #ifdef WITH_THREAD
  1952.     PyEval_SaveThread();
  1953. #endif
  1954.     return 0;
  1955. }
  1956.  
  1957. #endif
  1958.  
  1959. static void
  1960. EnableEventHook()
  1961. {
  1962. #ifdef WAIT_FOR_STDIN
  1963.     if (PyOS_InputHook == NULL) {
  1964. #ifdef WITH_THREAD
  1965.         event_tstate = PyThreadState_Get();
  1966. #endif
  1967.         PyOS_InputHook = EventHook;
  1968.     }
  1969. #endif
  1970. }
  1971.  
  1972. static void
  1973. DisableEventHook()
  1974. {
  1975. #ifdef WAIT_FOR_STDIN
  1976.     if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
  1977.         PyOS_InputHook = NULL;
  1978.     }
  1979. #endif
  1980. }
  1981.  
  1982.  
  1983. /* all errors will be checked in one fell swoop in init_tkinter() */
  1984. static void
  1985. ins_long(d, name, val)
  1986.     PyObject *d;
  1987.     char *name;
  1988.     long val;
  1989. {
  1990.     PyObject *v = PyInt_FromLong(val);
  1991.     if (v) {
  1992.         PyDict_SetItemString(d, name, v);
  1993.         Py_DECREF(v);
  1994.     }
  1995. }
  1996. static void
  1997. ins_string(d, name, val)
  1998.     PyObject *d;
  1999.     char *name;
  2000.     char *val;
  2001. {
  2002.     PyObject *v = PyString_FromString(val);
  2003.     if (v) {
  2004.         PyDict_SetItemString(d, name, v);
  2005.         Py_DECREF(v);
  2006.     }
  2007. }
  2008.  
  2009.  
  2010. DL_EXPORT(void)
  2011. init_tkinter()
  2012. {
  2013.     PyObject *m, *d;
  2014.  
  2015.     Tkapp_Type.ob_type = &PyType_Type;
  2016.  
  2017. #ifdef WITH_THREAD
  2018.     tcl_lock = PyThread_allocate_lock();
  2019. #endif
  2020.  
  2021.     m = Py_InitModule("_tkinter", moduleMethods);
  2022.  
  2023.     d = PyModule_GetDict(m);
  2024.     Tkinter_TclError = Py_BuildValue("s", "TclError");
  2025.     PyDict_SetItemString(d, "TclError", Tkinter_TclError);
  2026.  
  2027.     ins_long(d, "READABLE", TCL_READABLE);
  2028.     ins_long(d, "WRITABLE", TCL_WRITABLE);
  2029.     ins_long(d, "EXCEPTION", TCL_EXCEPTION);
  2030.     ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
  2031.     ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
  2032.     ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
  2033.     ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
  2034.     ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
  2035.     ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
  2036.     ins_string(d, "TK_VERSION", TK_VERSION);
  2037.     ins_string(d, "TCL_VERSION", TCL_VERSION);
  2038.  
  2039.     PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
  2040.  
  2041.     Tktt_Type.ob_type = &PyType_Type;
  2042.     PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
  2043.  
  2044.     if (PyErr_Occurred())
  2045.         return;
  2046.  
  2047. #if 0
  2048.     /* This was not a good idea; through <Destroy> bindings,
  2049.        Tcl_Finalize() may invoke Python code but at that point the
  2050.        interpreter and thread state have already been destroyed! */
  2051. #if TKMAJORMINOR >= 8000
  2052.     Py_AtExit(Tcl_Finalize);
  2053. #endif
  2054. #endif
  2055.  
  2056. #ifdef macintosh
  2057.     /*
  2058.     ** Part of this code is stolen from MacintoshInit in tkMacAppInit.
  2059.     ** Most of the initializations in that routine (toolbox init calls and
  2060.     ** such) have already been done for us, so we only need these.
  2061.     */
  2062. #if TKMAJORMINOR >= 8000
  2063.     tcl_macQdPtr = &qd;
  2064. #endif
  2065.  
  2066.     Tcl_MacSetEventProc(PyMacConvertEvent);
  2067. #if GENERATINGCFM
  2068.     mac_addlibresources();
  2069. #endif /* GENERATINGCFM */
  2070. #endif /* macintosh */
  2071. }
  2072.  
  2073.  
  2074.  
  2075. #ifdef macintosh
  2076.  
  2077. /*
  2078. ** Anyone who embeds Tcl/Tk on the Mac must define panic().
  2079. */
  2080.  
  2081. void
  2082. panic(char * format, ...)
  2083. {
  2084.     va_list varg;
  2085.     
  2086.     va_start(varg, format);
  2087.     
  2088.     vfprintf(stderr, format, varg);
  2089.     (void) fflush(stderr);
  2090.     
  2091.     va_end(varg);
  2092.  
  2093.     Py_FatalError("Tcl/Tk panic");
  2094. }
  2095.  
  2096. /*
  2097. ** Pass events to SIOUX before passing them to Tk.
  2098. */
  2099.  
  2100. static int
  2101. PyMacConvertEvent(eventPtr)
  2102.     EventRecord *eventPtr;
  2103. {
  2104.     WindowPtr frontwin;
  2105.     /*
  2106.     ** Sioux eats too many events, so we don't pass it everything.  We
  2107.     ** always pass update events to Sioux, and we only pass other events if
  2108.     ** the Sioux window is frontmost. This means that Tk menus don't work
  2109.     ** in that case, but at least we can scroll the sioux window.
  2110.     ** Note that the SIOUXIsAppWindow() routine we use here is not really
  2111.     ** part of the external interface of Sioux...
  2112.     */
  2113.     frontwin = FrontWindow();
  2114.     if ( eventPtr->what == updateEvt || SIOUXIsAppWindow(frontwin) ) {
  2115.         if (SIOUXHandleOneEvent(eventPtr))
  2116.             return 0; /* Nothing happened to the Tcl event queue */
  2117.     }
  2118.     return TkMacConvertEvent(eventPtr);
  2119. }
  2120.  
  2121. #if defined(USE_GUSI) && TKMAJORMINOR < 8000
  2122. /*
  2123.  * For Python we have to override this routine (from TclMacNotify),
  2124.  * since we use GUSI for our sockets, not Tcl streams. Hence, we have
  2125.  * to use GUSI select to see whether our socket is ready. Note that
  2126.  * createfilehandler (above) sets the type to TCL_UNIX_FD for our
  2127.  * files and sockets.
  2128.  *
  2129.  * NOTE: this code was lifted from Tcl 7.6, it may need to be modified
  2130.  * for other versions.  */
  2131.  
  2132. int
  2133. Tcl_FileReady(file, mask)
  2134.     Tcl_File file;        /* File handle for a stream. */
  2135.     int mask;            /* OR'ed combination of TCL_READABLE,
  2136.                  * TCL_WRITABLE, and TCL_EXCEPTION:
  2137.                  * indicates conditions caller cares about. */
  2138. {
  2139.     int type;
  2140.     int fd;
  2141.  
  2142.     fd = (int) Tcl_GetFileInfo(file, &type);
  2143.  
  2144.     if (type == TCL_MAC_SOCKET) {
  2145.     return TclMacSocketReady(file, mask);
  2146.     } else if (type == TCL_MAC_FILE) {
  2147.     /*
  2148.      * Under the Macintosh, files are always ready, so we just 
  2149.      * return the mask that was passed in.
  2150.      */
  2151.  
  2152.     return mask;
  2153.     } else if (type == TCL_UNIX_FD) {
  2154.     fd_set readset, writeset, excset;
  2155.     struct timeval tv;
  2156.     
  2157.     FD_ZERO(&readset);
  2158.     FD_ZERO(&writeset);
  2159.     FD_ZERO(&excset);
  2160.     
  2161.     if ( mask & TCL_READABLE ) FD_SET(fd, &readset);
  2162.     if ( mask & TCL_WRITABLE ) FD_SET(fd, &writeset);
  2163.     if ( mask & TCL_EXCEPTION ) FD_SET(fd, &excset);
  2164.     
  2165.     tv.tv_sec = tv.tv_usec = 0;
  2166.     if ( select(fd+1, &readset, &writeset, &excset, &tv) <= 0 )
  2167.         return 0;
  2168.     
  2169.     mask = 0;
  2170.     if ( FD_ISSET(fd, &readset) ) mask |= TCL_READABLE;
  2171.     if ( FD_ISSET(fd, &writeset) ) mask |= TCL_WRITABLE;
  2172.     if ( FD_ISSET(fd, &excset) ) mask |= TCL_EXCEPTION;
  2173.  
  2174.     return mask;
  2175.     }
  2176.     
  2177.     return 0;
  2178. }
  2179. #endif /* USE_GUSI */
  2180.  
  2181. #if GENERATINGCFM
  2182.  
  2183. /*
  2184. ** Additional Mac specific code for dealing with shared libraries.
  2185. */
  2186.  
  2187. #include <Resources.h>
  2188. #include <CodeFragments.h>
  2189.  
  2190. static int loaded_from_shlib = 0;
  2191. static FSSpec library_fss;
  2192.  
  2193. /*
  2194. ** If this module is dynamically loaded the following routine should
  2195. ** be the init routine. It takes care of adding the shared library to
  2196. ** the resource-file chain, so that the tk routines can find their
  2197. ** resources.
  2198. */
  2199. OSErr pascal
  2200. init_tkinter_shlib(CFragInitBlockPtr data)
  2201. {
  2202.     __initialize();
  2203.     if ( data == nil ) return noErr;
  2204.     if ( data->fragLocator.where == kDataForkCFragLocator ) {
  2205.         library_fss = *data->fragLocator.u.onDisk.fileSpec;
  2206.         loaded_from_shlib = 1;
  2207.     } else if ( data->fragLocator.where == kResourceCFragLocator ) {
  2208.         library_fss = *data->fragLocator.u.inSegs.fileSpec;
  2209.         loaded_from_shlib = 1;
  2210.     }
  2211.     return noErr;
  2212. }
  2213.  
  2214. /*
  2215. ** Insert the library resources into the search path. Put them after
  2216. ** the resources from the application. Again, we ignore errors.
  2217. */
  2218. static
  2219. mac_addlibresources()
  2220. {
  2221.     if ( !loaded_from_shlib ) 
  2222.         return;
  2223.     (void)FSpOpenResFile(&library_fss, fsRdPerm);
  2224. }
  2225.  
  2226. #endif /* GENERATINGCFM */
  2227. #endif /* macintosh */
  2228.