/Lib/idlelib/MultiCall.py

http://unladen-swallow.googlecode.com/ · Python · 406 lines · 284 code · 39 blank · 83 comment · 97 complexity · 6fe8c8bd338d255f71816ca848e039d2 MD5 · raw file

  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 sys
  29. import string
  30. import re
  31. import Tkinter
  32. import macosxSupport
  33. # the event type constants, which define the meaning of mc_type
  34. MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3;
  35. MC_ACTIVATE=4; MC_CIRCULATE=5; MC_COLORMAP=6; MC_CONFIGURE=7;
  36. MC_DEACTIVATE=8; MC_DESTROY=9; MC_ENTER=10; MC_EXPOSE=11; MC_FOCUSIN=12;
  37. MC_FOCUSOUT=13; MC_GRAVITY=14; MC_LEAVE=15; MC_MAP=16; MC_MOTION=17;
  38. MC_MOUSEWHEEL=18; MC_PROPERTY=19; MC_REPARENT=20; MC_UNMAP=21; MC_VISIBILITY=22;
  39. # the modifier state constants, which define the meaning of mc_state
  40. MC_SHIFT = 1<<0; MC_CONTROL = 1<<2; MC_ALT = 1<<3; MC_META = 1<<5
  41. MC_OPTION = 1<<6; MC_COMMAND = 1<<7
  42. # define the list of modifiers, to be used in complex event types.
  43. if macosxSupport.runningAsOSXApp():
  44. _modifiers = (("Shift",), ("Control",), ("Option",), ("Command",))
  45. _modifier_masks = (MC_SHIFT, MC_CONTROL, MC_OPTION, MC_COMMAND)
  46. else:
  47. _modifiers = (("Control",), ("Alt",), ("Shift",), ("Meta", "M"))
  48. _modifier_masks = (MC_CONTROL, MC_ALT, MC_SHIFT, MC_META)
  49. # a dictionary to map a modifier name into its number
  50. _modifier_names = dict([(name, number)
  51. for number in range(len(_modifiers))
  52. for name in _modifiers[number]])
  53. # A binder is a class which binds functions to one type of event. It has two
  54. # methods: bind and unbind, which get a function and a parsed sequence, as
  55. # returned by _parse_sequence(). There are two types of binders:
  56. # _SimpleBinder handles event types with no modifiers and no detail.
  57. # No Python functions are called when no events are binded.
  58. # _ComplexBinder handles event types with modifiers and a detail.
  59. # A Python function is called each time an event is generated.
  60. class _SimpleBinder:
  61. def __init__(self, type, widget, widgetinst):
  62. self.type = type
  63. self.sequence = '<'+_types[type][0]+'>'
  64. self.widget = widget
  65. self.widgetinst = widgetinst
  66. self.bindedfuncs = []
  67. self.handlerid = None
  68. def bind(self, triplet, func):
  69. if not self.handlerid:
  70. def handler(event, l = self.bindedfuncs, mc_type = self.type):
  71. event.mc_type = mc_type
  72. wascalled = {}
  73. for i in range(len(l)-1, -1, -1):
  74. func = l[i]
  75. if func not in wascalled:
  76. wascalled[func] = True
  77. r = func(event)
  78. if r:
  79. return r
  80. self.handlerid = self.widget.bind(self.widgetinst,
  81. self.sequence, handler)
  82. self.bindedfuncs.append(func)
  83. def unbind(self, triplet, func):
  84. self.bindedfuncs.remove(func)
  85. if not self.bindedfuncs:
  86. self.widget.unbind(self.widgetinst, self.sequence, self.handlerid)
  87. self.handlerid = None
  88. def __del__(self):
  89. if self.handlerid:
  90. self.widget.unbind(self.widgetinst, self.sequence, self.handlerid)
  91. # An int in range(1 << len(_modifiers)) represents a combination of modifiers
  92. # (if the least significent bit is on, _modifiers[0] is on, and so on).
  93. # _state_subsets gives for each combination of modifiers, or *state*,
  94. # a list of the states which are a subset of it. This list is ordered by the
  95. # number of modifiers is the state - the most specific state comes first.
  96. _states = range(1 << len(_modifiers))
  97. _state_names = [reduce(lambda x, y: x + y,
  98. [_modifiers[i][0]+'-' for i in range(len(_modifiers))
  99. if (1 << i) & s],
  100. "")
  101. for s in _states]
  102. _state_subsets = map(lambda i: filter(lambda j: not (j & (~i)), _states),
  103. _states)
  104. for l in _state_subsets:
  105. l.sort(lambda a, b, nummod = lambda x: len(filter(lambda i: (1<<i) & x,
  106. range(len(_modifiers)))):
  107. nummod(b) - nummod(a))
  108. # _state_codes gives for each state, the portable code to be passed as mc_state
  109. _state_codes = [reduce(lambda x, y: x | y,
  110. [_modifier_masks[i] for i in range(len(_modifiers))
  111. if (1 << i) & s],
  112. 0)
  113. for s in _states]
  114. class _ComplexBinder:
  115. # This class binds many functions, and only unbinds them when it is deleted.
  116. # self.handlerids is the list of seqs and ids of binded handler functions.
  117. # The binded functions sit in a dictionary of lists of lists, which maps
  118. # a detail (or None) and a state into a list of functions.
  119. # When a new detail is discovered, handlers for all the possible states
  120. # are binded.
  121. def __create_handler(self, lists, mc_type, mc_state):
  122. def handler(event, lists = lists,
  123. mc_type = mc_type, mc_state = mc_state,
  124. ishandlerrunning = self.ishandlerrunning,
  125. doafterhandler = self.doafterhandler):
  126. ishandlerrunning[:] = [True]
  127. event.mc_type = mc_type
  128. event.mc_state = mc_state
  129. wascalled = {}
  130. r = None
  131. for l in lists:
  132. for i in range(len(l)-1, -1, -1):
  133. func = l[i]
  134. if func not in wascalled:
  135. wascalled[func] = True
  136. r = l[i](event)
  137. if r:
  138. break
  139. if r:
  140. break
  141. ishandlerrunning[:] = []
  142. # Call all functions in doafterhandler and remove them from list
  143. while doafterhandler:
  144. doafterhandler.pop()()
  145. if r:
  146. return r
  147. return handler
  148. def __init__(self, type, widget, widgetinst):
  149. self.type = type
  150. self.typename = _types[type][0]
  151. self.widget = widget
  152. self.widgetinst = widgetinst
  153. self.bindedfuncs = {None: [[] for s in _states]}
  154. self.handlerids = []
  155. # we don't want to change the lists of functions while a handler is
  156. # running - it will mess up the loop and anyway, we usually want the
  157. # change to happen from the next event. So we have a list of functions
  158. # for the handler to run after it finishes calling the binded functions.
  159. # It calls them only once.
  160. # ishandlerrunning is a list. An empty one means no, otherwise - yes.
  161. # this is done so that it would be mutable.
  162. self.ishandlerrunning = []
  163. self.doafterhandler = []
  164. for s in _states:
  165. lists = [self.bindedfuncs[None][i] for i in _state_subsets[s]]
  166. handler = self.__create_handler(lists, type, _state_codes[s])
  167. seq = '<'+_state_names[s]+self.typename+'>'
  168. self.handlerids.append((seq, self.widget.bind(self.widgetinst,
  169. seq, handler)))
  170. def bind(self, triplet, func):
  171. if not self.bindedfuncs.has_key(triplet[2]):
  172. self.bindedfuncs[triplet[2]] = [[] for s in _states]
  173. for s in _states:
  174. lists = [ self.bindedfuncs[detail][i]
  175. for detail in (triplet[2], None)
  176. for i in _state_subsets[s] ]
  177. handler = self.__create_handler(lists, self.type,
  178. _state_codes[s])
  179. seq = "<%s%s-%s>"% (_state_names[s], self.typename, triplet[2])
  180. self.handlerids.append((seq, self.widget.bind(self.widgetinst,
  181. seq, handler)))
  182. doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].append(func)
  183. if not self.ishandlerrunning:
  184. doit()
  185. else:
  186. self.doafterhandler.append(doit)
  187. def unbind(self, triplet, func):
  188. doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].remove(func)
  189. if not self.ishandlerrunning:
  190. doit()
  191. else:
  192. self.doafterhandler.append(doit)
  193. def __del__(self):
  194. for seq, id in self.handlerids:
  195. self.widget.unbind(self.widgetinst, seq, id)
  196. # define the list of event types to be handled by MultiEvent. the order is
  197. # compatible with the definition of event type constants.
  198. _types = (
  199. ("KeyPress", "Key"), ("KeyRelease",), ("ButtonPress", "Button"),
  200. ("ButtonRelease",), ("Activate",), ("Circulate",), ("Colormap",),
  201. ("Configure",), ("Deactivate",), ("Destroy",), ("Enter",), ("Expose",),
  202. ("FocusIn",), ("FocusOut",), ("Gravity",), ("Leave",), ("Map",),
  203. ("Motion",), ("MouseWheel",), ("Property",), ("Reparent",), ("Unmap",),
  204. ("Visibility",),
  205. )
  206. # which binder should be used for every event type?
  207. _binder_classes = (_ComplexBinder,) * 4 + (_SimpleBinder,) * (len(_types)-4)
  208. # A dictionary to map a type name into its number
  209. _type_names = dict([(name, number)
  210. for number in range(len(_types))
  211. for name in _types[number]])
  212. _keysym_re = re.compile(r"^\w+$")
  213. _button_re = re.compile(r"^[1-5]$")
  214. def _parse_sequence(sequence):
  215. """Get a string which should describe an event sequence. If it is
  216. successfully parsed as one, return a tuple containing the state (as an int),
  217. the event type (as an index of _types), and the detail - None if none, or a
  218. string if there is one. If the parsing is unsuccessful, return None.
  219. """
  220. if not sequence or sequence[0] != '<' or sequence[-1] != '>':
  221. return None
  222. words = string.split(sequence[1:-1], '-')
  223. modifiers = 0
  224. while words and words[0] in _modifier_names:
  225. modifiers |= 1 << _modifier_names[words[0]]
  226. del words[0]
  227. if words and words[0] in _type_names:
  228. type = _type_names[words[0]]
  229. del words[0]
  230. else:
  231. return None
  232. if _binder_classes[type] is _SimpleBinder:
  233. if modifiers or words:
  234. return None
  235. else:
  236. detail = None
  237. else:
  238. # _ComplexBinder
  239. if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]:
  240. type_re = _keysym_re
  241. else:
  242. type_re = _button_re
  243. if not words:
  244. detail = None
  245. elif len(words) == 1 and type_re.match(words[0]):
  246. detail = words[0]
  247. else:
  248. return None
  249. return modifiers, type, detail
  250. def _triplet_to_sequence(triplet):
  251. if triplet[2]:
  252. return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'-'+ \
  253. triplet[2]+'>'
  254. else:
  255. return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'>'
  256. _multicall_dict = {}
  257. def MultiCallCreator(widget):
  258. """Return a MultiCall class which inherits its methods from the
  259. given widget class (for example, Tkinter.Text). This is used
  260. instead of a templating mechanism.
  261. """
  262. if widget in _multicall_dict:
  263. return _multicall_dict[widget]
  264. class MultiCall (widget):
  265. assert issubclass(widget, Tkinter.Misc)
  266. def __init__(self, *args, **kwargs):
  267. apply(widget.__init__, (self,)+args, kwargs)
  268. # a dictionary which maps a virtual event to a tuple with:
  269. # 0. the function binded
  270. # 1. a list of triplets - the sequences it is binded to
  271. self.__eventinfo = {}
  272. self.__binders = [_binder_classes[i](i, widget, self)
  273. for i in range(len(_types))]
  274. def bind(self, sequence=None, func=None, add=None):
  275. #print "bind(%s, %s, %s) called." % (sequence, func, add)
  276. if type(sequence) is str and len(sequence) > 2 and \
  277. sequence[:2] == "<<" and sequence[-2:] == ">>":
  278. if sequence in self.__eventinfo:
  279. ei = self.__eventinfo[sequence]
  280. if ei[0] is not None:
  281. for triplet in ei[1]:
  282. self.__binders[triplet[1]].unbind(triplet, ei[0])
  283. ei[0] = func
  284. if ei[0] is not None:
  285. for triplet in ei[1]:
  286. self.__binders[triplet[1]].bind(triplet, func)
  287. else:
  288. self.__eventinfo[sequence] = [func, []]
  289. return widget.bind(self, sequence, func, add)
  290. def unbind(self, sequence, funcid=None):
  291. if type(sequence) is str and len(sequence) > 2 and \
  292. sequence[:2] == "<<" and sequence[-2:] == ">>" and \
  293. sequence in self.__eventinfo:
  294. func, triplets = self.__eventinfo[sequence]
  295. if func is not None:
  296. for triplet in triplets:
  297. self.__binders[triplet[1]].unbind(triplet, func)
  298. self.__eventinfo[sequence][0] = None
  299. return widget.unbind(self, sequence, funcid)
  300. def event_add(self, virtual, *sequences):
  301. #print "event_add(%s,%s) was called"%(repr(virtual),repr(sequences))
  302. if virtual not in self.__eventinfo:
  303. self.__eventinfo[virtual] = [None, []]
  304. func, triplets = self.__eventinfo[virtual]
  305. for seq in sequences:
  306. triplet = _parse_sequence(seq)
  307. if triplet is None:
  308. #print >> sys.stderr, "Seq. %s was added by Tkinter."%seq
  309. widget.event_add(self, virtual, seq)
  310. else:
  311. if func is not None:
  312. self.__binders[triplet[1]].bind(triplet, func)
  313. triplets.append(triplet)
  314. def event_delete(self, virtual, *sequences):
  315. if virtual not in self.__eventinfo:
  316. return
  317. func, triplets = self.__eventinfo[virtual]
  318. for seq in sequences:
  319. triplet = _parse_sequence(seq)
  320. if triplet is None:
  321. #print >> sys.stderr, "Seq. %s was deleted by Tkinter."%seq
  322. widget.event_delete(self, virtual, seq)
  323. else:
  324. if func is not None:
  325. self.__binders[triplet[1]].unbind(triplet, func)
  326. triplets.remove(triplet)
  327. def event_info(self, virtual=None):
  328. if virtual is None or virtual not in self.__eventinfo:
  329. return widget.event_info(self, virtual)
  330. else:
  331. return tuple(map(_triplet_to_sequence,
  332. self.__eventinfo[virtual][1])) + \
  333. widget.event_info(self, virtual)
  334. def __del__(self):
  335. for virtual in self.__eventinfo:
  336. func, triplets = self.__eventinfo[virtual]
  337. if func:
  338. for triplet in triplets:
  339. self.__binders[triplet[1]].unbind(triplet, func)
  340. _multicall_dict[widget] = MultiCall
  341. return MultiCall
  342. if __name__ == "__main__":
  343. # Test
  344. root = Tkinter.Tk()
  345. text = MultiCallCreator(Tkinter.Text)(root)
  346. text.pack()
  347. def bindseq(seq, n=[0]):
  348. def handler(event):
  349. print seq
  350. text.bind("<<handler%d>>"%n[0], handler)
  351. text.event_add("<<handler%d>>"%n[0], seq)
  352. n[0] += 1
  353. bindseq("<Key>")
  354. bindseq("<Control-Key>")
  355. bindseq("<Alt-Key-a>")
  356. bindseq("<Control-Key-a>")
  357. bindseq("<Alt-Control-Key-a>")
  358. bindseq("<Key-b>")
  359. bindseq("<Control-Button-1>")
  360. bindseq("<Alt-Button-1>")
  361. bindseq("<FocusOut>")
  362. bindseq("<Enter>")
  363. bindseq("<Leave>")
  364. root.mainloop()