multicall.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. """
  2. MultiCall - a class which inherits its methods from a Tkinter widget (Text, for
  3. example), but enables multiple calls of functions per virtual event - all
  4. matching events will be called, not only the most specific one. This is done
  5. by wrapping the event functions - event_add, event_delete and event_info.
  6. MultiCall recognizes only a subset of legal event sequences. Sequences which
  7. are not recognized are treated by the original Tk handling mechanism. A
  8. more-specific event will be called before a less-specific event.
  9. The recognized sequences are complete one-event sequences (no emacs-style
  10. Ctrl-X Ctrl-C, no shortcuts like <3>), for all types of events.
  11. Key/Button Press/Release events can have modifiers.
  12. The recognized modifiers are Shift, Control, Option and Command for Mac, and
  13. Control, Alt, Shift, Meta/M for other platforms.
  14. For all events which were handled by MultiCall, a new member is added to the
  15. event instance passed to the binded functions - mc_type. This is one of the
  16. event type constants defined in this module (such as MC_KEYPRESS).
  17. For Key/Button events (which are handled by MultiCall and may receive
  18. modifiers), another member is added - mc_state. This member gives the state
  19. of the recognized modifiers, as a combination of the modifier constants
  20. also defined in this module (for example, MC_SHIFT).
  21. Using these members is absolutely portable.
  22. The order by which events are called is defined by these rules:
  23. 1. A more-specific event will be called before a less-specific event.
  24. 2. A recently-binded event will be called before a previously-binded event,
  25. unless this conflicts with the first rule.
  26. Each function will be called at most once for each event.
  27. """
  28. import re
  29. import sys
  30. import tkinter
  31. # the event type constants, which define the meaning of mc_type
  32. MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3;
  33. MC_ACTIVATE=4; MC_CIRCULATE=5; MC_COLORMAP=6; MC_CONFIGURE=7;
  34. MC_DEACTIVATE=8; MC_DESTROY=9; MC_ENTER=10; MC_EXPOSE=11; MC_FOCUSIN=12;
  35. MC_FOCUSOUT=13; MC_GRAVITY=14; MC_LEAVE=15; MC_MAP=16; MC_MOTION=17;
  36. MC_MOUSEWHEEL=18; MC_PROPERTY=19; MC_REPARENT=20; MC_UNMAP=21; MC_VISIBILITY=22;
  37. # the modifier state constants, which define the meaning of mc_state
  38. MC_SHIFT = 1<<0; MC_CONTROL = 1<<2; MC_ALT = 1<<3; MC_META = 1<<5
  39. MC_OPTION = 1<<6; MC_COMMAND = 1<<7
  40. # define the list of modifiers, to be used in complex event types.
  41. if sys.platform == "darwin":
  42. _modifiers = (("Shift",), ("Control",), ("Option",), ("Command",))
  43. _modifier_masks = (MC_SHIFT, MC_CONTROL, MC_OPTION, MC_COMMAND)
  44. else:
  45. _modifiers = (("Control",), ("Alt",), ("Shift",), ("Meta", "M"))
  46. _modifier_masks = (MC_CONTROL, MC_ALT, MC_SHIFT, MC_META)
  47. # a dictionary to map a modifier name into its number
  48. _modifier_names = dict([(name, number)
  49. for number in range(len(_modifiers))
  50. for name in _modifiers[number]])
  51. # In 3.4, if no shell window is ever open, the underlying Tk widget is
  52. # destroyed before .__del__ methods here are called. The following
  53. # is used to selectively ignore shutdown exceptions to avoid
  54. # 'Exception ignored' messages. See http://bugs.python.org/issue20167
  55. APPLICATION_GONE = "application has been destroyed"
  56. # A binder is a class which binds functions to one type of event. It has two
  57. # methods: bind and unbind, which get a function and a parsed sequence, as
  58. # returned by _parse_sequence(). There are two types of binders:
  59. # _SimpleBinder handles event types with no modifiers and no detail.
  60. # No Python functions are called when no events are binded.
  61. # _ComplexBinder handles event types with modifiers and a detail.
  62. # A Python function is called each time an event is generated.
  63. class _SimpleBinder:
  64. def __init__(self, type, widget, widgetinst):
  65. self.type = type
  66. self.sequence = '<'+_types[type][0]+'>'
  67. self.widget = widget
  68. self.widgetinst = widgetinst
  69. self.bindedfuncs = []
  70. self.handlerid = None
  71. def bind(self, triplet, func):
  72. if not self.handlerid:
  73. def handler(event, l = self.bindedfuncs, mc_type = self.type):
  74. event.mc_type = mc_type
  75. wascalled = {}
  76. for i in range(len(l)-1, -1, -1):
  77. func = l[i]
  78. if func not in wascalled:
  79. wascalled[func] = True
  80. r = func(event)
  81. if r:
  82. return r
  83. self.handlerid = self.widget.bind(self.widgetinst,
  84. self.sequence, handler)
  85. self.bindedfuncs.append(func)
  86. def unbind(self, triplet, func):
  87. self.bindedfuncs.remove(func)
  88. if not self.bindedfuncs:
  89. self.widget.unbind(self.widgetinst, self.sequence, self.handlerid)
  90. self.handlerid = None
  91. def __del__(self):
  92. if self.handlerid:
  93. try:
  94. self.widget.unbind(self.widgetinst, self.sequence,
  95. self.handlerid)
  96. except tkinter.TclError as e:
  97. if not APPLICATION_GONE in e.args[0]:
  98. raise
  99. # An int in range(1 << len(_modifiers)) represents a combination of modifiers
  100. # (if the least significant bit is on, _modifiers[0] is on, and so on).
  101. # _state_subsets gives for each combination of modifiers, or *state*,
  102. # a list of the states which are a subset of it. This list is ordered by the
  103. # number of modifiers is the state - the most specific state comes first.
  104. _states = range(1 << len(_modifiers))
  105. _state_names = [''.join(m[0]+'-'
  106. for i, m in enumerate(_modifiers)
  107. if (1 << i) & s)
  108. for s in _states]
  109. def expand_substates(states):
  110. '''For each item of states return a list containing all combinations of
  111. that item with individual bits reset, sorted by the number of set bits.
  112. '''
  113. def nbits(n):
  114. "number of bits set in n base 2"
  115. nb = 0
  116. while n:
  117. n, rem = divmod(n, 2)
  118. nb += rem
  119. return nb
  120. statelist = []
  121. for state in states:
  122. substates = list(set(state & x for x in states))
  123. substates.sort(key=nbits, reverse=True)
  124. statelist.append(substates)
  125. return statelist
  126. _state_subsets = expand_substates(_states)
  127. # _state_codes gives for each state, the portable code to be passed as mc_state
  128. _state_codes = []
  129. for s in _states:
  130. r = 0
  131. for i in range(len(_modifiers)):
  132. if (1 << i) & s:
  133. r |= _modifier_masks[i]
  134. _state_codes.append(r)
  135. class _ComplexBinder:
  136. # This class binds many functions, and only unbinds them when it is deleted.
  137. # self.handlerids is the list of seqs and ids of binded handler functions.
  138. # The binded functions sit in a dictionary of lists of lists, which maps
  139. # a detail (or None) and a state into a list of functions.
  140. # When a new detail is discovered, handlers for all the possible states
  141. # are binded.
  142. def __create_handler(self, lists, mc_type, mc_state):
  143. def handler(event, lists = lists,
  144. mc_type = mc_type, mc_state = mc_state,
  145. ishandlerrunning = self.ishandlerrunning,
  146. doafterhandler = self.doafterhandler):
  147. ishandlerrunning[:] = [True]
  148. event.mc_type = mc_type
  149. event.mc_state = mc_state
  150. wascalled = {}
  151. r = None
  152. for l in lists:
  153. for i in range(len(l)-1, -1, -1):
  154. func = l[i]
  155. if func not in wascalled:
  156. wascalled[func] = True
  157. r = l[i](event)
  158. if r:
  159. break
  160. if r:
  161. break
  162. ishandlerrunning[:] = []
  163. # Call all functions in doafterhandler and remove them from list
  164. for f in doafterhandler:
  165. f()
  166. doafterhandler[:] = []
  167. if r:
  168. return r
  169. return handler
  170. def __init__(self, type, widget, widgetinst):
  171. self.type = type
  172. self.typename = _types[type][0]
  173. self.widget = widget
  174. self.widgetinst = widgetinst
  175. self.bindedfuncs = {None: [[] for s in _states]}
  176. self.handlerids = []
  177. # we don't want to change the lists of functions while a handler is
  178. # running - it will mess up the loop and anyway, we usually want the
  179. # change to happen from the next event. So we have a list of functions
  180. # for the handler to run after it finishes calling the binded functions.
  181. # It calls them only once.
  182. # ishandlerrunning is a list. An empty one means no, otherwise - yes.
  183. # this is done so that it would be mutable.
  184. self.ishandlerrunning = []
  185. self.doafterhandler = []
  186. for s in _states:
  187. lists = [self.bindedfuncs[None][i] for i in _state_subsets[s]]
  188. handler = self.__create_handler(lists, type, _state_codes[s])
  189. seq = '<'+_state_names[s]+self.typename+'>'
  190. self.handlerids.append((seq, self.widget.bind(self.widgetinst,
  191. seq, handler)))
  192. def bind(self, triplet, func):
  193. if triplet[2] not in self.bindedfuncs:
  194. self.bindedfuncs[triplet[2]] = [[] for s in _states]
  195. for s in _states:
  196. lists = [ self.bindedfuncs[detail][i]
  197. for detail in (triplet[2], None)
  198. for i in _state_subsets[s] ]
  199. handler = self.__create_handler(lists, self.type,
  200. _state_codes[s])
  201. seq = "<%s%s-%s>"% (_state_names[s], self.typename, triplet[2])
  202. self.handlerids.append((seq, self.widget.bind(self.widgetinst,
  203. seq, handler)))
  204. doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].append(func)
  205. if not self.ishandlerrunning:
  206. doit()
  207. else:
  208. self.doafterhandler.append(doit)
  209. def unbind(self, triplet, func):
  210. doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].remove(func)
  211. if not self.ishandlerrunning:
  212. doit()
  213. else:
  214. self.doafterhandler.append(doit)
  215. def __del__(self):
  216. for seq, id in self.handlerids:
  217. try:
  218. self.widget.unbind(self.widgetinst, seq, id)
  219. except tkinter.TclError as e:
  220. if not APPLICATION_GONE in e.args[0]:
  221. raise
  222. # define the list of event types to be handled by MultiEvent. the order is
  223. # compatible with the definition of event type constants.
  224. _types = (
  225. ("KeyPress", "Key"), ("KeyRelease",), ("ButtonPress", "Button"),
  226. ("ButtonRelease",), ("Activate",), ("Circulate",), ("Colormap",),
  227. ("Configure",), ("Deactivate",), ("Destroy",), ("Enter",), ("Expose",),
  228. ("FocusIn",), ("FocusOut",), ("Gravity",), ("Leave",), ("Map",),
  229. ("Motion",), ("MouseWheel",), ("Property",), ("Reparent",), ("Unmap",),
  230. ("Visibility",),
  231. )
  232. # which binder should be used for every event type?
  233. _binder_classes = (_ComplexBinder,) * 4 + (_SimpleBinder,) * (len(_types)-4)
  234. # A dictionary to map a type name into its number
  235. _type_names = dict([(name, number)
  236. for number in range(len(_types))
  237. for name in _types[number]])
  238. _keysym_re = re.compile(r"^\w+$")
  239. _button_re = re.compile(r"^[1-5]$")
  240. def _parse_sequence(sequence):
  241. """Get a string which should describe an event sequence. If it is
  242. successfully parsed as one, return a tuple containing the state (as an int),
  243. the event type (as an index of _types), and the detail - None if none, or a
  244. string if there is one. If the parsing is unsuccessful, return None.
  245. """
  246. if not sequence or sequence[0] != '<' or sequence[-1] != '>':
  247. return None
  248. words = sequence[1:-1].split('-')
  249. modifiers = 0
  250. while words and words[0] in _modifier_names:
  251. modifiers |= 1 << _modifier_names[words[0]]
  252. del words[0]
  253. if words and words[0] in _type_names:
  254. type = _type_names[words[0]]
  255. del words[0]
  256. else:
  257. return None
  258. if _binder_classes[type] is _SimpleBinder:
  259. if modifiers or words:
  260. return None
  261. else:
  262. detail = None
  263. else:
  264. # _ComplexBinder
  265. if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]:
  266. type_re = _keysym_re
  267. else:
  268. type_re = _button_re
  269. if not words:
  270. detail = None
  271. elif len(words) == 1 and type_re.match(words[0]):
  272. detail = words[0]
  273. else:
  274. return None
  275. return modifiers, type, detail
  276. def _triplet_to_sequence(triplet):
  277. if triplet[2]:
  278. return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'-'+ \
  279. triplet[2]+'>'
  280. else:
  281. return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'>'
  282. _multicall_dict = {}
  283. def MultiCallCreator(widget):
  284. """Return a MultiCall class which inherits its methods from the
  285. given widget class (for example, Tkinter.Text). This is used
  286. instead of a templating mechanism.
  287. """
  288. if widget in _multicall_dict:
  289. return _multicall_dict[widget]
  290. class MultiCall (widget):
  291. assert issubclass(widget, tkinter.Misc)
  292. def __init__(self, *args, **kwargs):
  293. widget.__init__(self, *args, **kwargs)
  294. # a dictionary which maps a virtual event to a tuple with:
  295. # 0. the function binded
  296. # 1. a list of triplets - the sequences it is binded to
  297. self.__eventinfo = {}
  298. self.__binders = [_binder_classes[i](i, widget, self)
  299. for i in range(len(_types))]
  300. def bind(self, sequence=None, func=None, add=None):
  301. #print("bind(%s, %s, %s)" % (sequence, func, add),
  302. # file=sys.__stderr__)
  303. if type(sequence) is str and len(sequence) > 2 and \
  304. sequence[:2] == "<<" and sequence[-2:] == ">>":
  305. if sequence in self.__eventinfo:
  306. ei = self.__eventinfo[sequence]
  307. if ei[0] is not None:
  308. for triplet in ei[1]:
  309. self.__binders[triplet[1]].unbind(triplet, ei[0])
  310. ei[0] = func
  311. if ei[0] is not None:
  312. for triplet in ei[1]:
  313. self.__binders[triplet[1]].bind(triplet, func)
  314. else:
  315. self.__eventinfo[sequence] = [func, []]
  316. return widget.bind(self, sequence, func, add)
  317. def unbind(self, sequence, funcid=None):
  318. if type(sequence) is str and len(sequence) > 2 and \
  319. sequence[:2] == "<<" and sequence[-2:] == ">>" and \
  320. sequence in self.__eventinfo:
  321. func, triplets = self.__eventinfo[sequence]
  322. if func is not None:
  323. for triplet in triplets:
  324. self.__binders[triplet[1]].unbind(triplet, func)
  325. self.__eventinfo[sequence][0] = None
  326. return widget.unbind(self, sequence, funcid)
  327. def event_add(self, virtual, *sequences):
  328. #print("event_add(%s, %s)" % (repr(virtual), repr(sequences)),
  329. # file=sys.__stderr__)
  330. if virtual not in self.__eventinfo:
  331. self.__eventinfo[virtual] = [None, []]
  332. func, triplets = self.__eventinfo[virtual]
  333. for seq in sequences:
  334. triplet = _parse_sequence(seq)
  335. if triplet is None:
  336. #print("Tkinter event_add(%s)" % seq, file=sys.__stderr__)
  337. widget.event_add(self, virtual, seq)
  338. else:
  339. if func is not None:
  340. self.__binders[triplet[1]].bind(triplet, func)
  341. triplets.append(triplet)
  342. def event_delete(self, virtual, *sequences):
  343. if virtual not in self.__eventinfo:
  344. return
  345. func, triplets = self.__eventinfo[virtual]
  346. for seq in sequences:
  347. triplet = _parse_sequence(seq)
  348. if triplet is None:
  349. #print("Tkinter event_delete: %s" % seq, file=sys.__stderr__)
  350. widget.event_delete(self, virtual, seq)
  351. else:
  352. if func is not None:
  353. self.__binders[triplet[1]].unbind(triplet, func)
  354. triplets.remove(triplet)
  355. def event_info(self, virtual=None):
  356. if virtual is None or virtual not in self.__eventinfo:
  357. return widget.event_info(self, virtual)
  358. else:
  359. return tuple(map(_triplet_to_sequence,
  360. self.__eventinfo[virtual][1])) + \
  361. widget.event_info(self, virtual)
  362. def __del__(self):
  363. for virtual in self.__eventinfo:
  364. func, triplets = self.__eventinfo[virtual]
  365. if func:
  366. for triplet in triplets:
  367. try:
  368. self.__binders[triplet[1]].unbind(triplet, func)
  369. except tkinter.TclError as e:
  370. if not APPLICATION_GONE in e.args[0]:
  371. raise
  372. _multicall_dict[widget] = MultiCall
  373. return MultiCall
  374. def _multi_call(parent): # htest #
  375. top = tkinter.Toplevel(parent)
  376. top.title("Test MultiCall")
  377. x, y = map(int, parent.geometry().split('+')[1:])
  378. top.geometry("+%d+%d" % (x, y + 175))
  379. text = MultiCallCreator(tkinter.Text)(top)
  380. text.pack()
  381. def bindseq(seq, n=[0]):
  382. def handler(event):
  383. print(seq)
  384. text.bind("<<handler%d>>"%n[0], handler)
  385. text.event_add("<<handler%d>>"%n[0], seq)
  386. n[0] += 1
  387. bindseq("<Key>")
  388. bindseq("<Control-Key>")
  389. bindseq("<Alt-Key-a>")
  390. bindseq("<Control-Key-a>")
  391. bindseq("<Alt-Control-Key-a>")
  392. bindseq("<Key-b>")
  393. bindseq("<Control-Button-1>")
  394. bindseq("<Button-2>")
  395. bindseq("<Alt-Button-1>")
  396. bindseq("<FocusOut>")
  397. bindseq("<Enter>")
  398. bindseq("<Leave>")
  399. if __name__ == "__main__":
  400. from unittest import main
  401. main('idlelib.idle_test.test_mainmenu', verbosity=2, exit=False)
  402. from idlelib.idle_test.htest import run
  403. run(_multi_call)