Debian Codegraph @

lib_pypy/_tkinter/app.py

raw symbols SCIP
1 # The TkApp class.
2
3 from .tklib_cffi import ffi as tkffi, lib as tklib
4 from . import TclError
5 from .tclobj import (Tcl_Obj, FromObj, FromTclString, AsObj, TypeCache,
6 FromBignumObj, FromWideIntObj)
7
8 import contextlib
9 import sys
10 import threading
11 import time
12 import warnings
13
14
15 class _DummyLock(object):
16 "A lock-like object that does not do anything"
17 def acquire(self):
18 pass
19 def release(self):
20 pass
21 def __enter__(self):
22 pass
23 def __exit__(self, *exc):
24 pass
25
26
27 def varname_converter(input):
28 if isinstance(input, Tcl_Obj):
29 input = input.string
30 if isinstance(input, str):
31 input = input.encode('utf-8')
32 if b'\0' in input:
33 raise ValueError("NUL character in string")
34 return input
35
36
37 def Tcl_AppInit(app):
38 # For portable builds, try to load a local version of the libraries
39 from os.path import join, dirname, exists, sep
40 if sys.platform == 'win32':
41 lib_path = join(dirname(dirname(dirname(__file__))), 'tcl')
42 tcl_path = join(lib_path, 'tcl8.6')
43 tk_path = join(lib_path, 'tk8.6')
44 tcl_path = tcl_path.replace(sep, '/')
45 tk_path = tk_path.replace(sep, '/')
46 else:
47 lib_path = join(dirname(dirname(dirname(__file__))))
48 tcl_path = join(lib_path, 'tcl8.6')
49 tk_path = join(lib_path, 'tk8.6')
50 if exists(tcl_path):
51 tklib.Tcl_Eval(app.interp, 'set tcl_library "{0}"'.format(tcl_path).encode('utf-8'))
52 if exists(tk_path):
53 tklib.Tcl_Eval(app.interp, 'set tk_library "{0}"'.format(tk_path).encode('utf-8'))
54
55 if tklib.Tcl_Init(app.interp) == tklib.TCL_ERROR:
56 app.raiseTclError()
57 skip_tk_init = tklib.Tcl_GetVar(
58 app.interp, b"_tkinter_skip_tk_init", tklib.TCL_GLOBAL_ONLY)
59 if skip_tk_init and tkffi.string(skip_tk_init) == b"1":
60 return
61
62 if tklib.Tk_Init(app.interp) == tklib.TCL_ERROR:
63 app.raiseTclError()
64
65 class _CommandData(object):
66 def __new__(cls, app, name, func):
67 self = object.__new__(cls)
68 self.app = app
69 self.name = name
70 self.func = func
71 handle = tkffi.new_handle(self)
72 app._commands[name] = handle # To keep the command alive
73 return tkffi.cast("ClientData", handle)
74
75 @tkffi.callback("Tcl_CmdProc")
76 def PythonCmd(clientData, interp, argc, argv):
77 self = tkffi.from_handle(clientData)
78 assert self.app.interp == interp
79 with self.app._tcl_lock_released():
80 try:
81 args = [FromTclString(tkffi.string(arg)) for arg in argv[1:argc]]
82 result = self.func(*args)
83 obj = AsObj(result)
84 tklib.Tcl_SetObjResult(interp, obj)
85 except:
86 self.app.errorInCmd = True
87 self.app.exc_info = sys.exc_info()
88 return tklib.TCL_ERROR
89 else:
90 return tklib.TCL_OK
91
92 @tkffi.callback("Tcl_CmdDeleteProc")
93 def PythonCmdDelete(clientData):
94 self = tkffi.from_handle(clientData)
95 app = self.app
96 del app._commands[self.name]
97 return
98
99
100 class TkApp(object):
101 _busywaitinterval = 0.02 # 20ms.
102
103 def __new__(cls, screenName, className,
104 interactive, wantobjects, wantTk, sync, use):
105 if not wantobjects:
106 raise NotImplementedError("wantobjects=True only")
107 self = object.__new__(cls)
108 self.interp = tklib.Tcl_CreateInterp()
109 self._wantobjects = wantobjects
110 self.threaded = bool(tklib.Tcl_GetVar2Ex(
111 self.interp, b"tcl_platform", b"threaded",
112 tklib.TCL_GLOBAL_ONLY))
113 self.thread_id = tklib.Tcl_GetCurrentThread()
114 self.dispatching = False
115 self.quitMainLoop = False
116 self.errorInCmd = False
117
118 if not self.threaded:
119 # TCL is not thread-safe, calls needs to be serialized.
120 self._tcl_lock = threading.RLock()
121 else:
122 self._tcl_lock = _DummyLock()
123
124 self._typeCache = TypeCache()
125 self._commands = {}
126
127 # Delete the 'exit' command, which can screw things up
128 tklib.Tcl_DeleteCommand(self.interp, b"exit")
129
130 if screenName is not None:
131 tklib.Tcl_SetVar2(self.interp, b"env", b"DISPLAY",
132 screenName.encode('utf-8'),
133 tklib.TCL_GLOBAL_ONLY)
134
135 if interactive:
136 tklib.Tcl_SetVar(self.interp, b"tcl_interactive", b"1",
137 tklib.TCL_GLOBAL_ONLY)
138 else:
139 tklib.Tcl_SetVar(self.interp, b"tcl_interactive", b"0",
140 tklib.TCL_GLOBAL_ONLY)
141
142 # This is used to get the application class for Tk 4.1 and up
143 argv0 = className.lower().encode('utf-8')
144 tklib.Tcl_SetVar(self.interp, b"argv0", argv0,
145 tklib.TCL_GLOBAL_ONLY)
146
147 if not wantTk:
148 tklib.Tcl_SetVar(self.interp, b"_tkinter_skip_tk_init", b"1",
149 tklib.TCL_GLOBAL_ONLY)
150
151 # some initial arguments need to be in argv
152 if sync or use:
153 args = ""
154 if sync:
155 args += "-sync"
156 if use:
157 if sync:
158 args += " "
159 args += "-use " + use
160
161 tklib.Tcl_SetVar(self.interp, "argv", args,
162 tklib.TCL_GLOBAL_ONLY)
163
164 Tcl_AppInit(self)
165 # EnableEventHook()
166 self._typeCache.add_extra_types(self)
167 return self
168
169 def __del__(self):
170 tklib.Tcl_DeleteInterp(self.interp)
171 # DisableEventHook()
172
173 def raiseTclError(self):
174 if self.errorInCmd:
175 self.errorInCmd = False
176 raise self.exc_info[1].with_traceback(self.exc_info[2])
177 raise TclError(tkffi.string(
178 tklib.Tcl_GetStringResult(self.interp)).decode('utf-8'))
179
180 def wantobjects(self):
181 return self._wantobjects
182
183 def _check_tcl_appartment(self):
184 if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
185 raise RuntimeError("Calling Tcl from different appartment")
186
187 @contextlib.contextmanager
188 def _tcl_lock_released(self):
189 "Context manager to temporarily release the tcl lock."
190 self._tcl_lock.release()
191 yield
192 self._tcl_lock.acquire()
193
194 def loadtk(self):
195 # We want to guard against calling Tk_Init() multiple times
196 err = tklib.Tcl_Eval(self.interp, b"info exists tk_version")
197 if err == tklib.TCL_ERROR:
198 self.raiseTclError()
199 tk_exists = tklib.Tcl_GetStringResult(self.interp)
200 if not tk_exists or tkffi.string(tk_exists) != b"1":
201 err = tklib.Tk_Init(self.interp)
202 if err == tklib.TCL_ERROR:
203 self.raiseTclError()
204
205 def interpaddr(self):
206 return int(tkffi.cast('size_t', self.interp))
207
208 def _var_invoke(self, func, *args, **kwargs):
209 if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
210 # The current thread is not the interpreter thread.
211 # Marshal the call to the interpreter thread, then wait
212 # for completion.
213 raise NotImplementedError("Call from another thread")
214 return func(*args, **kwargs)
215
216 def _getvar(self, name1, name2=None, global_only=False):
217 name1 = varname_converter(name1)
218 if not name2:
219 name2 = tkffi.NULL
220 flags=tklib.TCL_LEAVE_ERR_MSG
221 if global_only:
222 flags |= tklib.TCL_GLOBAL_ONLY
223 with self._tcl_lock:
224 res = tklib.Tcl_GetVar2Ex(self.interp, name1, name2, flags)
225 if not res:
226 self.raiseTclError()
227 assert self._wantobjects
228 return FromObj(self, res)
229
230 def _setvar(self, name1, value, global_only=False):
231 name1 = varname_converter(name1)
232 # XXX Acquire tcl lock???
233 newval = AsObj(value)
234 flags=tklib.TCL_LEAVE_ERR_MSG
235 if global_only:
236 flags |= tklib.TCL_GLOBAL_ONLY
237 with self._tcl_lock:
238 res = tklib.Tcl_SetVar2Ex(self.interp, name1, tkffi.NULL,
239 newval, flags)
240 if not res:
241 self.raiseTclError()
242
243 def _unsetvar(self, name1, name2=None, global_only=False):
244 name1 = varname_converter(name1)
245 if not name2:
246 name2 = tkffi.NULL
247 flags=tklib.TCL_LEAVE_ERR_MSG
248 if global_only:
249 flags |= tklib.TCL_GLOBAL_ONLY
250 with self._tcl_lock:
251 res = tklib.Tcl_UnsetVar2(self.interp, name1, name2, flags)
252 if res == tklib.TCL_ERROR:
253 self.raiseTclError()
254
255 def getvar(self, name1, name2=None):
256 return self._var_invoke(self._getvar, name1, name2)
257
258 def globalgetvar(self, name1, name2=None):
259 return self._var_invoke(self._getvar, name1, name2, global_only=True)
260
261 def setvar(self, name1, value):
262 return self._var_invoke(self._setvar, name1, value)
263
264 def globalsetvar(self, name1, value):
265 return self._var_invoke(self._setvar, name1, value, global_only=True)
266
267 def unsetvar(self, name1, name2=None):
268 return self._var_invoke(self._unsetvar, name1, name2)
269
270 def globalunsetvar(self, name1, name2=None):
271 return self._var_invoke(self._unsetvar, name1, name2, global_only=True)
272
273 # COMMANDS
274
275 def createcommand(self, cmdName, func):
276 if not callable(func):
277 raise TypeError("command not callable")
278
279 if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
280 raise NotImplementedError("Call from another thread")
281
282 clientData = _CommandData(self, cmdName, func)
283
284 if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
285 raise NotImplementedError("Call from another thread")
286
287 with self._tcl_lock:
288 res = tklib.Tcl_CreateCommand(
289 self.interp, cmdName.encode('utf-8'), _CommandData.PythonCmd,
290 clientData, _CommandData.PythonCmdDelete)
291 if not res:
292 raise TclError("can't create Tcl command")
293
294 def deletecommand(self, cmdName):
295 if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
296 raise NotImplementedError("Call from another thread")
297
298 with self._tcl_lock:
299 res = tklib.Tcl_DeleteCommand(self.interp, cmdName.encode('utf-8'))
300 if res == -1:
301 raise TclError("can't delete Tcl command")
302
303 def call(self, *args):
304 flags = tklib.TCL_EVAL_DIRECT | tklib.TCL_EVAL_GLOBAL
305
306 # If args is a single tuple, replace with contents of tuple
307 if len(args) == 1 and isinstance(args[0], tuple):
308 args = args[0]
309
310 if self.threaded and self.thread_id != tklib.Tcl_GetCurrentThread():
311 # We cannot call the command directly. Instead, we must
312 # marshal the parameters to the interpreter thread.
313 raise NotImplementedError("Call from another thread")
314
315 objects = tkffi.new("Tcl_Obj*[]", len(args))
316 argc = len(args)
317 try:
318 for i, arg in enumerate(args):
319 if arg is None:
320 argc = i
321 break
322 obj = AsObj(arg)
323 tklib.Tcl_IncrRefCount(obj)
324 objects[i] = obj
325
326 with self._tcl_lock:
327 res = tklib.Tcl_EvalObjv(self.interp, argc, objects, flags)
328 if res == tklib.TCL_ERROR:
329 self.raiseTclError()
330 else:
331 result = self._callResult()
332 finally:
333 for obj in objects:
334 if obj:
335 tklib.Tcl_DecrRefCount(obj)
336 return result
337
338 def _callResult(self):
339 assert self._wantobjects
340 value = tklib.Tcl_GetObjResult(self.interp)
341 # Not sure whether the IncrRef is necessary, but something
342 # may overwrite the interpreter result while we are
343 # converting it.
344 tklib.Tcl_IncrRefCount(value)
345 res = FromObj(self, value)
346 tklib.Tcl_DecrRefCount(value)
347 return res
348
349 def eval(self, script):
350 self._check_tcl_appartment()
351 with self._tcl_lock:
352 res = tklib.Tcl_Eval(self.interp, script.encode('utf-8'))
353 if res == tklib.TCL_ERROR:
354 self.raiseTclError()
355 result = tkffi.string(tklib.Tcl_GetStringResult(self.interp))
356 return FromTclString(result)
357
358 def evalfile(self, filename):
359 self._check_tcl_appartment()
360 with self._tcl_lock:
361 res = tklib.Tcl_EvalFile(self.interp, filename.encode('utf-8'))
362 if res == tklib.TCL_ERROR:
363 self.raiseTclError()
364 result = tkffi.string(tklib.Tcl_GetStringResult(self.interp))
365 return FromTclString(result)
366
367 def split(self, arg):
368 warnings.warn("split() is deprecated; consider using splitlist() instead",
369 DeprecationWarning)
370 if isinstance(arg, Tcl_Obj):
371 objc = tkffi.new("int*")
372 objv = tkffi.new("Tcl_Obj***")
373 status = tklib.Tcl_ListObjGetElements(self.interp, arg._value, objc, objv)
374 if status == tklib.TCL_ERROR:
375 return FromObj(self, arg._value)
376 if objc == 0:
377 return ''
378 elif objc == 1:
379 return FromObj(self, objv[0][0])
380 result = []
381 for i in range(objc[0]):
382 result.append(FromObj(self, objv[0][i]))
383 return tuple(result)
384 elif isinstance(arg, (tuple, list)):
385 return self._splitObj(arg)
386 if isinstance(arg, str):
387 arg = arg.encode('utf-8')
388 return self._split(arg)
389
390 def splitlist(self, arg):
391 if isinstance(arg, Tcl_Obj):
392 objc = tkffi.new("int*")
393 objv = tkffi.new("Tcl_Obj***")
394 status = tklib.Tcl_ListObjGetElements(self.interp, arg._value, objc, objv)
395 if status == tklib.TCL_ERROR:
396 self.raiseTclError()
397 result = []
398 for i in range(objc[0]):
399 result.append(FromObj(self, objv[0][i]))
400 return tuple(result)
401 elif isinstance(arg, tuple):
402 return arg
403 elif isinstance(arg, list):
404 return tuple(arg)
405 elif isinstance(arg, str):
406 arg = arg.encode('utf8')
407
408 argc = tkffi.new("int*")
409 argv = tkffi.new("char***")
410 res = tklib.Tcl_SplitList(self.interp, arg, argc, argv)
411 if res == tklib.TCL_ERROR:
412 self.raiseTclError()
413
414 result = tuple(FromTclString(tkffi.string(argv[0][i]))
415 for i in range(argc[0]))
416 tklib.Tcl_Free(argv[0])
417 return result
418
419 def _splitObj(self, arg):
420 if isinstance(arg, tuple):
421 size = len(arg)
422 result = None
423 # Recursively invoke SplitObj for all tuple items.
424 # If this does not return a new object, no action is
425 # needed.
426 for i in range(size):
427 elem = arg[i]
428 newelem = self._splitObj(elem)
429 if result is None:
430 if newelem == elem:
431 continue
432 result = [None] * size
433 for k in range(i):
434 result[k] = arg[k]
435 result[i] = newelem
436 if result is not None:
437 return tuple(result)
438 if isinstance(arg, list):
439 # Recursively invoke SplitObj for all list items.
440 return tuple(self._splitObj(elem) for elem in arg)
441 elif isinstance(arg, str):
442 argc = tkffi.new("int*")
443 argv = tkffi.new("char***")
444 list_ = arg.encode('utf-8')
445 res = tklib.Tcl_SplitList(tkffi.NULL, list_, argc, argv)
446 if res != tklib.TCL_OK:
447 return arg
448 tklib.Tcl_Free(argv[0])
449 if argc[0] > 1:
450 return self._split(list_)
451 elif isinstance(arg, bytes):
452 argc = tkffi.new("int*")
453 argv = tkffi.new("char***")
454 list_ = arg
455 res = tklib.Tcl_SplitList(tkffi.NULL, list_, argc, argv)
456 if res != tklib.TCL_OK:
457 return arg
458 tklib.Tcl_Free(argv[0])
459 if argc[0] > 1:
460 return self._split(list_)
461 return arg
462
463 def _split(self, arg):
464 argc = tkffi.new("int*")
465 argv = tkffi.new("char***")
466 res = tklib.Tcl_SplitList(tkffi.NULL, arg, argc, argv)
467 if res == tklib.TCL_ERROR:
468 # Not a list.
469 # Could be a quoted string containing funnies, e.g. {"}.
470 # Return the string itself.
471 return FromTclString(arg)
472
473 try:
474 if argc[0] == 0:
475 return ""
476 elif argc[0] == 1:
477 return FromTclString(tkffi.string(argv[0][0]))
478 else:
479 return tuple(self._split(argv[0][i])
480 for i in range(argc[0]))
481 finally:
482 tklib.Tcl_Free(argv[0])
483
484 def merge(self, *args):
485 warnings.warn("merge is deprecated and will be removed in 3.4",
486 DeprecationWarning)
487 s = self._merge(args)
488 return s.decode('utf-8')
489
490 def _merge(self, args):
491 argv = []
492 for arg in args:
493 if isinstance(arg, tuple):
494 argv.append(self._merge(arg))
495 elif arg is None:
496 break
497 elif isinstance(arg, bytes):
498 argv.append(arg)
499 else:
500 argv.append(str(arg).encode('utf-8'))
501 argv_array = [tkffi.new("char[]", arg) for arg in argv]
502 res = tklib.Tcl_Merge(len(argv), argv_array)
503 if not res:
504 raise TclError("merge failed")
505 try:
506 return tkffi.string(res)
507 finally:
508 tklib.Tcl_Free(res)
509
510 def getboolean(self, s):
511 if isinstance(s, int):
512 return bool(s)
513 if isinstance(s, Tcl_Obj):
514 s = s.string
515 if '\x00' in s:
516 raise TypeError
517 s = s.encode('utf-8')
518 v = tkffi.new("int*")
519 res = tklib.Tcl_GetBoolean(self.interp, s, v)
520 if res == tklib.TCL_ERROR:
521 self.raiseTclError()
522 return bool(v[0])
523
524 def getint(self, s):
525 if isinstance(s, int):
526 return s
527 if isinstance(s, Tcl_Obj):
528 s = s.string
529 if '\x00' in s:
530 raise TypeError
531 s = s.encode('utf-8')
532 if tklib.HAVE_LIBTOMMATH or tklib.HAVE_WIDE_INT_TYPE:
533 value = tklib.Tcl_NewStringObj(s, -1)
534 if not value:
535 self.raiseTclError()
536 try:
537 if tklib.HAVE_LIBTOMMATH:
538 return FromBignumObj(self, value)
539 else:
540 return FromWideIntObj(self, value)
541 finally:
542 tklib.Tcl_DecrRefCount(value)
543 else:
544 v = tkffi.new("int*")
545 res = tklib.Tcl_GetInt(self.interp, s, v)
546 if res == tklib.TCL_ERROR:
547 self.raiseTclError()
548 return v[0]
549
550 def getdouble(self, s):
551 if isinstance(s, (float, int)):
552 return float(s)
553 if isinstance(s, Tcl_Obj):
554 s = s.string
555 if '\x00' in s:
556 raise TypeError
557 s = s.encode('utf-8')
558 v = tkffi.new("double*")
559 res = tklib.Tcl_GetDouble(self.interp, s, v)
560 if res == tklib.TCL_ERROR:
561 self.raiseTclError()
562 return v[0]
563
564 def exprboolean(self, s):
565 if '\x00' in s:
566 raise TypeError
567 s = s.encode('utf-8')
568 v = tkffi.new("int*")
569 res = tklib.Tcl_ExprBoolean(self.interp, s, v)
570 if res == tklib.TCL_ERROR:
571 self.raiseTclError()
572 return v[0]
573
574 def exprlong(self, s):
575 if '\x00' in s:
576 raise TypeError
577 s = s.encode('utf-8')
578 v = tkffi.new("long*")
579 res = tklib.Tcl_ExprLong(self.interp, s, v)
580 if res == tklib.TCL_ERROR:
581 self.raiseTclError()
582 return v[0]
583
584 def exprdouble(self, s):
585 if '\x00' in s:
586 raise TypeError
587 s = s.encode('utf-8')
588 v = tkffi.new("double*")
589 res = tklib.Tcl_ExprDouble(self.interp, s, v)
590 if res == tklib.TCL_ERROR:
591 self.raiseTclError()
592 return v[0]
593
594 def exprstring(self, s):
595 if '\x00' in s:
596 raise TypeError
597 s = s.encode('utf-8')
598 res = tklib.Tcl_ExprString(self.interp, s)
599 if res == tklib.TCL_ERROR:
600 self.raiseTclError()
601 return FromTclString(tkffi.string(
602 tklib.Tcl_GetStringResult(self.interp)))
603
604 def mainloop(self, threshold):
605 self._check_tcl_appartment()
606 self.dispatching = True
607 while (tklib.Tk_GetNumMainWindows() > threshold and
608 not self.quitMainLoop and not self.errorInCmd):
609
610 if self.threaded:
611 result = tklib.Tcl_DoOneEvent(0)
612 else:
613 with self._tcl_lock:
614 result = tklib.Tcl_DoOneEvent(tklib.TCL_DONT_WAIT)
615 if result == 0:
616 time.sleep(self._busywaitinterval)
617
618 if result < 0:
619 break
620 self.dispatching = False
621 self.quitMainLoop = False
622 if self.errorInCmd:
623 self.errorInCmd = False
624 raise self.exc_info[1].with_traceback(self.exc_info[2])
625
626 def quit(self):
627 self.quitMainLoop = True
628
629 def _createbytearray(self, buf):
630 """Convert Python string or any buffer compatible object to Tcl
631 byte-array object. Use it to pass binary data (e.g. image's
632 data) to Tcl/Tk commands."""
633 cdata = tkffi.new("char[]", buf)
634 res = tklib.Tcl_NewByteArrayObj(cdata, len(buf))
635 if not res:
636 self.raiseTclError()
637 return TclObject(res)