logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

redirector.py (6875B)


  1. from tkinter import TclError
  2. class WidgetRedirector:
  3. """Support for redirecting arbitrary widget subcommands.
  4. Some Tk operations don't normally pass through tkinter. For example, if a
  5. character is inserted into a Text widget by pressing a key, a default Tk
  6. binding to the widget's 'insert' operation is activated, and the Tk library
  7. processes the insert without calling back into tkinter.
  8. Although a binding to <Key> could be made via tkinter, what we really want
  9. to do is to hook the Tk 'insert' operation itself. For one thing, we want
  10. a text.insert call in idle code to have the same effect as a key press.
  11. When a widget is instantiated, a Tcl command is created whose name is the
  12. same as the pathname widget._w. This command is used to invoke the various
  13. widget operations, e.g. insert (for a Text widget). We are going to hook
  14. this command and provide a facility ('register') to intercept the widget
  15. operation. We will also intercept method calls on the tkinter class
  16. instance that represents the tk widget.
  17. In IDLE, WidgetRedirector is used in Percolator to intercept Text
  18. commands. The function being registered provides access to the top
  19. of a Percolator chain. At the bottom of the chain is a call to the
  20. original Tk widget operation.
  21. """
  22. def __init__(self, widget):
  23. '''Initialize attributes and setup redirection.
  24. _operations: dict mapping operation name to new function.
  25. widget: the widget whose tcl command is to be intercepted.
  26. tk: widget.tk, a convenience attribute, probably not needed.
  27. orig: new name of the original tcl command.
  28. Since renaming to orig fails with TclError when orig already
  29. exists, only one WidgetDirector can exist for a given widget.
  30. '''
  31. self._operations = {}
  32. self.widget = widget # widget instance
  33. self.tk = tk = widget.tk # widget's root
  34. w = widget._w # widget's (full) Tk pathname
  35. self.orig = w + "_orig"
  36. # Rename the Tcl command within Tcl:
  37. tk.call("rename", w, self.orig)
  38. # Create a new Tcl command whose name is the widget's pathname, and
  39. # whose action is to dispatch on the operation passed to the widget:
  40. tk.createcommand(w, self.dispatch)
  41. def __repr__(self):
  42. return "%s(%s<%s>)" % (self.__class__.__name__,
  43. self.widget.__class__.__name__,
  44. self.widget._w)
  45. def close(self):
  46. "Unregister operations and revert redirection created by .__init__."
  47. for operation in list(self._operations):
  48. self.unregister(operation)
  49. widget = self.widget
  50. tk = widget.tk
  51. w = widget._w
  52. # Restore the original widget Tcl command.
  53. tk.deletecommand(w)
  54. tk.call("rename", self.orig, w)
  55. del self.widget, self.tk # Should not be needed
  56. # if instance is deleted after close, as in Percolator.
  57. def register(self, operation, function):
  58. '''Return OriginalCommand(operation) after registering function.
  59. Registration adds an operation: function pair to ._operations.
  60. It also adds a widget function attribute that masks the tkinter
  61. class instance method. Method masking operates independently
  62. from command dispatch.
  63. If a second function is registered for the same operation, the
  64. first function is replaced in both places.
  65. '''
  66. self._operations[operation] = function
  67. setattr(self.widget, operation, function)
  68. return OriginalCommand(self, operation)
  69. def unregister(self, operation):
  70. '''Return the function for the operation, or None.
  71. Deleting the instance attribute unmasks the class attribute.
  72. '''
  73. if operation in self._operations:
  74. function = self._operations[operation]
  75. del self._operations[operation]
  76. try:
  77. delattr(self.widget, operation)
  78. except AttributeError:
  79. pass
  80. return function
  81. else:
  82. return None
  83. def dispatch(self, operation, *args):
  84. '''Callback from Tcl which runs when the widget is referenced.
  85. If an operation has been registered in self._operations, apply the
  86. associated function to the args passed into Tcl. Otherwise, pass the
  87. operation through to Tk via the original Tcl function.
  88. Note that if a registered function is called, the operation is not
  89. passed through to Tk. Apply the function returned by self.register()
  90. to *args to accomplish that. For an example, see colorizer.py.
  91. '''
  92. m = self._operations.get(operation)
  93. try:
  94. if m:
  95. return m(*args)
  96. else:
  97. return self.tk.call((self.orig, operation) + args)
  98. except TclError:
  99. return ""
  100. class OriginalCommand:
  101. '''Callable for original tk command that has been redirected.
  102. Returned by .register; can be used in the function registered.
  103. redir = WidgetRedirector(text)
  104. def my_insert(*args):
  105. print("insert", args)
  106. original_insert(*args)
  107. original_insert = redir.register("insert", my_insert)
  108. '''
  109. def __init__(self, redir, operation):
  110. '''Create .tk_call and .orig_and_operation for .__call__ method.
  111. .redir and .operation store the input args for __repr__.
  112. .tk and .orig copy attributes of .redir (probably not needed).
  113. '''
  114. self.redir = redir
  115. self.operation = operation
  116. self.tk = redir.tk # redundant with self.redir
  117. self.orig = redir.orig # redundant with self.redir
  118. # These two could be deleted after checking recipient code.
  119. self.tk_call = redir.tk.call
  120. self.orig_and_operation = (redir.orig, operation)
  121. def __repr__(self):
  122. return "%s(%r, %r)" % (self.__class__.__name__,
  123. self.redir, self.operation)
  124. def __call__(self, *args):
  125. return self.tk_call(self.orig_and_operation + args)
  126. def _widget_redirector(parent): # htest #
  127. from tkinter import Toplevel, Text
  128. top = Toplevel(parent)
  129. top.title("Test WidgetRedirector")
  130. x, y = map(int, parent.geometry().split('+')[1:])
  131. top.geometry("+%d+%d" % (x, y + 175))
  132. text = Text(top)
  133. text.pack()
  134. text.focus_set()
  135. redir = WidgetRedirector(text)
  136. def my_insert(*args):
  137. print("insert", args)
  138. original_insert(*args)
  139. original_insert = redir.register("insert", my_insert)
  140. if __name__ == "__main__":
  141. from unittest import main
  142. main('idlelib.idle_test.test_redirector', verbosity=2, exit=False)
  143. from idlelib.idle_test.htest import run
  144. run(_widget_redirector)