You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3272 lines
84 KiB

32 years ago
31 years ago
31 years ago
24 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
21 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
21 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
32 years ago
  1. /***********************************************************
  2. Copyright (C) 1994 Steen Lumholt.
  3. All Rights Reserved
  4. ******************************************************************/
  5. /* _tkinter.c -- Interface to libtk.a and libtcl.a. */
  6. /* TCL/TK VERSION INFO:
  7. Only Tcl/Tk 8.3.1 and later are supported. Older versions are not
  8. supported. Use Python 2.6 or older if you cannot upgrade your
  9. Tcl/Tk libraries.
  10. */
  11. /* XXX Further speed-up ideas, involving Tcl 8.0 features:
  12. - Register a new Tcl type, "Python callable", which can be called more
  13. efficiently and passed to Tcl_EvalObj() directly (if this is possible).
  14. */
  15. #include "Python.h"
  16. #include <ctype.h>
  17. #ifdef WITH_THREAD
  18. #include "pythread.h"
  19. #endif
  20. #ifdef MS_WINDOWS
  21. #include <windows.h>
  22. #endif
  23. /* Allow using this code in Python 2.[12] */
  24. #ifndef PyDoc_STRVAR
  25. #define PyDoc_STRVAR(name,str) static char name[] = str
  26. #endif
  27. #ifndef PyMODINIT_FUNC
  28. #define PyMODINIT_FUNC void
  29. #endif
  30. #ifndef PyBool_Check
  31. #define PyBool_Check(o) 0
  32. #define PyBool_FromLong PyInt_FromLong
  33. #endif
  34. /* Starting with Tcl 8.4, many APIs offer const-correctness. Unfortunately,
  35. making _tkinter correct for this API means to break earlier
  36. versions. USE_COMPAT_CONST allows to make _tkinter work with both 8.4 and
  37. earlier versions. Once Tcl releases before 8.4 don't need to be supported
  38. anymore, this should go. */
  39. #define USE_COMPAT_CONST
  40. /* If Tcl is compiled for threads, we must also define TCL_THREAD. We define
  41. it always; if Tcl is not threaded, the thread functions in
  42. Tcl are empty. */
  43. #define TCL_THREADS
  44. #ifdef TK_FRAMEWORK
  45. #include <Tcl/tcl.h>
  46. #include <Tk/tk.h>
  47. #else
  48. #include <tcl.h>
  49. #include <tk.h>
  50. #endif
  51. #include "tkinter.h"
  52. /* For Tcl 8.2 and 8.3, CONST* is not defined (except on Cygwin). */
  53. #ifndef CONST84_RETURN
  54. #define CONST84_RETURN
  55. #undef CONST
  56. #define CONST
  57. #endif
  58. #if TK_VERSION_HEX < 0x08030102
  59. #error "Tk older than 8.3.1 not supported"
  60. #endif
  61. /* Unicode conversion assumes that Tcl_UniChar is two bytes.
  62. We cannot test this directly, so we test UTF-8 size instead,
  63. expecting that TCL_UTF_MAX is changed if Tcl ever supports
  64. either UTF-16 or UCS-4.
  65. Redhat 8 sets TCL_UTF_MAX to 6, and uses wchar_t for
  66. Tcl_Unichar. This is also ok as long as Python uses UCS-4,
  67. as well.
  68. */
  69. #if TCL_UTF_MAX != 3 && !(defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==6)
  70. #error "unsupported Tcl configuration"
  71. #endif
  72. #if !(defined(MS_WINDOWS) || defined(__CYGWIN__))
  73. #define HAVE_CREATEFILEHANDLER
  74. #endif
  75. #ifdef HAVE_CREATEFILEHANDLER
  76. /* This bit is to ensure that TCL_UNIX_FD is defined and doesn't interfere
  77. with the proper calculation of FHANDLETYPE == TCL_UNIX_FD below. */
  78. #ifndef TCL_UNIX_FD
  79. # ifdef TCL_WIN_SOCKET
  80. # define TCL_UNIX_FD (! TCL_WIN_SOCKET)
  81. # else
  82. # define TCL_UNIX_FD 1
  83. # endif
  84. #endif
  85. /* Tcl_CreateFileHandler() changed several times; these macros deal with the
  86. messiness. In Tcl 8.0 and later, it is not available on Windows (and on
  87. Unix, only because Jack added it back); when available on Windows, it only
  88. applies to sockets. */
  89. #ifdef MS_WINDOWS
  90. #define FHANDLETYPE TCL_WIN_SOCKET
  91. #else
  92. #define FHANDLETYPE TCL_UNIX_FD
  93. #endif
  94. /* If Tcl can wait for a Unix file descriptor, define the EventHook() routine
  95. which uses this to handle Tcl events while the user is typing commands. */
  96. #if FHANDLETYPE == TCL_UNIX_FD
  97. #define WAIT_FOR_STDIN
  98. #endif
  99. #endif /* HAVE_CREATEFILEHANDLER */
  100. #ifdef MS_WINDOWS
  101. #include <conio.h>
  102. #define WAIT_FOR_STDIN
  103. #endif
  104. #ifdef WITH_THREAD
  105. /* The threading situation is complicated. Tcl is not thread-safe, except
  106. when configured with --enable-threads.
  107. So we need to use a lock around all uses of Tcl. Previously, the Python
  108. interpreter lock was used for this. However, this causes problems when
  109. other Python threads need to run while Tcl is blocked waiting for events.
  110. To solve this problem, a separate lock for Tcl is introduced. Holding it
  111. is incompatible with holding Python's interpreter lock. The following four
  112. macros manipulate both locks together.
  113. ENTER_TCL and LEAVE_TCL are brackets, just like Py_BEGIN_ALLOW_THREADS and
  114. Py_END_ALLOW_THREADS. They should be used whenever a call into Tcl is made
  115. that could call an event handler, or otherwise affect the state of a Tcl
  116. interpreter. These assume that the surrounding code has the Python
  117. interpreter lock; inside the brackets, the Python interpreter lock has been
  118. released and the lock for Tcl has been acquired.
  119. Sometimes, it is necessary to have both the Python lock and the Tcl lock.
  120. (For example, when transferring data from the Tcl interpreter result to a
  121. Python string object.) This can be done by using different macros to close
  122. the ENTER_TCL block: ENTER_OVERLAP reacquires the Python lock (and restores
  123. the thread state) but doesn't release the Tcl lock; LEAVE_OVERLAP_TCL
  124. releases the Tcl lock.
  125. By contrast, ENTER_PYTHON and LEAVE_PYTHON are used in Tcl event
  126. handlers when the handler needs to use Python. Such event handlers are
  127. entered while the lock for Tcl is held; the event handler presumably needs
  128. to use Python. ENTER_PYTHON releases the lock for Tcl and acquires
  129. the Python interpreter lock, restoring the appropriate thread state, and
  130. LEAVE_PYTHON releases the Python interpreter lock and re-acquires the lock
  131. for Tcl. It is okay for ENTER_TCL/LEAVE_TCL pairs to be contained inside
  132. the code between ENTER_PYTHON and LEAVE_PYTHON.
  133. These locks expand to several statements and brackets; they should not be
  134. used in branches of if statements and the like.
  135. If Tcl is threaded, this approach won't work anymore. The Tcl interpreter is
  136. only valid in the thread that created it, and all Tk activity must happen in this
  137. thread, also. That means that the mainloop must be invoked in the thread that
  138. created the interpreter. Invoking commands from other threads is possible;
  139. _tkinter will queue an event for the interpreter thread, which will then
  140. execute the command and pass back the result. If the main thread is not in the
  141. mainloop, and invoking commands causes an exception; if the main loop is running
  142. but not processing events, the command invocation will block.
  143. In addition, for a threaded Tcl, a single global tcl_tstate won't be sufficient
  144. anymore, since multiple Tcl interpreters may simultaneously dispatch in different
  145. threads. So we use the Tcl TLS API.
  146. */
  147. static PyThread_type_lock tcl_lock = 0;
  148. #ifdef TCL_THREADS
  149. static Tcl_ThreadDataKey state_key;
  150. typedef PyThreadState *ThreadSpecificData;
  151. #define tcl_tstate (*(PyThreadState**)Tcl_GetThreadData(&state_key, sizeof(PyThreadState*)))
  152. #else
  153. static PyThreadState *tcl_tstate = NULL;
  154. #endif
  155. #define ENTER_TCL \
  156. { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
  157. if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
  158. #define LEAVE_TCL \
  159. tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS}
  160. #define ENTER_OVERLAP \
  161. Py_END_ALLOW_THREADS
  162. #define LEAVE_OVERLAP_TCL \
  163. tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); }
  164. #define ENTER_PYTHON \
  165. { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
  166. if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
  167. #define LEAVE_PYTHON \
  168. { PyThreadState *tstate = PyEval_SaveThread(); \
  169. if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
  170. #define CHECK_TCL_APPARTMENT \
  171. if (((TkappObject *)self)->threaded && \
  172. ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \
  173. PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \
  174. return 0; \
  175. }
  176. #else
  177. #define ENTER_TCL
  178. #define LEAVE_TCL
  179. #define ENTER_OVERLAP
  180. #define LEAVE_OVERLAP_TCL
  181. #define ENTER_PYTHON
  182. #define LEAVE_PYTHON
  183. #define CHECK_TCL_APPARTMENT
  184. #endif
  185. #ifndef FREECAST
  186. #define FREECAST (char *)
  187. #endif
  188. /**** Tkapp Object Declaration ****/
  189. static PyTypeObject Tkapp_Type;
  190. typedef struct {
  191. PyObject_HEAD
  192. Tcl_Interp *interp;
  193. int wantobjects;
  194. int threaded; /* True if tcl_platform[threaded] */
  195. Tcl_ThreadId thread_id;
  196. int dispatching;
  197. /* We cannot include tclInt.h, as this is internal.
  198. So we cache interesting types here. */
  199. Tcl_ObjType *BooleanType;
  200. Tcl_ObjType *ByteArrayType;
  201. Tcl_ObjType *DoubleType;
  202. Tcl_ObjType *IntType;
  203. Tcl_ObjType *ListType;
  204. Tcl_ObjType *ProcBodyType;
  205. Tcl_ObjType *StringType;
  206. } TkappObject;
  207. #define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type)
  208. #define Tkapp_Interp(v) (((TkappObject *) (v))->interp)
  209. #define Tkapp_Result(v) Tcl_GetStringResult(Tkapp_Interp(v))
  210. #define DEBUG_REFCNT(v) (printf("DEBUG: id=%p, refcnt=%i\n", \
  211. (void *) v, Py_REFCNT(v)))
  212. /**** Error Handling ****/
  213. static PyObject *Tkinter_TclError;
  214. static int quitMainLoop = 0;
  215. static int errorInCmd = 0;
  216. static PyObject *excInCmd;
  217. static PyObject *valInCmd;
  218. static PyObject *trbInCmd;
  219. #ifdef TKINTER_PROTECT_LOADTK
  220. static int tk_load_failed;
  221. #endif
  222. static PyObject *
  223. Tkinter_Error(PyObject *v)
  224. {
  225. PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
  226. return NULL;
  227. }
  228. /**** Utils ****/
  229. static int Tkinter_busywaitinterval = 20;
  230. #ifdef WITH_THREAD
  231. #ifndef MS_WINDOWS
  232. /* Millisecond sleep() for Unix platforms. */
  233. static void
  234. Sleep(int milli)
  235. {
  236. /* XXX Too bad if you don't have select(). */
  237. struct timeval t;
  238. t.tv_sec = milli/1000;
  239. t.tv_usec = (milli%1000) * 1000;
  240. select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
  241. }
  242. #endif /* MS_WINDOWS */
  243. /* Wait up to 1s for the mainloop to come up. */
  244. static int
  245. WaitForMainloop(TkappObject* self)
  246. {
  247. int i;
  248. for (i = 0; i < 10; i++) {
  249. if (self->dispatching)
  250. return 1;
  251. Py_BEGIN_ALLOW_THREADS
  252. Sleep(100);
  253. Py_END_ALLOW_THREADS
  254. }
  255. if (self->dispatching)
  256. return 1;
  257. PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop");
  258. return 0;
  259. }
  260. #endif /* WITH_THREAD */
  261. static char *
  262. AsString(PyObject *value, PyObject *tmp)
  263. {
  264. if (PyString_Check(value))
  265. return PyString_AsString(value);
  266. #ifdef Py_USING_UNICODE
  267. else if (PyUnicode_Check(value)) {
  268. PyObject *v = PyUnicode_AsUTF8String(value);
  269. if (v == NULL)
  270. return NULL;
  271. if (PyList_Append(tmp, v) != 0) {
  272. Py_DECREF(v);
  273. return NULL;
  274. }
  275. Py_DECREF(v);
  276. return PyString_AsString(v);
  277. }
  278. #endif
  279. else {
  280. PyObject *v = PyObject_Str(value);
  281. if (v == NULL)
  282. return NULL;
  283. if (PyList_Append(tmp, v) != 0) {
  284. Py_DECREF(v);
  285. return NULL;
  286. }
  287. Py_DECREF(v);
  288. return PyString_AsString(v);
  289. }
  290. }
  291. #define ARGSZ 64
  292. static char *
  293. Merge(PyObject *args)
  294. {
  295. PyObject *tmp = NULL;
  296. char *argvStore[ARGSZ];
  297. char **argv = NULL;
  298. int fvStore[ARGSZ];
  299. int *fv = NULL;
  300. int argc = 0, fvc = 0, i;
  301. char *res = NULL;
  302. if (!(tmp = PyList_New(0)))
  303. return NULL;
  304. argv = argvStore;
  305. fv = fvStore;
  306. if (args == NULL)
  307. argc = 0;
  308. else if (!PyTuple_Check(args)) {
  309. argc = 1;
  310. fv[0] = 0;
  311. if (!(argv[0] = AsString(args, tmp)))
  312. goto finally;
  313. }
  314. else {
  315. argc = PyTuple_Size(args);
  316. if (argc > ARGSZ) {
  317. argv = (char **)ckalloc(argc * sizeof(char *));
  318. fv = (int *)ckalloc(argc * sizeof(int));
  319. if (argv == NULL || fv == NULL) {
  320. PyErr_NoMemory();
  321. goto finally;
  322. }
  323. }
  324. for (i = 0; i < argc; i++) {
  325. PyObject *v = PyTuple_GetItem(args, i);
  326. if (PyTuple_Check(v)) {
  327. fv[i] = 1;
  328. if (!(argv[i] = Merge(v)))
  329. goto finally;
  330. fvc++;
  331. }
  332. else if (v == Py_None) {
  333. argc = i;
  334. break;
  335. }
  336. else {
  337. fv[i] = 0;
  338. if (!(argv[i] = AsString(v, tmp)))
  339. goto finally;
  340. fvc++;
  341. }
  342. }
  343. }
  344. res = Tcl_Merge(argc, argv);
  345. if (res == NULL)
  346. PyErr_SetString(Tkinter_TclError, "merge failed");
  347. finally:
  348. for (i = 0; i < fvc; i++)
  349. if (fv[i]) {
  350. ckfree(argv[i]);
  351. }
  352. if (argv != argvStore)
  353. ckfree(FREECAST argv);
  354. if (fv != fvStore)
  355. ckfree(FREECAST fv);
  356. Py_DECREF(tmp);
  357. return res;
  358. }
  359. static PyObject *
  360. Split(char *list)
  361. {
  362. int argc;
  363. char **argv;
  364. PyObject *v;
  365. if (list == NULL) {
  366. Py_INCREF(Py_None);
  367. return Py_None;
  368. }
  369. if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
  370. /* Not a list.
  371. * Could be a quoted string containing funnies, e.g. {"}.
  372. * Return the string itself.
  373. */
  374. return PyString_FromString(list);
  375. }
  376. if (argc == 0)
  377. v = PyString_FromString("");
  378. else if (argc == 1)
  379. v = PyString_FromString(argv[0]);
  380. else if ((v = PyTuple_New(argc)) != NULL) {
  381. int i;
  382. PyObject *w;
  383. for (i = 0; i < argc; i++) {
  384. if ((w = Split(argv[i])) == NULL) {
  385. Py_DECREF(v);
  386. v = NULL;
  387. break;
  388. }
  389. PyTuple_SetItem(v, i, w);
  390. }
  391. }
  392. Tcl_Free(FREECAST argv);
  393. return v;
  394. }
  395. /* In some cases, Tcl will still return strings that are supposed to be
  396. lists. SplitObj walks through a nested tuple, finding string objects that
  397. need to be split. */
  398. static PyObject *
  399. SplitObj(PyObject *arg)
  400. {
  401. if (PyTuple_Check(arg)) {
  402. int i, size;
  403. PyObject *elem, *newelem, *result;
  404. size = PyTuple_Size(arg);
  405. result = NULL;
  406. /* Recursively invoke SplitObj for all tuple items.
  407. If this does not return a new object, no action is
  408. needed. */
  409. for(i = 0; i < size; i++) {
  410. elem = PyTuple_GetItem(arg, i);
  411. newelem = SplitObj(elem);
  412. if (!newelem) {
  413. Py_XDECREF(result);
  414. return NULL;
  415. }
  416. if (!result) {
  417. int k;
  418. if (newelem == elem) {
  419. Py_DECREF(newelem);
  420. continue;
  421. }
  422. result = PyTuple_New(size);
  423. if (!result)
  424. return NULL;
  425. for(k = 0; k < i; k++) {
  426. elem = PyTuple_GetItem(arg, k);
  427. Py_INCREF(elem);
  428. PyTuple_SetItem(result, k, elem);
  429. }
  430. }
  431. PyTuple_SetItem(result, i, newelem);
  432. }
  433. if (result)
  434. return result;
  435. /* Fall through, returning arg. */
  436. }
  437. else if (PyString_Check(arg)) {
  438. int argc;
  439. char **argv;
  440. char *list = PyString_AsString(arg);
  441. if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
  442. Py_INCREF(arg);
  443. return arg;
  444. }
  445. Tcl_Free(FREECAST argv);
  446. if (argc > 1)
  447. return Split(PyString_AsString(arg));
  448. /* Fall through, returning arg. */
  449. }
  450. Py_INCREF(arg);
  451. return arg;
  452. }
  453. /**** Tkapp Object ****/
  454. #ifndef WITH_APPINIT
  455. int
  456. Tcl_AppInit(Tcl_Interp *interp)
  457. {
  458. const char * _tkinter_skip_tk_init;
  459. if (Tcl_Init(interp) == TCL_ERROR) {
  460. PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp));
  461. return TCL_ERROR;
  462. }
  463. _tkinter_skip_tk_init = Tcl_GetVar(interp,
  464. "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
  465. if (_tkinter_skip_tk_init != NULL &&
  466. strcmp(_tkinter_skip_tk_init, "1") == 0) {
  467. return TCL_OK;
  468. }
  469. #ifdef TKINTER_PROTECT_LOADTK
  470. if (tk_load_failed) {
  471. PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG);
  472. return TCL_ERROR;
  473. }
  474. #endif
  475. if (Tk_Init(interp) == TCL_ERROR) {
  476. #ifdef TKINTER_PROTECT_LOADTK
  477. tk_load_failed = 1;
  478. #endif
  479. PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
  480. return TCL_ERROR;
  481. }
  482. return TCL_OK;
  483. }
  484. #endif /* !WITH_APPINIT */
  485. /* Initialize the Tk application; see the `main' function in
  486. * `tkMain.c'.
  487. */
  488. static void EnableEventHook(void); /* Forward */
  489. static void DisableEventHook(void); /* Forward */
  490. static TkappObject *
  491. Tkapp_New(char *screenName, char *baseName, char *className,
  492. int interactive, int wantobjects, int wantTk, int sync, char *use)
  493. {
  494. TkappObject *v;
  495. char *argv0;
  496. v = PyObject_New(TkappObject, &Tkapp_Type);
  497. if (v == NULL)
  498. return NULL;
  499. v->interp = Tcl_CreateInterp();
  500. v->wantobjects = wantobjects;
  501. v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded",
  502. TCL_GLOBAL_ONLY) != NULL;
  503. v->thread_id = Tcl_GetCurrentThread();
  504. v->dispatching = 0;
  505. #ifndef TCL_THREADS
  506. if (v->threaded) {
  507. PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not");
  508. Py_DECREF(v);
  509. return 0;
  510. }
  511. #endif
  512. #ifdef WITH_THREAD
  513. if (v->threaded && tcl_lock) {
  514. /* If Tcl is threaded, we don't need the lock. */
  515. PyThread_free_lock(tcl_lock);
  516. tcl_lock = NULL;
  517. }
  518. #endif
  519. v->BooleanType = Tcl_GetObjType("boolean");
  520. v->ByteArrayType = Tcl_GetObjType("bytearray");
  521. v->DoubleType = Tcl_GetObjType("double");
  522. v->IntType = Tcl_GetObjType("int");
  523. v->ListType = Tcl_GetObjType("list");
  524. v->ProcBodyType = Tcl_GetObjType("procbody");
  525. v->StringType = Tcl_GetObjType("string");
  526. /* Delete the 'exit' command, which can screw things up */
  527. Tcl_DeleteCommand(v->interp, "exit");
  528. if (screenName != NULL)
  529. Tcl_SetVar2(v->interp, "env", "DISPLAY",
  530. screenName, TCL_GLOBAL_ONLY);
  531. if (interactive)
  532. Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
  533. else
  534. Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
  535. /* This is used to get the application class for Tk 4.1 and up */
  536. argv0 = (char*)ckalloc(strlen(className) + 1);
  537. if (!argv0) {
  538. PyErr_NoMemory();
  539. Py_DECREF(v);
  540. return NULL;
  541. }
  542. strcpy(argv0, className);
  543. if (Py_ISUPPER(Py_CHARMASK(argv0[0])))
  544. argv0[0] = Py_TOLOWER(Py_CHARMASK(argv0[0]));
  545. Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
  546. ckfree(argv0);
  547. if (! wantTk) {
  548. Tcl_SetVar(v->interp,
  549. "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY);
  550. }
  551. #ifdef TKINTER_PROTECT_LOADTK
  552. else if (tk_load_failed) {
  553. Tcl_SetVar(v->interp,
  554. "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
  555. }
  556. #endif
  557. /* some initial arguments need to be in argv */
  558. if (sync || use) {
  559. char *args;
  560. int len = 0;
  561. if (sync)
  562. len += sizeof "-sync";
  563. if (use)
  564. len += strlen(use) + sizeof "-use ";
  565. args = (char*)ckalloc(len);
  566. if (!args) {
  567. PyErr_NoMemory();
  568. Py_DECREF(v);
  569. return NULL;
  570. }
  571. args[0] = '\0';
  572. if (sync)
  573. strcat(args, "-sync");
  574. if (use) {
  575. if (sync)
  576. strcat(args, " ");
  577. strcat(args, "-use ");
  578. strcat(args, use);
  579. }
  580. Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY);
  581. ckfree(args);
  582. }
  583. if (Tcl_AppInit(v->interp) != TCL_OK) {
  584. PyObject *result = Tkinter_Error((PyObject *)v);
  585. #ifdef TKINTER_PROTECT_LOADTK
  586. if (wantTk) {
  587. const char *_tkinter_tk_failed;
  588. _tkinter_tk_failed = Tcl_GetVar(v->interp,
  589. "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
  590. if ( _tkinter_tk_failed != NULL &&
  591. strcmp(_tkinter_tk_failed, "1") == 0) {
  592. tk_load_failed = 1;
  593. }
  594. }
  595. #endif
  596. Py_DECREF((PyObject *)v);
  597. return (TkappObject *)result;
  598. }
  599. EnableEventHook();
  600. return v;
  601. }
  602. #ifdef WITH_THREAD
  603. static void
  604. Tkapp_ThreadSend(TkappObject *self, Tcl_Event *ev,
  605. Tcl_Condition *cond, Tcl_Mutex *mutex)
  606. {
  607. Py_BEGIN_ALLOW_THREADS;
  608. Tcl_MutexLock(mutex);
  609. Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
  610. Tcl_ThreadAlert(self->thread_id);
  611. Tcl_ConditionWait(cond, mutex, NULL);
  612. Tcl_MutexUnlock(mutex);
  613. Py_END_ALLOW_THREADS
  614. }
  615. #endif
  616. /** Tcl Eval **/
  617. typedef struct {
  618. PyObject_HEAD
  619. Tcl_Obj *value;
  620. PyObject *string; /* This cannot cause cycles. */
  621. } PyTclObject;
  622. staticforward PyTypeObject PyTclObject_Type;
  623. #define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type)
  624. static PyObject *
  625. newPyTclObject(Tcl_Obj *arg)
  626. {
  627. PyTclObject *self;
  628. self = PyObject_New(PyTclObject, &PyTclObject_Type);
  629. if (self == NULL)
  630. return NULL;
  631. Tcl_IncrRefCount(arg);
  632. self->value = arg;
  633. self->string = NULL;
  634. return (PyObject*)self;
  635. }
  636. static void
  637. PyTclObject_dealloc(PyTclObject *self)
  638. {
  639. Tcl_DecrRefCount(self->value);
  640. Py_XDECREF(self->string);
  641. PyObject_Del(self);
  642. }
  643. static PyObject *
  644. PyTclObject_str(PyTclObject *self)
  645. {
  646. if (self->string && PyString_Check(self->string)) {
  647. Py_INCREF(self->string);
  648. return self->string;
  649. }
  650. /* XXX Could cache value if it is an ASCII string. */
  651. return PyString_FromString(Tcl_GetString(self->value));
  652. }
  653. static char*
  654. PyTclObject_TclString(PyObject *self)
  655. {
  656. return Tcl_GetString(((PyTclObject*)self)->value);
  657. }
  658. /* Like _str, but create Unicode if necessary. */
  659. PyDoc_STRVAR(PyTclObject_string__doc__,
  660. "the string representation of this object, either as string or Unicode");
  661. static PyObject *
  662. PyTclObject_string(PyTclObject *self, void *ignored)
  663. {
  664. char *s;
  665. int i, len;
  666. if (!self->string) {
  667. s = Tcl_GetStringFromObj(self->value, &len);
  668. for (i = 0; i < len; i++)
  669. if (s[i] & 0x80)
  670. break;
  671. #ifdef Py_USING_UNICODE
  672. if (i == len)
  673. /* It is an ASCII string. */
  674. self->string = PyString_FromStringAndSize(s, len);
  675. else {
  676. self->string = PyUnicode_DecodeUTF8(s, len, "strict");
  677. if (!self->string) {
  678. PyErr_Clear();
  679. self->string = PyString_FromStringAndSize(s, len);
  680. }
  681. }
  682. #else
  683. self->string = PyString_FromStringAndSize(s, len);
  684. #endif
  685. if (!self->string)
  686. return NULL;
  687. }
  688. Py_INCREF(self->string);
  689. return self->string;
  690. }
  691. #ifdef Py_USING_UNICODE
  692. PyDoc_STRVAR(PyTclObject_unicode__doc__, "convert argument to unicode");
  693. static PyObject *
  694. PyTclObject_unicode(PyTclObject *self, void *ignored)
  695. {
  696. char *s;
  697. int len;
  698. if (self->string && PyUnicode_Check(self->string)) {
  699. Py_INCREF(self->string);
  700. return self->string;
  701. }
  702. /* XXX Could chache result if it is non-ASCII. */
  703. s = Tcl_GetStringFromObj(self->value, &len);
  704. return PyUnicode_DecodeUTF8(s, len, "strict");
  705. }
  706. #endif
  707. static PyObject *
  708. PyTclObject_repr(PyTclObject *self)
  709. {
  710. char buf[50];
  711. PyOS_snprintf(buf, 50, "<%s object at %p>",
  712. self->value->typePtr->name, self->value);
  713. return PyString_FromString(buf);
  714. }
  715. static int
  716. PyTclObject_cmp(PyTclObject *self, PyTclObject *other)
  717. {
  718. int res;
  719. res = strcmp(Tcl_GetString(self->value),
  720. Tcl_GetString(other->value));
  721. if (res < 0) return -1;
  722. if (res > 0) return 1;
  723. return 0;
  724. }
  725. PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
  726. static PyObject*
  727. get_typename(PyTclObject* obj, void* ignored)
  728. {
  729. return PyString_FromString(obj->value->typePtr->name);
  730. }
  731. static PyGetSetDef PyTclObject_getsetlist[] = {
  732. {"typename", (getter)get_typename, NULL, get_typename__doc__},
  733. {"string", (getter)PyTclObject_string, NULL,
  734. PyTclObject_string__doc__},
  735. {0},
  736. };
  737. static PyMethodDef PyTclObject_methods[] = {
  738. #ifdef Py_USING_UNICODE
  739. {"__unicode__", (PyCFunction)PyTclObject_unicode, METH_NOARGS,
  740. PyTclObject_unicode__doc__},
  741. #endif
  742. {0}
  743. };
  744. statichere PyTypeObject PyTclObject_Type = {
  745. PyObject_HEAD_INIT(NULL)
  746. 0, /*ob_size*/
  747. "_tkinter.Tcl_Obj", /*tp_name*/
  748. sizeof(PyTclObject), /*tp_basicsize*/
  749. 0, /*tp_itemsize*/
  750. /* methods */
  751. (destructor)PyTclObject_dealloc, /*tp_dealloc*/
  752. 0, /*tp_print*/
  753. 0, /*tp_getattr*/
  754. 0, /*tp_setattr*/
  755. (cmpfunc)PyTclObject_cmp, /*tp_compare*/
  756. (reprfunc)PyTclObject_repr, /*tp_repr*/
  757. 0, /*tp_as_number*/
  758. 0, /*tp_as_sequence*/
  759. 0, /*tp_as_mapping*/
  760. 0, /*tp_hash*/
  761. 0, /*tp_call*/
  762. (reprfunc)PyTclObject_str, /*tp_str*/
  763. PyObject_GenericGetAttr,/*tp_getattro*/
  764. 0, /*tp_setattro*/
  765. 0, /*tp_as_buffer*/
  766. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  767. 0, /*tp_doc*/
  768. 0, /*tp_traverse*/
  769. 0, /*tp_clear*/
  770. 0, /*tp_richcompare*/
  771. 0, /*tp_weaklistoffset*/
  772. 0, /*tp_iter*/
  773. 0, /*tp_iternext*/
  774. PyTclObject_methods, /*tp_methods*/
  775. 0, /*tp_members*/
  776. PyTclObject_getsetlist, /*tp_getset*/
  777. 0, /*tp_base*/
  778. 0, /*tp_dict*/
  779. 0, /*tp_descr_get*/
  780. 0, /*tp_descr_set*/
  781. 0, /*tp_dictoffset*/
  782. 0, /*tp_init*/
  783. 0, /*tp_alloc*/
  784. 0, /*tp_new*/
  785. 0, /*tp_free*/
  786. 0, /*tp_is_gc*/
  787. };
  788. static Tcl_Obj*
  789. AsObj(PyObject *value)
  790. {
  791. Tcl_Obj *result;
  792. if (PyString_Check(value))
  793. return Tcl_NewStringObj(PyString_AS_STRING(value),
  794. PyString_GET_SIZE(value));
  795. else if (PyBool_Check(value))
  796. return Tcl_NewBooleanObj(PyObject_IsTrue(value));
  797. else if (PyInt_Check(value))
  798. return Tcl_NewLongObj(PyInt_AS_LONG(value));
  799. else if (PyFloat_Check(value))
  800. return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
  801. else if (PyTuple_Check(value)) {
  802. Tcl_Obj **argv = (Tcl_Obj**)
  803. ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*));
  804. int i;
  805. if(!argv)
  806. return 0;
  807. for(i=0;i<PyTuple_Size(value);i++)
  808. argv[i] = AsObj(PyTuple_GetItem(value,i));
  809. result = Tcl_NewListObj(PyTuple_Size(value), argv);
  810. ckfree(FREECAST argv);
  811. return result;
  812. }
  813. #ifdef Py_USING_UNICODE
  814. else if (PyUnicode_Check(value)) {
  815. Py_UNICODE *inbuf = PyUnicode_AS_UNICODE(value);
  816. Py_ssize_t size = PyUnicode_GET_SIZE(value);
  817. /* This #ifdef assumes that Tcl uses UCS-2.
  818. See TCL_UTF_MAX test above. */
  819. #if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX == 3
  820. Tcl_UniChar *outbuf = NULL;
  821. Py_ssize_t i;
  822. size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar);
  823. if (allocsize >= size)
  824. outbuf = (Tcl_UniChar*)ckalloc(allocsize);
  825. /* Else overflow occurred, and we take the next exit */
  826. if (!outbuf) {
  827. PyErr_NoMemory();
  828. return NULL;
  829. }
  830. for (i = 0; i < size; i++) {
  831. if (inbuf[i] >= 0x10000) {
  832. /* Tcl doesn't do UTF-16, yet. */
  833. PyErr_SetString(PyExc_ValueError,
  834. "unsupported character");
  835. ckfree(FREECAST outbuf);
  836. return NULL;
  837. }
  838. outbuf[i] = inbuf[i];
  839. }
  840. result = Tcl_NewUnicodeObj(outbuf, size);
  841. ckfree(FREECAST outbuf);
  842. return result;
  843. #else
  844. return Tcl_NewUnicodeObj(inbuf, size);
  845. #endif
  846. }
  847. #endif
  848. else if(PyTclObject_Check(value)) {
  849. Tcl_Obj *v = ((PyTclObject*)value)->value;
  850. Tcl_IncrRefCount(v);
  851. return v;
  852. }
  853. else {
  854. PyObject *v = PyObject_Str(value);
  855. if (!v)
  856. return 0;
  857. result = AsObj(v);
  858. Py_DECREF(v);
  859. return result;
  860. }
  861. }
  862. static PyObject*
  863. FromObj(PyObject* tkapp, Tcl_Obj *value)
  864. {
  865. PyObject *result = NULL;
  866. TkappObject *app = (TkappObject*)tkapp;
  867. if (value->typePtr == NULL) {
  868. /* If the result contains any bytes with the top bit set,
  869. it's UTF-8 and we should decode it to Unicode */
  870. #ifdef Py_USING_UNICODE
  871. int i;
  872. char *s = value->bytes;
  873. int len = value->length;
  874. for (i = 0; i < len; i++) {
  875. if (value->bytes[i] & 0x80)
  876. break;
  877. }
  878. if (i == value->length)
  879. result = PyString_FromStringAndSize(s, len);
  880. else {
  881. /* Convert UTF-8 to Unicode string */
  882. result = PyUnicode_DecodeUTF8(s, len, "strict");
  883. if (result == NULL) {
  884. PyErr_Clear();
  885. result = PyString_FromStringAndSize(s, len);
  886. }
  887. }
  888. #else
  889. result = PyString_FromStringAndSize(value->bytes, value->length);
  890. #endif
  891. return result;
  892. }
  893. if (value->typePtr == app->BooleanType) {
  894. result = value->internalRep.longValue ? Py_True : Py_False;
  895. Py_INCREF(result);
  896. return result;
  897. }
  898. if (value->typePtr == app->ByteArrayType) {
  899. int size;
  900. char *data = (char*)Tcl_GetByteArrayFromObj(value, &size);
  901. return PyString_FromStringAndSize(data, size);
  902. }
  903. if (value->typePtr == app->DoubleType) {
  904. return PyFloat_FromDouble(value->internalRep.doubleValue);
  905. }
  906. if (value->typePtr == app->IntType) {
  907. return PyInt_FromLong(value->internalRep.longValue);
  908. }
  909. if (value->typePtr == app->ListType) {
  910. int size;
  911. int i, status;
  912. PyObject *elem;
  913. Tcl_Obj *tcl_elem;
  914. status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size);
  915. if (status == TCL_ERROR)
  916. return Tkinter_Error(tkapp);
  917. result = PyTuple_New(size);
  918. if (!result)
  919. return NULL;
  920. for (i = 0; i < size; i++) {
  921. status = Tcl_ListObjIndex(Tkapp_Interp(tkapp),
  922. value, i, &tcl_elem);
  923. if (status == TCL_ERROR) {
  924. Py_DECREF(result);
  925. return Tkinter_Error(tkapp);
  926. }
  927. elem = FromObj(tkapp, tcl_elem);
  928. if (!elem) {
  929. Py_DECREF(result);
  930. return NULL;
  931. }
  932. PyTuple_SetItem(result, i, elem);
  933. }
  934. return result;
  935. }
  936. if (value->typePtr == app->ProcBodyType) {
  937. /* fall through: return tcl object. */
  938. }
  939. if (value->typePtr == app->StringType) {
  940. #ifdef Py_USING_UNICODE
  941. #if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==3
  942. PyObject *result;
  943. int size;
  944. Tcl_UniChar *input;
  945. Py_UNICODE *output;
  946. size = Tcl_GetCharLength(value);
  947. result = PyUnicode_FromUnicode(NULL, size);
  948. if (!result)
  949. return NULL;
  950. input = Tcl_GetUnicode(value);
  951. output = PyUnicode_AS_UNICODE(result);
  952. while (size--)
  953. *output++ = *input++;
  954. return result;
  955. #else
  956. return PyUnicode_FromUnicode(Tcl_GetUnicode(value),
  957. Tcl_GetCharLength(value));
  958. #endif
  959. #else
  960. int size;
  961. char *c;
  962. c = Tcl_GetStringFromObj(value, &size);
  963. return PyString_FromStringAndSize(c, size);
  964. #endif
  965. }
  966. return newPyTclObject(value);
  967. }
  968. #ifdef WITH_THREAD
  969. /* This mutex synchronizes inter-thread command calls. */
  970. TCL_DECLARE_MUTEX(call_mutex)
  971. typedef struct Tkapp_CallEvent {
  972. Tcl_Event ev; /* Must be first */
  973. TkappObject *self;
  974. PyObject *args;
  975. int flags;
  976. PyObject **res;
  977. PyObject **exc_type, **exc_value, **exc_tb;
  978. Tcl_Condition *done;
  979. } Tkapp_CallEvent;
  980. #endif
  981. void
  982. Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc)
  983. {
  984. int i;
  985. for (i = 0; i < objc; i++)
  986. Tcl_DecrRefCount(objv[i]);
  987. if (objv != objStore)
  988. ckfree(FREECAST objv);
  989. }
  990. /* Convert Python objects to Tcl objects. This must happen in the
  991. interpreter thread, which may or may not be the calling thread. */
  992. static Tcl_Obj**
  993. Tkapp_CallArgs(PyObject *args, Tcl_Obj** objStore, int *pobjc)
  994. {
  995. Tcl_Obj **objv = objStore;
  996. int objc = 0, i;
  997. if (args == NULL)
  998. /* do nothing */;
  999. else if (!PyTuple_Check(args)) {
  1000. objv[0] = AsObj(args);
  1001. if (objv[0] == 0)
  1002. goto finally;
  1003. objc = 1;
  1004. Tcl_IncrRefCount(objv[0]);
  1005. }
  1006. else {
  1007. objc = PyTuple_Size(args);
  1008. if (objc > ARGSZ) {
  1009. objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
  1010. if (objv == NULL) {
  1011. PyErr_NoMemory();
  1012. objc = 0;
  1013. goto finally;
  1014. }
  1015. }
  1016. for (i = 0; i < objc; i++) {
  1017. PyObject *v = PyTuple_GetItem(args, i);
  1018. if (v == Py_None) {
  1019. objc = i;
  1020. break;
  1021. }
  1022. objv[i] = AsObj(v);
  1023. if (!objv[i]) {
  1024. /* Reset objc, so it attempts to clear
  1025. objects only up to i. */
  1026. objc = i;
  1027. goto finally;
  1028. }
  1029. Tcl_IncrRefCount(objv[i]);
  1030. }
  1031. }
  1032. *pobjc = objc;
  1033. return objv;
  1034. finally:
  1035. Tkapp_CallDeallocArgs(objv, objStore, objc);
  1036. return NULL;
  1037. }
  1038. /* Convert the results of a command call into a Python objects. */
  1039. static PyObject*
  1040. Tkapp_CallResult(TkappObject *self)
  1041. {
  1042. PyObject *res = NULL;
  1043. if(self->wantobjects) {
  1044. Tcl_Obj *value = Tcl_GetObjResult(self->interp);
  1045. /* Not sure whether the IncrRef is necessary, but something
  1046. may overwrite the interpreter result while we are
  1047. converting it. */
  1048. Tcl_IncrRefCount(value);
  1049. res = FromObj((PyObject*)self, value);
  1050. Tcl_DecrRefCount(value);
  1051. } else {
  1052. const char *s = Tcl_GetStringResult(self->interp);
  1053. const char *p = s;
  1054. /* If the result contains any bytes with the top bit set,
  1055. it's UTF-8 and we should decode it to Unicode */
  1056. #ifdef Py_USING_UNICODE
  1057. while (*p != '\0') {
  1058. if (*p & 0x80)
  1059. break;
  1060. p++;
  1061. }
  1062. if (*p == '\0')
  1063. res = PyString_FromStringAndSize(s, (int)(p-s));
  1064. else {
  1065. /* Convert UTF-8 to Unicode string */
  1066. p = strchr(p, '\0');
  1067. res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
  1068. if (res == NULL) {
  1069. PyErr_Clear();
  1070. res = PyString_FromStringAndSize(s, (int)(p-s));
  1071. }
  1072. }
  1073. #else
  1074. p = strchr(p, '\0');
  1075. res = PyString_FromStringAndSize(s, (int)(p-s));
  1076. #endif
  1077. }
  1078. return res;
  1079. }
  1080. #ifdef WITH_THREAD
  1081. /* Tkapp_CallProc is the event procedure that is executed in the context of
  1082. the Tcl interpreter thread. Initially, it holds the Tcl lock, and doesn't
  1083. hold the Python lock. */
  1084. static int
  1085. Tkapp_CallProc(Tkapp_CallEvent *e, int flags)
  1086. {
  1087. Tcl_Obj *objStore[ARGSZ];
  1088. Tcl_Obj **objv;
  1089. int objc;
  1090. int i;
  1091. ENTER_PYTHON
  1092. objv = Tkapp_CallArgs(e->args, objStore, &objc);
  1093. if (!objv) {
  1094. PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb);
  1095. *(e->res) = NULL;
  1096. }
  1097. LEAVE_PYTHON
  1098. if (!objv)
  1099. goto done;
  1100. i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags);
  1101. ENTER_PYTHON
  1102. if (i == TCL_ERROR) {
  1103. *(e->res) = NULL;
  1104. *(e->exc_type) = NULL;
  1105. *(e->exc_tb) = NULL;
  1106. *(e->exc_value) = PyObject_CallFunction(
  1107. Tkinter_TclError, "s",
  1108. Tcl_GetStringResult(e->self->interp));
  1109. }
  1110. else {
  1111. *(e->res) = Tkapp_CallResult(e->self);
  1112. }
  1113. LEAVE_PYTHON
  1114. Tkapp_CallDeallocArgs(objv, objStore, objc);
  1115. done:
  1116. /* Wake up calling thread. */
  1117. Tcl_MutexLock(&call_mutex);
  1118. Tcl_ConditionNotify(e->done);
  1119. Tcl_MutexUnlock(&call_mutex);
  1120. return 1;
  1121. }
  1122. #endif
  1123. /* This is the main entry point for calling a Tcl command.
  1124. It supports three cases, with regard to threading:
  1125. 1. Tcl is not threaded: Must have the Tcl lock, then can invoke command in
  1126. the context of the calling thread.
  1127. 2. Tcl is threaded, caller of the command is in the interpreter thread:
  1128. Execute the command in the calling thread. Since the Tcl lock will
  1129. not be used, we can merge that with case 1.
  1130. 3. Tcl is threaded, caller is in a different thread: Must queue an event to
  1131. the interpreter thread. Allocation of Tcl objects needs to occur in the
  1132. interpreter thread, so we ship the PyObject* args to the target thread,
  1133. and perform processing there. */
  1134. static PyObject *
  1135. Tkapp_Call(PyObject *selfptr, PyObject *args)
  1136. {
  1137. Tcl_Obj *objStore[ARGSZ];
  1138. Tcl_Obj **objv = NULL;
  1139. int objc, i;
  1140. PyObject *res = NULL;
  1141. TkappObject *self = (TkappObject*)selfptr;
  1142. int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL;
  1143. /* If args is a single tuple, replace with contents of tuple */
  1144. if (1 == PyTuple_Size(args)){
  1145. PyObject* item = PyTuple_GetItem(args, 0);
  1146. if (PyTuple_Check(item))
  1147. args = item;
  1148. }
  1149. #ifdef WITH_THREAD
  1150. if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
  1151. /* We cannot call the command directly. Instead, we must
  1152. marshal the parameters to the interpreter thread. */
  1153. Tkapp_CallEvent *ev;
  1154. Tcl_Condition cond = NULL;
  1155. PyObject *exc_type, *exc_value, *exc_tb;
  1156. if (!WaitForMainloop(self))
  1157. return NULL;
  1158. ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent));
  1159. ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc;
  1160. ev->self = self;
  1161. ev->args = args;
  1162. ev->res = &res;
  1163. ev->exc_type = &exc_type;
  1164. ev->exc_value = &exc_value;
  1165. ev->exc_tb = &exc_tb;
  1166. ev->done = &cond;
  1167. Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex);
  1168. if (res == NULL) {
  1169. if (exc_type)
  1170. PyErr_Restore(exc_type, exc_value, exc_tb);
  1171. else
  1172. PyErr_SetObject(Tkinter_TclError, exc_value);
  1173. }
  1174. Tcl_ConditionFinalize(&cond);
  1175. }
  1176. else
  1177. #endif
  1178. {
  1179. objv = Tkapp_CallArgs(args, objStore, &objc);
  1180. if (!objv)
  1181. return NULL;
  1182. ENTER_TCL
  1183. i = Tcl_EvalObjv(self->interp, objc, objv, flags);
  1184. ENTER_OVERLAP
  1185. if (i == TCL_ERROR)
  1186. Tkinter_Error(selfptr);
  1187. else
  1188. res = Tkapp_CallResult(self);
  1189. LEAVE_OVERLAP_TCL
  1190. Tkapp_CallDeallocArgs(objv, objStore, objc);
  1191. }
  1192. return res;
  1193. }
  1194. static PyObject *
  1195. Tkapp_GlobalCall(PyObject *self, PyObject *args)
  1196. {
  1197. /* Could do the same here as for Tkapp_Call(), but this is not used
  1198. much, so I can't be bothered. Unfortunately Tcl doesn't export a
  1199. way for the user to do what all its Global* variants do (save and
  1200. reset the scope pointer, call the local version, restore the saved
  1201. scope pointer). */
  1202. char *cmd;
  1203. PyObject *res = NULL;
  1204. CHECK_TCL_APPARTMENT;
  1205. cmd = Merge(args);
  1206. if (cmd) {
  1207. int err;
  1208. ENTER_TCL
  1209. err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
  1210. ENTER_OVERLAP
  1211. if (err == TCL_ERROR)
  1212. res = Tkinter_Error(self);
  1213. else
  1214. res = PyString_FromString(Tkapp_Result(self));
  1215. LEAVE_OVERLAP_TCL
  1216. ckfree(cmd);
  1217. }
  1218. return res;
  1219. }
  1220. static PyObject *
  1221. Tkapp_Eval(PyObject *self, PyObject *args)
  1222. {
  1223. char *script;
  1224. PyObject *res = NULL;
  1225. int err;
  1226. if (!PyArg_ParseTuple(args, "s:eval", &script))
  1227. return NULL;
  1228. CHECK_TCL_APPARTMENT;
  1229. ENTER_TCL
  1230. err = Tcl_Eval(Tkapp_Interp(self), script);
  1231. ENTER_OVERLAP
  1232. if (err == TCL_ERROR)
  1233. res = Tkinter_Error(self);
  1234. else
  1235. res = PyString_FromString(Tkapp_Result(self));
  1236. LEAVE_OVERLAP_TCL
  1237. return res;
  1238. }
  1239. static PyObject *
  1240. Tkapp_GlobalEval(PyObject *self, PyObject *args)
  1241. {
  1242. char *script;
  1243. PyObject *res = NULL;
  1244. int err;
  1245. if (!PyArg_ParseTuple(args, "s:globaleval", &script))
  1246. return NULL;
  1247. CHECK_TCL_APPARTMENT;
  1248. ENTER_TCL
  1249. err = Tcl_GlobalEval(Tkapp_Interp(self), script);
  1250. ENTER_OVERLAP
  1251. if (err == TCL_ERROR)
  1252. res = Tkinter_Error(self);
  1253. else
  1254. res = PyString_FromString(Tkapp_Result(self));
  1255. LEAVE_OVERLAP_TCL
  1256. return res;
  1257. }
  1258. static PyObject *
  1259. Tkapp_EvalFile(PyObject *self, PyObject *args)
  1260. {
  1261. char *fileName;
  1262. PyObject *res = NULL;
  1263. int err;
  1264. if (!PyArg_ParseTuple(args, "s:evalfile", &fileName))
  1265. return NULL;
  1266. CHECK_TCL_APPARTMENT;
  1267. ENTER_TCL
  1268. err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
  1269. ENTER_OVERLAP
  1270. if (err == TCL_ERROR)
  1271. res = Tkinter_Error(self);
  1272. else
  1273. res = PyString_FromString(Tkapp_Result(self));
  1274. LEAVE_OVERLAP_TCL
  1275. return res;
  1276. }
  1277. static PyObject *
  1278. Tkapp_Record(PyObject *self, PyObject *args)
  1279. {
  1280. char *script;
  1281. PyObject *res = NULL;
  1282. int err;
  1283. if (!PyArg_ParseTuple(args, "s", &script))
  1284. return NULL;
  1285. CHECK_TCL_APPARTMENT;
  1286. ENTER_TCL
  1287. err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
  1288. ENTER_OVERLAP
  1289. if (err == TCL_ERROR)
  1290. res = Tkinter_Error(self);
  1291. else
  1292. res = PyString_FromString(Tkapp_Result(self));
  1293. LEAVE_OVERLAP_TCL
  1294. return res;
  1295. }
  1296. static PyObject *
  1297. Tkapp_AddErrorInfo(PyObject *self, PyObject *args)
  1298. {
  1299. char *msg;
  1300. if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg))
  1301. return NULL;
  1302. CHECK_TCL_APPARTMENT;
  1303. ENTER_TCL
  1304. Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
  1305. LEAVE_TCL
  1306. Py_INCREF(Py_None);
  1307. return Py_None;
  1308. }
  1309. /** Tcl Variable **/
  1310. typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags);
  1311. #ifdef WITH_THREAD
  1312. TCL_DECLARE_MUTEX(var_mutex)
  1313. typedef struct VarEvent {
  1314. Tcl_Event ev; /* must be first */
  1315. PyObject *self;
  1316. PyObject *args;
  1317. int flags;
  1318. EventFunc func;
  1319. PyObject **res;
  1320. PyObject **exc_type;
  1321. PyObject **exc_val;
  1322. Tcl_Condition *cond;
  1323. } VarEvent;
  1324. #endif
  1325. static int
  1326. varname_converter(PyObject *in, void *_out)
  1327. {
  1328. char **out = (char**)_out;
  1329. if (PyString_Check(in)) {
  1330. *out = PyString_AsString(in);
  1331. return 1;
  1332. }
  1333. if (PyTclObject_Check(in)) {
  1334. *out = PyTclObject_TclString(in);
  1335. return 1;
  1336. }
  1337. /* XXX: Should give diagnostics. */
  1338. return 0;
  1339. }
  1340. #ifdef WITH_THREAD
  1341. static void
  1342. var_perform(VarEvent *ev)
  1343. {
  1344. *(ev->res) = ev->func(ev->self, ev->args, ev->flags);
  1345. if (!*(ev->res)) {
  1346. PyObject *exc, *val, *tb;
  1347. PyErr_Fetch(&exc, &val, &tb);
  1348. PyErr_NormalizeException(&exc, &val, &tb);
  1349. *(ev->exc_type) = exc;
  1350. *(ev->exc_val) = val;
  1351. Py_DECREF(tb);
  1352. }
  1353. }
  1354. static int
  1355. var_proc(VarEvent* ev, int flags)
  1356. {
  1357. ENTER_PYTHON
  1358. var_perform(ev);
  1359. Tcl_MutexLock(&var_mutex);
  1360. Tcl_ConditionNotify(ev->cond);
  1361. Tcl_MutexUnlock(&var_mutex);
  1362. LEAVE_PYTHON
  1363. return 1;
  1364. }
  1365. #endif
  1366. static PyObject*
  1367. var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags)
  1368. {
  1369. #ifdef WITH_THREAD
  1370. TkappObject *self = (TkappObject*)selfptr;
  1371. if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
  1372. TkappObject *self = (TkappObject*)selfptr;
  1373. VarEvent *ev;
  1374. PyObject *res, *exc_type, *exc_val;
  1375. Tcl_Condition cond = NULL;
  1376. /* The current thread is not the interpreter thread. Marshal
  1377. the call to the interpreter thread, then wait for
  1378. completion. */
  1379. if (!WaitForMainloop(self))
  1380. return NULL;
  1381. ev = (VarEvent*)ckalloc(sizeof(VarEvent));
  1382. ev->self = selfptr;
  1383. ev->args = args;
  1384. ev->flags = flags;
  1385. ev->func = func;
  1386. ev->res = &res;
  1387. ev->exc_type = &exc_type;
  1388. ev->exc_val = &exc_val;
  1389. ev->cond = &cond;
  1390. ev->ev.proc = (Tcl_EventProc*)var_proc;
  1391. Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex);
  1392. Tcl_ConditionFinalize(&cond);
  1393. if (!res) {
  1394. PyErr_SetObject(exc_type, exc_val);
  1395. Py_DECREF(exc_type);
  1396. Py_DECREF(exc_val);
  1397. return NULL;
  1398. }
  1399. return res;
  1400. }
  1401. #endif
  1402. /* Tcl is not threaded, or this is the interpreter thread. */
  1403. return func(selfptr, args, flags);
  1404. }
  1405. static PyObject *
  1406. SetVar(PyObject *self, PyObject *args, int flags)
  1407. {
  1408. char *name1, *name2;
  1409. PyObject *newValue;
  1410. PyObject *res = NULL;
  1411. Tcl_Obj *newval, *ok;
  1412. if (PyArg_ParseTuple(args, "O&O:setvar",
  1413. varname_converter, &name1, &newValue)) {
  1414. /* XXX Acquire tcl lock??? */
  1415. newval = AsObj(newValue);
  1416. if (newval == NULL)
  1417. return NULL;
  1418. ENTER_TCL
  1419. ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL,
  1420. newval, flags);
  1421. ENTER_OVERLAP
  1422. if (!ok)
  1423. Tkinter_Error(self);
  1424. else {
  1425. res = Py_None;
  1426. Py_INCREF(res);
  1427. }
  1428. LEAVE_OVERLAP_TCL
  1429. }
  1430. else {
  1431. PyErr_Clear();
  1432. if (PyArg_ParseTuple(args, "ssO:setvar",
  1433. &name1, &name2, &newValue)) {
  1434. /* XXX must hold tcl lock already??? */
  1435. newval = AsObj(newValue);
  1436. ENTER_TCL
  1437. ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags);
  1438. ENTER_OVERLAP
  1439. if (!ok)
  1440. Tkinter_Error(self);
  1441. else {
  1442. res = Py_None;
  1443. Py_INCREF(res);
  1444. }
  1445. LEAVE_OVERLAP_TCL
  1446. }
  1447. else {
  1448. return NULL;
  1449. }
  1450. }
  1451. return res;
  1452. }
  1453. static PyObject *
  1454. Tkapp_SetVar(PyObject *self, PyObject *args)
  1455. {
  1456. return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG);
  1457. }
  1458. static PyObject *
  1459. Tkapp_GlobalSetVar(PyObject *self, PyObject *args)
  1460. {
  1461. return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  1462. }
  1463. static PyObject *
  1464. GetVar(PyObject *self, PyObject *args, int flags)
  1465. {
  1466. char *name1, *name2=NULL;
  1467. PyObject *res = NULL;
  1468. Tcl_Obj *tres;
  1469. if (!PyArg_ParseTuple(args, "O&|s:getvar",
  1470. varname_converter, &name1, &name2))
  1471. return NULL;
  1472. ENTER_TCL
  1473. tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags);
  1474. ENTER_OVERLAP
  1475. if (tres == NULL) {
  1476. PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
  1477. } else {
  1478. if (((TkappObject*)self)->wantobjects) {
  1479. res = FromObj(self, tres);
  1480. }
  1481. else {
  1482. res = PyString_FromString(Tcl_GetString(tres));
  1483. }
  1484. }
  1485. LEAVE_OVERLAP_TCL
  1486. return res;
  1487. }
  1488. static PyObject *
  1489. Tkapp_GetVar(PyObject *self, PyObject *args)
  1490. {
  1491. return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG);
  1492. }
  1493. static PyObject *
  1494. Tkapp_GlobalGetVar(PyObject *self, PyObject *args)
  1495. {
  1496. return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  1497. }
  1498. static PyObject *
  1499. UnsetVar(PyObject *self, PyObject *args, int flags)
  1500. {
  1501. char *name1, *name2=NULL;
  1502. int code;
  1503. PyObject *res = NULL;
  1504. if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2))
  1505. return NULL;
  1506. ENTER_TCL
  1507. code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
  1508. ENTER_OVERLAP
  1509. if (code == TCL_ERROR)
  1510. res = Tkinter_Error(self);
  1511. else {
  1512. Py_INCREF(Py_None);
  1513. res = Py_None;
  1514. }
  1515. LEAVE_OVERLAP_TCL
  1516. return res;
  1517. }
  1518. static PyObject *
  1519. Tkapp_UnsetVar(PyObject *self, PyObject *args)
  1520. {
  1521. return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG);
  1522. }
  1523. static PyObject *
  1524. Tkapp_GlobalUnsetVar(PyObject *self, PyObject *args)
  1525. {
  1526. return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  1527. }
  1528. /** Tcl to Python **/
  1529. static PyObject *
  1530. Tkapp_GetInt(PyObject *self, PyObject *args)
  1531. {
  1532. char *s;
  1533. int v;
  1534. if (PyTuple_Size(args) == 1) {
  1535. PyObject* o = PyTuple_GetItem(args, 0);
  1536. if (PyInt_Check(o)) {
  1537. Py_INCREF(o);
  1538. return o;
  1539. }
  1540. }
  1541. if (!PyArg_ParseTuple(args, "s:getint", &s))
  1542. return NULL;
  1543. if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  1544. return Tkinter_Error(self);
  1545. return Py_BuildValue("i", v);
  1546. }
  1547. static PyObject *
  1548. Tkapp_GetDouble(PyObject *self, PyObject *args)
  1549. {
  1550. char *s;
  1551. double v;
  1552. if (PyTuple_Size(args) == 1) {
  1553. PyObject *o = PyTuple_GetItem(args, 0);
  1554. if (PyFloat_Check(o)) {
  1555. Py_INCREF(o);
  1556. return o;
  1557. }
  1558. }
  1559. if (!PyArg_ParseTuple(args, "s:getdouble", &s))
  1560. return NULL;
  1561. if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  1562. return Tkinter_Error(self);
  1563. return Py_BuildValue("d", v);
  1564. }
  1565. static PyObject *
  1566. Tkapp_GetBoolean(PyObject *self, PyObject *args)
  1567. {
  1568. char *s;
  1569. int v;
  1570. if (PyTuple_Size(args) == 1) {
  1571. PyObject *o = PyTuple_GetItem(args, 0);
  1572. if (PyInt_Check(o)) {
  1573. Py_INCREF(o);
  1574. return o;
  1575. }
  1576. }
  1577. if (!PyArg_ParseTuple(args, "s:getboolean", &s))
  1578. return NULL;
  1579. if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  1580. return Tkinter_Error(self);
  1581. return PyBool_FromLong(v);
  1582. }
  1583. static PyObject *
  1584. Tkapp_ExprString(PyObject *self, PyObject *args)
  1585. {
  1586. char *s;
  1587. PyObject *res = NULL;
  1588. int retval;
  1589. if (!PyArg_ParseTuple(args, "s:exprstring", &s))
  1590. return NULL;
  1591. CHECK_TCL_APPARTMENT;
  1592. ENTER_TCL
  1593. retval = Tcl_ExprString(Tkapp_Interp(self), s);
  1594. ENTER_OVERLAP
  1595. if (retval == TCL_ERROR)
  1596. res = Tkinter_Error(self);
  1597. else
  1598. res = Py_BuildValue("s", Tkapp_Result(self));
  1599. LEAVE_OVERLAP_TCL
  1600. return res;
  1601. }
  1602. static PyObject *
  1603. Tkapp_ExprLong(PyObject *self, PyObject *args)
  1604. {
  1605. char *s;
  1606. PyObject *res = NULL;
  1607. int retval;
  1608. long v;
  1609. if (!PyArg_ParseTuple(args, "s:exprlong", &s))
  1610. return NULL;
  1611. CHECK_TCL_APPARTMENT;
  1612. ENTER_TCL
  1613. retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
  1614. ENTER_OVERLAP
  1615. if (retval == TCL_ERROR)
  1616. res = Tkinter_Error(self);
  1617. else
  1618. res = Py_BuildValue("l", v);
  1619. LEAVE_OVERLAP_TCL
  1620. return res;
  1621. }
  1622. static PyObject *
  1623. Tkapp_ExprDouble(PyObject *self, PyObject *args)
  1624. {
  1625. char *s;
  1626. PyObject *res = NULL;
  1627. double v;
  1628. int retval;
  1629. if (!PyArg_ParseTuple(args, "s:exprdouble", &s))
  1630. return NULL;
  1631. CHECK_TCL_APPARTMENT;
  1632. PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
  1633. ENTER_TCL
  1634. retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
  1635. ENTER_OVERLAP
  1636. PyFPE_END_PROTECT(retval)
  1637. if (retval == TCL_ERROR)
  1638. res = Tkinter_Error(self);
  1639. else
  1640. res = Py_BuildValue("d", v);
  1641. LEAVE_OVERLAP_TCL
  1642. return res;
  1643. }
  1644. static PyObject *
  1645. Tkapp_ExprBoolean(PyObject *self, PyObject *args)
  1646. {
  1647. char *s;
  1648. PyObject *res = NULL;
  1649. int retval;
  1650. int v;
  1651. if (!PyArg_ParseTuple(args, "s:exprboolean", &s))
  1652. return NULL;
  1653. CHECK_TCL_APPARTMENT;
  1654. ENTER_TCL
  1655. retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
  1656. ENTER_OVERLAP
  1657. if (retval == TCL_ERROR)
  1658. res = Tkinter_Error(self);
  1659. else
  1660. res = Py_BuildValue("i", v);
  1661. LEAVE_OVERLAP_TCL
  1662. return res;
  1663. }
  1664. static PyObject *
  1665. Tkapp_SplitList(PyObject *self, PyObject *args)
  1666. {
  1667. char *list;
  1668. int argc;
  1669. char **argv;
  1670. PyObject *v;
  1671. int i;
  1672. if (PyTuple_Size(args) == 1) {
  1673. v = PyTuple_GetItem(args, 0);
  1674. if (PyTuple_Check(v)) {
  1675. Py_INCREF(v);
  1676. return v;
  1677. }
  1678. }
  1679. if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list))
  1680. return NULL;
  1681. if (Tcl_SplitList(Tkapp_Interp(self), list,
  1682. &argc, &argv) == TCL_ERROR) {
  1683. PyMem_Free(list);
  1684. return Tkinter_Error(self);
  1685. }
  1686. if (!(v = PyTuple_New(argc)))
  1687. goto finally;
  1688. for (i = 0; i < argc; i++) {
  1689. PyObject *s = PyString_FromString(argv[i]);
  1690. if (!s || PyTuple_SetItem(v, i, s)) {
  1691. Py_DECREF(v);
  1692. v = NULL;
  1693. goto finally;
  1694. }
  1695. }
  1696. finally:
  1697. ckfree(FREECAST argv);
  1698. PyMem_Free(list);
  1699. return v;
  1700. }
  1701. static PyObject *
  1702. Tkapp_Split(PyObject *self, PyObject *args)
  1703. {
  1704. PyObject *v;
  1705. char *list;
  1706. if (PyTuple_Size(args) == 1) {
  1707. PyObject* o = PyTuple_GetItem(args, 0);
  1708. if (PyTuple_Check(o)) {
  1709. o = SplitObj(o);
  1710. return o;
  1711. }
  1712. }
  1713. if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list))
  1714. return NULL;
  1715. v = Split(list);
  1716. PyMem_Free(list);
  1717. return v;
  1718. }
  1719. static PyObject *
  1720. Tkapp_Merge(PyObject *self, PyObject *args)
  1721. {
  1722. char *s = Merge(args);
  1723. PyObject *res = NULL;
  1724. if (s) {
  1725. res = PyString_FromString(s);
  1726. ckfree(s);
  1727. }
  1728. return res;
  1729. }
  1730. /** Tcl Command **/
  1731. /* Client data struct */
  1732. typedef struct {
  1733. PyObject *self;
  1734. PyObject *func;
  1735. } PythonCmd_ClientData;
  1736. static int
  1737. PythonCmd_Error(Tcl_Interp *interp)
  1738. {
  1739. errorInCmd = 1;
  1740. PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1741. LEAVE_PYTHON
  1742. return TCL_ERROR;
  1743. }
  1744. /* This is the Tcl command that acts as a wrapper for Python
  1745. * function or method.
  1746. */
  1747. static int
  1748. PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])
  1749. {
  1750. PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
  1751. PyObject *func, *arg, *res;
  1752. int i, rv;
  1753. Tcl_Obj *obj_res;
  1754. ENTER_PYTHON
  1755. /* TBD: no error checking here since we know, via the
  1756. * Tkapp_CreateCommand() that the client data is a two-tuple
  1757. */
  1758. func = data->func;
  1759. /* Create argument list (argv1, ..., argvN) */
  1760. if (!(arg = PyTuple_New(argc - 1)))
  1761. return PythonCmd_Error(interp);
  1762. for (i = 0; i < (argc - 1); i++) {
  1763. PyObject *s = PyString_FromString(argv[i + 1]);
  1764. if (!s || PyTuple_SetItem(arg, i, s)) {
  1765. Py_DECREF(arg);
  1766. return PythonCmd_Error(interp);
  1767. }
  1768. }
  1769. res = PyEval_CallObject(func, arg);
  1770. Py_DECREF(arg);
  1771. if (res == NULL)
  1772. return PythonCmd_Error(interp);
  1773. obj_res = AsObj(res);
  1774. if (obj_res == NULL) {
  1775. Py_DECREF(res);
  1776. return PythonCmd_Error(interp);
  1777. }
  1778. else {
  1779. Tcl_SetObjResult(interp, obj_res);
  1780. rv = TCL_OK;
  1781. }
  1782. Py_DECREF(res);
  1783. LEAVE_PYTHON
  1784. return rv;
  1785. }
  1786. static void
  1787. PythonCmdDelete(ClientData clientData)
  1788. {
  1789. PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
  1790. ENTER_PYTHON
  1791. Py_XDECREF(data->self);
  1792. Py_XDECREF(data->func);
  1793. PyMem_DEL(data);
  1794. LEAVE_PYTHON
  1795. }
  1796. #ifdef WITH_THREAD
  1797. TCL_DECLARE_MUTEX(command_mutex)
  1798. typedef struct CommandEvent{
  1799. Tcl_Event ev;
  1800. Tcl_Interp* interp;
  1801. char *name;
  1802. int create;
  1803. int *status;
  1804. ClientData *data;
  1805. Tcl_Condition *done;
  1806. } CommandEvent;
  1807. static int
  1808. Tkapp_CommandProc(CommandEvent *ev, int flags)
  1809. {
  1810. if (ev->create)
  1811. *ev->status = Tcl_CreateCommand(
  1812. ev->interp, ev->name, PythonCmd,
  1813. ev->data, PythonCmdDelete) == NULL;
  1814. else
  1815. *ev->status = Tcl_DeleteCommand(ev->interp, ev->name);
  1816. Tcl_MutexLock(&command_mutex);
  1817. Tcl_ConditionNotify(ev->done);
  1818. Tcl_MutexUnlock(&command_mutex);
  1819. return 1;
  1820. }
  1821. #endif
  1822. static PyObject *
  1823. Tkapp_CreateCommand(PyObject *selfptr, PyObject *args)
  1824. {
  1825. TkappObject *self = (TkappObject*)selfptr;
  1826. PythonCmd_ClientData *data;
  1827. char *cmdName;
  1828. PyObject *func;
  1829. int err;
  1830. if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func))
  1831. return NULL;
  1832. if (!PyCallable_Check(func)) {
  1833. PyErr_SetString(PyExc_TypeError, "command not callable");
  1834. return NULL;
  1835. }
  1836. #ifdef WITH_THREAD
  1837. if (self->threaded && self->thread_id != Tcl_GetCurrentThread() &&
  1838. !WaitForMainloop(self))
  1839. return NULL;
  1840. #endif
  1841. data = PyMem_NEW(PythonCmd_ClientData, 1);
  1842. if (!data)
  1843. return PyErr_NoMemory();
  1844. Py_INCREF(self);
  1845. Py_INCREF(func);
  1846. data->self = selfptr;
  1847. data->func = func;
  1848. #ifdef WITH_THREAD
  1849. if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
  1850. Tcl_Condition cond = NULL;
  1851. CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
  1852. ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
  1853. ev->interp = self->interp;
  1854. ev->create = 1;
  1855. ev->name = cmdName;
  1856. ev->data = (ClientData)data;
  1857. ev->status = &err;
  1858. ev->done = &cond;
  1859. Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex);
  1860. Tcl_ConditionFinalize(&cond);
  1861. }
  1862. else
  1863. #endif
  1864. {
  1865. ENTER_TCL
  1866. err = Tcl_CreateCommand(
  1867. Tkapp_Interp(self), cmdName, PythonCmd,
  1868. (ClientData)data, PythonCmdDelete) == NULL;
  1869. LEAVE_TCL
  1870. }
  1871. if (err) {
  1872. PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
  1873. PyMem_DEL(data);
  1874. return NULL;
  1875. }
  1876. Py_INCREF(Py_None);
  1877. return Py_None;
  1878. }
  1879. static PyObject *
  1880. Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args)
  1881. {
  1882. TkappObject *self = (TkappObject*)selfptr;
  1883. char *cmdName;
  1884. int err;
  1885. if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
  1886. return NULL;
  1887. #ifdef WITH_THREAD
  1888. if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
  1889. Tcl_Condition cond = NULL;
  1890. CommandEvent *ev;
  1891. ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
  1892. ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
  1893. ev->interp = self->interp;
  1894. ev->create = 0;
  1895. ev->name = cmdName;
  1896. ev->status = &err;
  1897. ev->done = &cond;
  1898. Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond,
  1899. &command_mutex);
  1900. Tcl_ConditionFinalize(&cond);
  1901. }
  1902. else
  1903. #endif
  1904. {
  1905. ENTER_TCL
  1906. err = Tcl_DeleteCommand(self->interp, cmdName);
  1907. LEAVE_TCL
  1908. }
  1909. if (err == -1) {
  1910. PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
  1911. return NULL;
  1912. }
  1913. Py_INCREF(Py_None);
  1914. return Py_None;
  1915. }
  1916. #ifdef HAVE_CREATEFILEHANDLER
  1917. /** File Handler **/
  1918. typedef struct _fhcdata {
  1919. PyObject *func;
  1920. PyObject *file;
  1921. int id;
  1922. struct _fhcdata *next;
  1923. } FileHandler_ClientData;
  1924. static FileHandler_ClientData *HeadFHCD;
  1925. static FileHandler_ClientData *
  1926. NewFHCD(PyObject *func, PyObject *file, int id)
  1927. {
  1928. FileHandler_ClientData *p;
  1929. p = PyMem_NEW(FileHandler_ClientData, 1);
  1930. if (p != NULL) {
  1931. Py_XINCREF(func);
  1932. Py_XINCREF(file);
  1933. p->func = func;
  1934. p->file = file;
  1935. p->id = id;
  1936. p->next = HeadFHCD;
  1937. HeadFHCD = p;
  1938. }
  1939. return p;
  1940. }
  1941. static void
  1942. DeleteFHCD(int id)
  1943. {
  1944. FileHandler_ClientData *p, **pp;
  1945. pp = &HeadFHCD;
  1946. while ((p = *pp) != NULL) {
  1947. if (p->id == id) {
  1948. *pp = p->next;
  1949. Py_XDECREF(p->func);
  1950. Py_XDECREF(p->file);
  1951. PyMem_DEL(p);
  1952. }
  1953. else
  1954. pp = &p->next;
  1955. }
  1956. }
  1957. static void
  1958. FileHandler(ClientData clientData, int mask)
  1959. {
  1960. FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
  1961. PyObject *func, *file, *arg, *res;
  1962. ENTER_PYTHON
  1963. func = data->func;
  1964. file = data->file;
  1965. arg = Py_BuildValue("(Oi)", file, (long) mask);
  1966. res = PyEval_CallObject(func, arg);
  1967. Py_DECREF(arg);
  1968. if (res == NULL) {
  1969. errorInCmd = 1;
  1970. PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1971. }
  1972. Py_XDECREF(res);
  1973. LEAVE_PYTHON
  1974. }
  1975. static PyObject *
  1976. Tkapp_CreateFileHandler(PyObject *self, PyObject *args)
  1977. /* args is (file, mask, func) */
  1978. {
  1979. FileHandler_ClientData *data;
  1980. PyObject *file, *func;
  1981. int mask, tfile;
  1982. if (!self && Py_Py3kWarningFlag) {
  1983. if (PyErr_Warn(PyExc_DeprecationWarning,
  1984. "_tkinter.createfilehandler is gone in 3.x") < 0)
  1985. return NULL;
  1986. }
  1987. if (!PyArg_ParseTuple(args, "OiO:createfilehandler",
  1988. &file, &mask, &func))
  1989. return NULL;
  1990. #ifdef WITH_THREAD
  1991. if (!self && !tcl_lock) {
  1992. /* We don't have the Tcl lock since Tcl is threaded. */
  1993. PyErr_SetString(PyExc_RuntimeError,
  1994. "_tkinter.createfilehandler not supported "
  1995. "for threaded Tcl");
  1996. return NULL;
  1997. }
  1998. #endif
  1999. if (self) {
  2000. CHECK_TCL_APPARTMENT;
  2001. }
  2002. tfile = PyObject_AsFileDescriptor(file);
  2003. if (tfile < 0)
  2004. return NULL;
  2005. if (!PyCallable_Check(func)) {
  2006. PyErr_SetString(PyExc_TypeError, "bad argument list");
  2007. return NULL;
  2008. }
  2009. data = NewFHCD(func, file, tfile);
  2010. if (data == NULL)
  2011. return NULL;
  2012. /* Ought to check for null Tcl_File object... */
  2013. ENTER_TCL
  2014. Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
  2015. LEAVE_TCL
  2016. Py_INCREF(Py_None);
  2017. return Py_None;
  2018. }
  2019. static PyObject *
  2020. Tkapp_DeleteFileHandler(PyObject *self, PyObject *args)
  2021. {
  2022. PyObject *file;
  2023. int tfile;
  2024. if (!self && Py_Py3kWarningFlag) {
  2025. if (PyErr_Warn(PyExc_DeprecationWarning,
  2026. "_tkinter.deletefilehandler is gone in 3.x") < 0)
  2027. return NULL;
  2028. }
  2029. if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
  2030. return NULL;
  2031. #ifdef WITH_THREAD
  2032. if (!self && !tcl_lock) {
  2033. /* We don't have the Tcl lock since Tcl is threaded. */
  2034. PyErr_SetString(PyExc_RuntimeError,
  2035. "_tkinter.deletefilehandler not supported "
  2036. "for threaded Tcl");
  2037. return NULL;
  2038. }
  2039. #endif
  2040. if (self) {
  2041. CHECK_TCL_APPARTMENT;
  2042. }
  2043. tfile = PyObject_AsFileDescriptor(file);
  2044. if (tfile < 0)
  2045. return NULL;
  2046. DeleteFHCD(tfile);
  2047. /* Ought to check for null Tcl_File object... */
  2048. ENTER_TCL
  2049. Tcl_DeleteFileHandler(tfile);
  2050. LEAVE_TCL
  2051. Py_INCREF(Py_None);
  2052. return Py_None;
  2053. }
  2054. #endif /* HAVE_CREATEFILEHANDLER */
  2055. /**** Tktt Object (timer token) ****/
  2056. static PyTypeObject Tktt_Type;
  2057. typedef struct {
  2058. PyObject_HEAD
  2059. Tcl_TimerToken token;
  2060. PyObject *func;
  2061. } TkttObject;
  2062. static PyObject *
  2063. Tktt_DeleteTimerHandler(PyObject *self, PyObject *args)
  2064. {
  2065. TkttObject *v = (TkttObject *)self;
  2066. PyObject *func = v->func;
  2067. if (!PyArg_ParseTuple(args, ":deletetimerhandler"))
  2068. return NULL;
  2069. if (v->token != NULL) {
  2070. Tcl_DeleteTimerHandler(v->token);
  2071. v->token = NULL;
  2072. }
  2073. if (func != NULL) {
  2074. v->func = NULL;
  2075. Py_DECREF(func);
  2076. Py_DECREF(v); /* See Tktt_New() */
  2077. }
  2078. Py_INCREF(Py_None);
  2079. return Py_None;
  2080. }
  2081. static PyMethodDef Tktt_methods[] =
  2082. {
  2083. {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS},
  2084. {NULL, NULL}
  2085. };
  2086. static TkttObject *
  2087. Tktt_New(PyObject *func)
  2088. {
  2089. TkttObject *v;
  2090. v = PyObject_New(TkttObject, &Tktt_Type);
  2091. if (v == NULL)
  2092. return NULL;
  2093. Py_INCREF(func);
  2094. v->token = NULL;
  2095. v->func = func;
  2096. /* Extra reference, deleted when called or when handler is deleted */
  2097. Py_INCREF(v);
  2098. return v;
  2099. }
  2100. static void
  2101. Tktt_Dealloc(PyObject *self)
  2102. {
  2103. TkttObject *v = (TkttObject *)self;
  2104. PyObject *func = v->func;
  2105. Py_XDECREF(func);
  2106. PyObject_Del(self);
  2107. }
  2108. static PyObject *
  2109. Tktt_Repr(PyObject *self)
  2110. {
  2111. TkttObject *v = (TkttObject *)self;
  2112. char buf[100];
  2113. PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
  2114. v->func == NULL ? ", handler deleted" : "");
  2115. return PyString_FromString(buf);
  2116. }
  2117. static PyObject *
  2118. Tktt_GetAttr(PyObject *self, char *name)
  2119. {
  2120. return Py_FindMethod(Tktt_methods, self, name);
  2121. }
  2122. static PyTypeObject Tktt_Type =
  2123. {
  2124. PyVarObject_HEAD_INIT(NULL, 0)
  2125. "tktimertoken", /*tp_name */
  2126. sizeof(TkttObject), /*tp_basicsize */
  2127. 0, /*tp_itemsize */
  2128. Tktt_Dealloc, /*tp_dealloc */
  2129. 0, /*tp_print */
  2130. Tktt_GetAttr, /*tp_getattr */
  2131. 0, /*tp_setattr */
  2132. 0, /*tp_compare */
  2133. Tktt_Repr, /*tp_repr */
  2134. 0, /*tp_as_number */
  2135. 0, /*tp_as_sequence */
  2136. 0, /*tp_as_mapping */
  2137. 0, /*tp_hash */
  2138. };
  2139. /** Timer Handler **/
  2140. static void
  2141. TimerHandler(ClientData clientData)
  2142. {
  2143. TkttObject *v = (TkttObject *)clientData;
  2144. PyObject *func = v->func;
  2145. PyObject *res;
  2146. if (func == NULL)
  2147. return;
  2148. v->func = NULL;
  2149. ENTER_PYTHON
  2150. res = PyEval_CallObject(func, NULL);
  2151. Py_DECREF(func);
  2152. Py_DECREF(v); /* See Tktt_New() */
  2153. if (res == NULL) {
  2154. errorInCmd = 1;
  2155. PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  2156. }
  2157. else
  2158. Py_DECREF(res);
  2159. LEAVE_PYTHON
  2160. }
  2161. static PyObject *
  2162. Tkapp_CreateTimerHandler(PyObject *self, PyObject *args)
  2163. {
  2164. int milliseconds;
  2165. PyObject *func;
  2166. TkttObject *v;
  2167. if (!self && Py_Py3kWarningFlag) {
  2168. if (PyErr_Warn(PyExc_DeprecationWarning,
  2169. "_tkinter.createtimerhandler is gone in 3.x") < 0)
  2170. return NULL;
  2171. }
  2172. if (!PyArg_ParseTuple(args, "iO:createtimerhandler",
  2173. &milliseconds, &func))
  2174. return NULL;
  2175. if (!PyCallable_Check(func)) {
  2176. PyErr_SetString(PyExc_TypeError, "bad argument list");
  2177. return NULL;
  2178. }
  2179. #ifdef WITH_THREAD
  2180. if (!self && !tcl_lock) {
  2181. /* We don't have the Tcl lock since Tcl is threaded. */
  2182. PyErr_SetString(PyExc_RuntimeError,
  2183. "_tkinter.createtimerhandler not supported "
  2184. "for threaded Tcl");
  2185. return NULL;
  2186. }
  2187. #endif
  2188. if (self) {
  2189. CHECK_TCL_APPARTMENT;
  2190. }
  2191. v = Tktt_New(func);
  2192. if (v) {
  2193. v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
  2194. (ClientData)v);
  2195. }
  2196. return (PyObject *) v;
  2197. }
  2198. /** Event Loop **/
  2199. static PyObject *
  2200. Tkapp_MainLoop(PyObject *selfptr, PyObject *args)
  2201. {
  2202. int threshold = 0;
  2203. TkappObject *self = (TkappObject*)selfptr;
  2204. #ifdef WITH_THREAD
  2205. PyThreadState *tstate = PyThreadState_Get();
  2206. #endif
  2207. if (!self && Py_Py3kWarningFlag) {
  2208. if (PyErr_Warn(PyExc_DeprecationWarning,
  2209. "_tkinter.mainloop is gone in 3.x") < 0)
  2210. return NULL;
  2211. }
  2212. if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
  2213. return NULL;
  2214. #ifdef WITH_THREAD
  2215. if (!self && !tcl_lock) {
  2216. /* We don't have the Tcl lock since Tcl is threaded. */
  2217. PyErr_SetString(PyExc_RuntimeError,
  2218. "_tkinter.mainloop not supported "
  2219. "for threaded Tcl");
  2220. return NULL;
  2221. }
  2222. #endif
  2223. if (self) {
  2224. CHECK_TCL_APPARTMENT;
  2225. self->dispatching = 1;
  2226. }
  2227. quitMainLoop = 0;
  2228. while (Tk_GetNumMainWindows() > threshold &&
  2229. !quitMainLoop &&
  2230. !errorInCmd)
  2231. {
  2232. int result;
  2233. #ifdef WITH_THREAD
  2234. if (self && self->threaded) {
  2235. /* Allow other Python threads to run. */
  2236. ENTER_TCL
  2237. result = Tcl_DoOneEvent(0);
  2238. LEAVE_TCL
  2239. }
  2240. else {
  2241. Py_BEGIN_ALLOW_THREADS
  2242. if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
  2243. tcl_tstate = tstate;
  2244. result = Tcl_DoOneEvent(TCL_DONT_WAIT);
  2245. tcl_tstate = NULL;
  2246. if(tcl_lock)PyThread_release_lock(tcl_lock);
  2247. if (result == 0)
  2248. Sleep(Tkinter_busywaitinterval);
  2249. Py_END_ALLOW_THREADS
  2250. }
  2251. #else
  2252. result = Tcl_DoOneEvent(0);
  2253. #endif
  2254. if (PyErr_CheckSignals() != 0) {
  2255. if (self)
  2256. self->dispatching = 0;
  2257. return NULL;
  2258. }
  2259. if (result < 0)
  2260. break;
  2261. }
  2262. if (self)
  2263. self->dispatching = 0;
  2264. quitMainLoop = 0;
  2265. if (errorInCmd) {
  2266. errorInCmd = 0;
  2267. PyErr_Restore(excInCmd, valInCmd, trbInCmd);
  2268. excInCmd = valInCmd = trbInCmd = NULL;
  2269. return NULL;
  2270. }
  2271. Py_INCREF(Py_None);
  2272. return Py_None;
  2273. }
  2274. static PyObject *
  2275. Tkapp_DoOneEvent(PyObject *self, PyObject *args)
  2276. {
  2277. int flags = 0;
  2278. int rv;
  2279. if (!self && Py_Py3kWarningFlag) {
  2280. if (PyErr_Warn(PyExc_DeprecationWarning,
  2281. "_tkinter.dooneevent is gone in 3.x") < 0)
  2282. return NULL;
  2283. }
  2284. if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
  2285. return NULL;
  2286. ENTER_TCL
  2287. rv = Tcl_DoOneEvent(flags);
  2288. LEAVE_TCL
  2289. return Py_BuildValue("i", rv);
  2290. }
  2291. static PyObject *
  2292. Tkapp_Quit(PyObject *self, PyObject *args)
  2293. {
  2294. if (!self && Py_Py3kWarningFlag) {
  2295. if (PyErr_Warn(PyExc_DeprecationWarning,
  2296. "_tkinter.quit is gone in 3.x") < 0)
  2297. return NULL;
  2298. }
  2299. if (!PyArg_ParseTuple(args, ":quit"))
  2300. return NULL;
  2301. quitMainLoop = 1;
  2302. Py_INCREF(Py_None);
  2303. return Py_None;
  2304. }
  2305. static PyObject *
  2306. Tkapp_InterpAddr(PyObject *self, PyObject *args)
  2307. {
  2308. if (!PyArg_ParseTuple(args, ":interpaddr"))
  2309. return NULL;
  2310. return PyInt_FromLong((long)Tkapp_Interp(self));
  2311. }
  2312. static PyObject *
  2313. Tkapp_TkInit(PyObject *self, PyObject *args)
  2314. {
  2315. Tcl_Interp *interp = Tkapp_Interp(self);
  2316. const char * _tk_exists = NULL;
  2317. int err;
  2318. #ifdef TKINTER_PROTECT_LOADTK
  2319. /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the
  2320. * first call failed.
  2321. * To avoid the deadlock, we just refuse the second call through
  2322. * a static variable.
  2323. */
  2324. if (tk_load_failed) {
  2325. PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG);
  2326. return NULL;
  2327. }
  2328. #endif
  2329. /* We want to guard against calling Tk_Init() multiple times */
  2330. CHECK_TCL_APPARTMENT;
  2331. ENTER_TCL
  2332. err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version");
  2333. ENTER_OVERLAP
  2334. if (err == TCL_ERROR) {
  2335. /* This sets an exception, but we cannot return right
  2336. away because we need to exit the overlap first. */
  2337. Tkinter_Error(self);
  2338. } else {
  2339. _tk_exists = Tkapp_Result(self);
  2340. }
  2341. LEAVE_OVERLAP_TCL
  2342. if (err == TCL_ERROR) {
  2343. return NULL;
  2344. }
  2345. if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) {
  2346. if (Tk_Init(interp) == TCL_ERROR) {
  2347. PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
  2348. #ifdef TKINTER_PROTECT_LOADTK
  2349. tk_load_failed = 1;
  2350. #endif
  2351. return NULL;
  2352. }
  2353. }
  2354. Py_INCREF(Py_None);
  2355. return Py_None;
  2356. }
  2357. static PyObject *
  2358. Tkapp_WantObjects(PyObject *self, PyObject *args)
  2359. {
  2360. int wantobjects = -1;
  2361. if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects))
  2362. return NULL;
  2363. if (wantobjects == -1)
  2364. return PyBool_FromLong(((TkappObject*)self)->wantobjects);
  2365. ((TkappObject*)self)->wantobjects = wantobjects;
  2366. Py_INCREF(Py_None);
  2367. return Py_None;
  2368. }
  2369. static PyObject *
  2370. Tkapp_WillDispatch(PyObject *self, PyObject *args)
  2371. {
  2372. ((TkappObject*)self)->dispatching = 1;
  2373. Py_INCREF(Py_None);
  2374. return Py_None;
  2375. }
  2376. /**** Tkapp Method List ****/
  2377. static PyMethodDef Tkapp_methods[] =
  2378. {
  2379. {"willdispatch", Tkapp_WillDispatch, METH_NOARGS},
  2380. {"wantobjects", Tkapp_WantObjects, METH_VARARGS},
  2381. {"call", Tkapp_Call, METH_VARARGS},
  2382. {"globalcall", Tkapp_GlobalCall, METH_VARARGS},
  2383. {"eval", Tkapp_Eval, METH_VARARGS},
  2384. {"globaleval", Tkapp_GlobalEval, METH_VARARGS},
  2385. {"evalfile", Tkapp_EvalFile, METH_VARARGS},
  2386. {"record", Tkapp_Record, METH_VARARGS},
  2387. {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS},
  2388. {"setvar", Tkapp_SetVar, METH_VARARGS},
  2389. {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS},
  2390. {"getvar", Tkapp_GetVar, METH_VARARGS},
  2391. {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS},
  2392. {"unsetvar", Tkapp_UnsetVar, METH_VARARGS},
  2393. {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS},
  2394. {"getint", Tkapp_GetInt, METH_VARARGS},
  2395. {"getdouble", Tkapp_GetDouble, METH_VARARGS},
  2396. {"getboolean", Tkapp_GetBoolean, METH_VARARGS},
  2397. {"exprstring", Tkapp_ExprString, METH_VARARGS},
  2398. {"exprlong", Tkapp_ExprLong, METH_VARARGS},
  2399. {"exprdouble", Tkapp_ExprDouble, METH_VARARGS},
  2400. {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS},
  2401. {"splitlist", Tkapp_SplitList, METH_VARARGS},
  2402. {"split", Tkapp_Split, METH_VARARGS},
  2403. {"merge", Tkapp_Merge, METH_VARARGS},
  2404. {"createcommand", Tkapp_CreateCommand, METH_VARARGS},
  2405. {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS},
  2406. #ifdef HAVE_CREATEFILEHANDLER
  2407. {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
  2408. {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
  2409. #endif
  2410. {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
  2411. {"mainloop", Tkapp_MainLoop, METH_VARARGS},
  2412. {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
  2413. {"quit", Tkapp_Quit, METH_VARARGS},
  2414. {"interpaddr", Tkapp_InterpAddr, METH_VARARGS},
  2415. {"loadtk", Tkapp_TkInit, METH_NOARGS},
  2416. {NULL, NULL}
  2417. };
  2418. /**** Tkapp Type Methods ****/
  2419. static void
  2420. Tkapp_Dealloc(PyObject *self)
  2421. {
  2422. /*CHECK_TCL_APPARTMENT;*/
  2423. ENTER_TCL
  2424. Tcl_DeleteInterp(Tkapp_Interp(self));
  2425. LEAVE_TCL
  2426. PyObject_Del(self);
  2427. DisableEventHook();
  2428. }
  2429. static PyObject *
  2430. Tkapp_GetAttr(PyObject *self, char *name)
  2431. {
  2432. return Py_FindMethod(Tkapp_methods, self, name);
  2433. }
  2434. static PyTypeObject Tkapp_Type =
  2435. {
  2436. PyVarObject_HEAD_INIT(NULL, 0)
  2437. "tkapp", /*tp_name */
  2438. sizeof(TkappObject), /*tp_basicsize */
  2439. 0, /*tp_itemsize */
  2440. Tkapp_Dealloc, /*tp_dealloc */
  2441. 0, /*tp_print */
  2442. Tkapp_GetAttr, /*tp_getattr */
  2443. 0, /*tp_setattr */
  2444. 0, /*tp_compare */
  2445. 0, /*tp_repr */
  2446. 0, /*tp_as_number */
  2447. 0, /*tp_as_sequence */
  2448. 0, /*tp_as_mapping */
  2449. 0, /*tp_hash */
  2450. };
  2451. /**** Tkinter Module ****/
  2452. typedef struct {
  2453. PyObject* tuple;
  2454. int size; /* current size */
  2455. int maxsize; /* allocated size */
  2456. } FlattenContext;
  2457. static int
  2458. _bump(FlattenContext* context, int size)
  2459. {
  2460. /* expand tuple to hold (at least) size new items.
  2461. return true if successful, false if an exception was raised */
  2462. int maxsize = context->maxsize * 2;
  2463. if (maxsize < context->size + size)
  2464. maxsize = context->size + size;
  2465. context->maxsize = maxsize;
  2466. return _PyTuple_Resize(&context->tuple, maxsize) >= 0;
  2467. }
  2468. static int
  2469. _flatten1(FlattenContext* context, PyObject* item, int depth)
  2470. {
  2471. /* add tuple or list to argument tuple (recursively) */
  2472. int i, size;
  2473. if (depth > 1000) {
  2474. PyErr_SetString(PyExc_ValueError,
  2475. "nesting too deep in _flatten");
  2476. return 0;
  2477. } else if (PyList_Check(item)) {
  2478. size = PyList_GET_SIZE(item);
  2479. /* preallocate (assume no nesting) */
  2480. if (context->size + size > context->maxsize &&
  2481. !_bump(context, size))
  2482. return 0;
  2483. /* copy items to output tuple */
  2484. for (i = 0; i < size; i++) {
  2485. PyObject *o = PyList_GET_ITEM(item, i);
  2486. if (PyList_Check(o) || PyTuple_Check(o)) {
  2487. if (!_flatten1(context, o, depth + 1))
  2488. return 0;
  2489. } else if (o != Py_None) {
  2490. if (context->size + 1 > context->maxsize &&
  2491. !_bump(context, 1))
  2492. return 0;
  2493. Py_INCREF(o);
  2494. PyTuple_SET_ITEM(context->tuple,
  2495. context->size++, o);
  2496. }
  2497. }
  2498. } else if (PyTuple_Check(item)) {
  2499. /* same, for tuples */
  2500. size = PyTuple_GET_SIZE(item);
  2501. if (context->size + size > context->maxsize &&
  2502. !_bump(context, size))
  2503. return 0;
  2504. for (i = 0; i < size; i++) {
  2505. PyObject *o = PyTuple_GET_ITEM(item, i);
  2506. if (PyList_Check(o) || PyTuple_Check(o)) {
  2507. if (!_flatten1(context, o, depth + 1))
  2508. return 0;
  2509. } else if (o != Py_None) {
  2510. if (context->size + 1 > context->maxsize &&
  2511. !_bump(context, 1))
  2512. return 0;
  2513. Py_INCREF(o);
  2514. PyTuple_SET_ITEM(context->tuple,
  2515. context->size++, o);
  2516. }
  2517. }
  2518. } else {
  2519. PyErr_SetString(PyExc_TypeError, "argument must be sequence");
  2520. return 0;
  2521. }
  2522. return 1;
  2523. }
  2524. static PyObject *
  2525. Tkinter_Flatten(PyObject* self, PyObject* args)
  2526. {
  2527. FlattenContext context;
  2528. PyObject* item;
  2529. if (!PyArg_ParseTuple(args, "O:_flatten", &item))
  2530. return NULL;
  2531. context.maxsize = PySequence_Size(item);
  2532. if (context.maxsize < 0)
  2533. return NULL;
  2534. if (context.maxsize == 0)
  2535. return PyTuple_New(0);
  2536. context.tuple = PyTuple_New(context.maxsize);
  2537. if (!context.tuple)
  2538. return NULL;
  2539. context.size = 0;
  2540. if (!_flatten1(&context, item,0))
  2541. return NULL;
  2542. if (_PyTuple_Resize(&context.tuple, context.size))
  2543. return NULL;
  2544. return context.tuple;
  2545. }
  2546. static PyObject *
  2547. Tkinter_Create(PyObject *self, PyObject *args)
  2548. {
  2549. char *screenName = NULL;
  2550. char *baseName = NULL;
  2551. char *className = NULL;
  2552. int interactive = 0;
  2553. int wantobjects = 0;
  2554. int wantTk = 1; /* If false, then Tk_Init() doesn't get called */
  2555. int sync = 0; /* pass -sync to wish */
  2556. char *use = NULL; /* pass -use to wish */
  2557. baseName = strrchr(Py_GetProgramName(), '/');
  2558. if (baseName != NULL)
  2559. baseName++;
  2560. else
  2561. baseName = Py_GetProgramName();
  2562. className = "Tk";
  2563. if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
  2564. &screenName, &baseName, &className,
  2565. &interactive, &wantobjects, &wantTk,
  2566. &sync, &use))
  2567. return NULL;
  2568. return (PyObject *) Tkapp_New(screenName, baseName, className,
  2569. interactive, wantobjects, wantTk,
  2570. sync, use);
  2571. }
  2572. static PyObject *
  2573. Tkinter_setbusywaitinterval(PyObject *self, PyObject *args)
  2574. {
  2575. int new_val;
  2576. if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val))
  2577. return NULL;
  2578. if (new_val < 0) {
  2579. PyErr_SetString(PyExc_ValueError,
  2580. "busywaitinterval must be >= 0");
  2581. return NULL;
  2582. }
  2583. Tkinter_busywaitinterval = new_val;
  2584. Py_INCREF(Py_None);
  2585. return Py_None;
  2586. }
  2587. static char setbusywaitinterval_doc[] =
  2588. "setbusywaitinterval(n) -> None\n\
  2589. \n\
  2590. Set the busy-wait interval in milliseconds between successive\n\
  2591. calls to Tcl_DoOneEvent in a threaded Python interpreter.\n\
  2592. It should be set to a divisor of the maximum time between\n\
  2593. frames in an animation.";
  2594. static PyObject *
  2595. Tkinter_getbusywaitinterval(PyObject *self, PyObject *args)
  2596. {
  2597. return PyInt_FromLong(Tkinter_busywaitinterval);
  2598. }
  2599. static char getbusywaitinterval_doc[] =
  2600. "getbusywaitinterval() -> int\n\
  2601. \n\
  2602. Return the current busy-wait interval between successive\n\
  2603. calls to Tcl_DoOneEvent in a threaded Python interpreter.";
  2604. static PyMethodDef moduleMethods[] =
  2605. {
  2606. {"_flatten", Tkinter_Flatten, METH_VARARGS},
  2607. {"create", Tkinter_Create, METH_VARARGS},
  2608. #ifdef HAVE_CREATEFILEHANDLER
  2609. {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
  2610. {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
  2611. #endif
  2612. {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
  2613. {"mainloop", Tkapp_MainLoop, METH_VARARGS},
  2614. {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
  2615. {"quit", Tkapp_Quit, METH_VARARGS},
  2616. {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
  2617. setbusywaitinterval_doc},
  2618. {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
  2619. METH_NOARGS, getbusywaitinterval_doc},
  2620. {NULL, NULL}
  2621. };
  2622. #ifdef WAIT_FOR_STDIN
  2623. static int stdin_ready = 0;
  2624. #ifndef MS_WINDOWS
  2625. static void
  2626. MyFileProc(void *clientData, int mask)
  2627. {
  2628. stdin_ready = 1;
  2629. }
  2630. #endif
  2631. #ifdef WITH_THREAD
  2632. static PyThreadState *event_tstate = NULL;
  2633. #endif
  2634. static int
  2635. EventHook(void)
  2636. {
  2637. #ifndef MS_WINDOWS
  2638. int tfile;
  2639. #endif
  2640. #ifdef WITH_THREAD
  2641. PyEval_RestoreThread(event_tstate);
  2642. #endif
  2643. stdin_ready = 0;
  2644. errorInCmd = 0;
  2645. #ifndef MS_WINDOWS
  2646. tfile = fileno(stdin);
  2647. Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
  2648. #endif
  2649. while (!errorInCmd && !stdin_ready) {
  2650. int result;
  2651. #ifdef MS_WINDOWS
  2652. if (_kbhit()) {
  2653. stdin_ready = 1;
  2654. break;
  2655. }
  2656. #endif
  2657. #if defined(WITH_THREAD) || defined(MS_WINDOWS)
  2658. Py_BEGIN_ALLOW_THREADS
  2659. if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
  2660. tcl_tstate = event_tstate;
  2661. result = Tcl_DoOneEvent(TCL_DONT_WAIT);
  2662. tcl_tstate = NULL;
  2663. if(tcl_lock)PyThread_release_lock(tcl_lock);
  2664. if (result == 0)
  2665. Sleep(Tkinter_busywaitinterval);
  2666. Py_END_ALLOW_THREADS
  2667. #else
  2668. result = Tcl_DoOneEvent(0);
  2669. #endif
  2670. if (result < 0)
  2671. break;
  2672. }
  2673. #ifndef MS_WINDOWS
  2674. Tcl_DeleteFileHandler(tfile);
  2675. #endif
  2676. if (errorInCmd) {
  2677. errorInCmd = 0;
  2678. PyErr_Restore(excInCmd, valInCmd, trbInCmd);
  2679. excInCmd = valInCmd = trbInCmd = NULL;
  2680. PyErr_Print();
  2681. }
  2682. #ifdef WITH_THREAD
  2683. PyEval_SaveThread();
  2684. #endif
  2685. return 0;
  2686. }
  2687. #endif
  2688. static void
  2689. EnableEventHook(void)
  2690. {
  2691. #ifdef WAIT_FOR_STDIN
  2692. if (PyOS_InputHook == NULL) {
  2693. #ifdef WITH_THREAD
  2694. event_tstate = PyThreadState_Get();
  2695. #endif
  2696. PyOS_InputHook = EventHook;
  2697. }
  2698. #endif
  2699. }
  2700. static void
  2701. DisableEventHook(void)
  2702. {
  2703. #ifdef WAIT_FOR_STDIN
  2704. if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
  2705. PyOS_InputHook = NULL;
  2706. }
  2707. #endif
  2708. }
  2709. /* all errors will be checked in one fell swoop in init_tkinter() */
  2710. static void
  2711. ins_long(PyObject *d, char *name, long val)
  2712. {
  2713. PyObject *v = PyInt_FromLong(val);
  2714. if (v) {
  2715. PyDict_SetItemString(d, name, v);
  2716. Py_DECREF(v);
  2717. }
  2718. }
  2719. static void
  2720. ins_string(PyObject *d, char *name, char *val)
  2721. {
  2722. PyObject *v = PyString_FromString(val);
  2723. if (v) {
  2724. PyDict_SetItemString(d, name, v);
  2725. Py_DECREF(v);
  2726. }
  2727. }
  2728. PyMODINIT_FUNC
  2729. init_tkinter(void)
  2730. {
  2731. PyObject *m, *d;
  2732. Py_TYPE(&Tkapp_Type) = &PyType_Type;
  2733. #ifdef WITH_THREAD
  2734. tcl_lock = PyThread_allocate_lock();
  2735. #endif
  2736. m = Py_InitModule("_tkinter", moduleMethods);
  2737. if (m == NULL)
  2738. return;
  2739. d = PyModule_GetDict(m);
  2740. Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL);
  2741. PyDict_SetItemString(d, "TclError", Tkinter_TclError);
  2742. ins_long(d, "READABLE", TCL_READABLE);
  2743. ins_long(d, "WRITABLE", TCL_WRITABLE);
  2744. ins_long(d, "EXCEPTION", TCL_EXCEPTION);
  2745. ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
  2746. ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
  2747. ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
  2748. ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
  2749. ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
  2750. ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
  2751. ins_string(d, "TK_VERSION", TK_VERSION);
  2752. ins_string(d, "TCL_VERSION", TCL_VERSION);
  2753. PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
  2754. Py_TYPE(&Tktt_Type) = &PyType_Type;
  2755. PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
  2756. Py_TYPE(&PyTclObject_Type) = &PyType_Type;
  2757. PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type);
  2758. #ifdef TK_AQUA
  2759. /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems
  2760. * start waking up. Note that Tcl_FindExecutable will do this, this
  2761. * code must be above it! The original warning from
  2762. * tkMacOSXAppInit.c is copied below.
  2763. *
  2764. * NB - You have to swap in the Tk Notifier BEFORE you start up the
  2765. * Tcl interpreter for now. It probably should work to do this
  2766. * in the other order, but for now it doesn't seem to.
  2767. *
  2768. */
  2769. Tk_MacOSXSetupTkNotifier();
  2770. #endif
  2771. /* This helps the dynamic loader; in Unicode aware Tcl versions
  2772. it also helps Tcl find its encodings. */
  2773. Tcl_FindExecutable(Py_GetProgramName());
  2774. if (PyErr_Occurred())
  2775. return;
  2776. #if 0
  2777. /* This was not a good idea; through <Destroy> bindings,
  2778. Tcl_Finalize() may invoke Python code but at that point the
  2779. interpreter and thread state have already been destroyed! */
  2780. Py_AtExit(Tcl_Finalize);
  2781. #endif
  2782. }