|
| 1 | +# |
| 2 | +# Copyright 2021 Roger D. Serwy |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | +""" |
| 17 | +_willdispatch.py |
| 18 | +
|
| 19 | +
|
| 20 | +This Tkinter multithreading support makes use of the undocumented |
| 21 | +`.willdispatch()` function that then bypasses the `WaitForMainloop()` |
| 22 | +C function in _tkinter.c. |
| 23 | +
|
| 24 | +The C code already checks the running thread and serializes the |
| 25 | +request to the main thread with `Tkapp_ThreadSend()`. That |
| 26 | +function acquires a mutex before adding the event to the Tcl event queue. |
| 27 | +
|
| 28 | +There is a threading race condition, where `disptaching` can be set to |
| 29 | +zero before the thread reads it. This is why there is a retry loop on |
| 30 | +the function call. |
| 31 | +
|
| 32 | +""" |
| 33 | +from __future__ import print_function |
| 34 | +import traceback |
| 35 | +import sys |
| 36 | + |
| 37 | +from . import tk |
| 38 | + |
| 39 | +class _tk_dispatcher(object): |
| 40 | + """ Force `WaitForMainloop` to return 1""" |
| 41 | + _RETRY_COUNT = 10 |
| 42 | + |
| 43 | + def __init__(self, tk): |
| 44 | + self.__tk = tk |
| 45 | + |
| 46 | + def __getattr__(self, name): |
| 47 | + return getattr(self.__tk, name) |
| 48 | + |
| 49 | + |
| 50 | + # --------------------------- |
| 51 | + # create the needed functions |
| 52 | + # --------------------------- |
| 53 | + |
| 54 | + def _make_func(name): |
| 55 | + def wrapped(self, *args, **kwargs): |
| 56 | + _tk = self.__tk |
| 57 | + func = getattr(_tk, name) |
| 58 | + rcount = _tk_dispatcher._RETRY_COUNT |
| 59 | + for n in range(rcount + 1): |
| 60 | + _tk.willdispatch() |
| 61 | + try: |
| 62 | + result = func(*args, **kwargs) |
| 63 | + break |
| 64 | + except RuntimeError as exc: |
| 65 | + # There is a race condition between this thread |
| 66 | + # and the main thread event loop setting dispatch=0. |
| 67 | + # As rare as the condition is, it needs to be handled. |
| 68 | + if n < rcount: |
| 69 | + traceback.print_exc(file=sys.stderr) |
| 70 | + print('retrying %r %i of %i' % (name, n+1, rcount), |
| 71 | + file=sys.stderr) |
| 72 | + continue |
| 73 | + else: |
| 74 | + raise |
| 75 | + return result |
| 76 | + return wrapped |
| 77 | + |
| 78 | + |
| 79 | + _locals = locals() |
| 80 | + for _name in ['call', 'createcommand', 'deletecommand', |
| 81 | + 'setvar', 'unsetvar', 'getvar', |
| 82 | + 'globalsetvar', 'globalunsetvar', 'globalgetvar']: |
| 83 | + _locals[_name] = _make_func(_name) |
| 84 | + |
| 85 | + del _locals |
| 86 | + del _name |
| 87 | + del _make_func |
| 88 | + |
| 89 | + |
| 90 | +class _Tk(tk.Tk): |
| 91 | + def __init__(self, *args, **kw): |
| 92 | + tk._Tk_original_.__init__(self, *args, **kw) |
| 93 | + # patch the existing Tkapp object |
| 94 | + self.tk = _tk_dispatcher(self.tk) |
| 95 | + |
| 96 | + |
| 97 | +def tkinstall(): |
| 98 | + """Replace tkinter's `Tk` class with a thread-enabled version""" |
| 99 | + import platform |
| 100 | + runtime = platform.python_implementation() |
| 101 | + if 'cpython' not in runtime.lower(): |
| 102 | + raise RuntimeError('Requires CPython, not %s' % runtime) |
| 103 | + |
| 104 | + tk.__dict__.setdefault('_Tk_original_', tk.Tk) # save the original version |
| 105 | + if tk.Tk is tk._Tk_original_: |
| 106 | + tk.Tk = _Tk |
| 107 | + |
| 108 | + |
| 109 | +def main(widget): |
| 110 | + """Decorator to run callable on Tcl/Tk mainthread.""" |
| 111 | + def wrapped(func): |
| 112 | + widget.tk.willdispatch() |
| 113 | + widget.after(0, func) |
| 114 | + return func |
| 115 | + return wrapped |
| 116 | + |
| 117 | + |
| 118 | +def current(widget): |
| 119 | + """Decorator to run callable on the current thread. |
| 120 | + Useful for quickly changing with `tkthread.main`""" |
| 121 | + def wrapped(func): |
| 122 | + func() |
| 123 | + return func |
| 124 | + return wrapped |
0 commit comments