PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/idlelib/MultiCall.py

https://bitbucket.org/kkris/pypy
Python | 422 lines | 312 code | 36 blank | 74 comment | 83 complexity | 2ed00190f4b33b96ec038de4887f1c20 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. from idlelib 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 = [''.join(m[0]+'-'
  98. for i, m in enumerate(_modifiers)
  99. if (1 << i) & s)
  100. for s in _states]
  101. def expand_substates(states):
  102. '''For each item of states return a list containing all combinations of
  103. that item with individual bits reset, sorted by the number of set bits.
  104. '''
  105. def nbits(n):
  106. "number of bits set in n base 2"
  107. nb = 0
  108. while n:
  109. n, rem = divmod(n, 2)
  110. nb += rem
  111. return nb
  112. statelist = []
  113. for state in states:
  114. substates = list(set(state & x for x in states))
  115. substates.sort(key=nbits, reverse=True)
  116. statelist.append(substates)
  117. return statelist
  118. _state_subsets = expand_substates(_states)
  119. # _state_codes gives for each state, the portable code to be passed as mc_state
  120. _state_codes = []
  121. for s in _states:
  122. r = 0
  123. for i in range(len(_modifiers)):
  124. if (1 << i) & s:
  125. r |= _modifier_masks[i]
  126. _state_codes.append(r)
  127. class _ComplexBinder:
  128. # This class binds many functions, and only unbinds them when it is deleted.
  129. # self.handlerids is the list of seqs and ids of binded handler functions.
  130. # The binded functions sit in a dictionary of lists of lists, which maps
  131. # a detail (or None) and a state into a list of functions.
  132. # When a new detail is discovered, handlers for all the possible states
  133. # are binded.
  134. def __create_handler(self, lists, mc_type, mc_state):
  135. def handler(event, lists = lists,
  136. mc_type = mc_type, mc_state = mc_state,
  137. ishandlerrunning = self.ishandlerrunning,
  138. doafterhandler = self.doafterhandler):
  139. ishandlerrunning[:] = [True]
  140. event.mc_type = mc_type
  141. event.mc_state = mc_state
  142. wascalled = {}
  143. r = None
  144. for l in lists:
  145. for i in range(len(l)-1, -1, -1):
  146. func = l[i]
  147. if func not in wascalled:
  148. wascalled[func] = True
  149. r = l[i](event)
  150. if r:
  151. break
  152. if r:
  153. break
  154. ishandlerrunning[:] = []
  155. # Call all functions in doafterhandler and remove them from list
  156. while doafterhandler:
  157. doafterhandler.pop()()
  158. if r:
  159. return r
  160. return handler
  161. def __init__(self, type, widget, widgetinst):
  162. self.type = type
  163. self.typename = _types[type][0]
  164. self.widget = widget
  165. self.widgetinst = widgetinst
  166. self.bindedfuncs = {None: [[] for s in _states]}
  167. self.handlerids = []
  168. # we don't want to change the lists of functions while a handler is
  169. # running - it will mess up the loop and anyway, we usually want the
  170. # change to happen from the next event. So we have a list of functions
  171. # for the handler to run after it finishes calling the binded functions.
  172. # It calls them only once.
  173. # ishandlerrunning is a list. An empty one means no, otherwise - yes.
  174. # this is done so that it would be mutable.
  175. self.ishandlerrunning = []
  176. self.doafterhandler = []
  177. for s in _states:
  178. lists = [self.bindedfuncs[None][i] for i in _state_subsets[s]]
  179. handler = self.__create_handler(lists, type, _state_codes[s])
  180. seq = '<'+_state_names[s]+self.typename+'>'
  181. self.handlerids.append((seq, self.widget.bind(self.widgetinst,
  182. seq, handler)))
  183. def bind(self, triplet, func):
  184. if triplet[2] not in self.bindedfuncs:
  185. self.bindedfuncs[triplet[2]] = [[] for s in _states]
  186. for s in _states:
  187. lists = [ self.bindedfuncs[detail][i]
  188. for detail in (triplet[2], None)
  189. for i in _state_subsets[s] ]
  190. handler = self.__create_handler(lists, self.type,
  191. _state_codes[s])
  192. seq = "<%s%s-%s>"% (_state_names[s], self.typename, triplet[2])
  193. self.handlerids.append((seq, self.widget.bind(self.widgetinst,
  194. seq, handler)))
  195. doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].append(func)
  196. if not self.ishandlerrunning:
  197. doit()
  198. else:
  199. self.doafterhandler.append(doit)
  200. def unbind(self, triplet, func):
  201. doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].remove(func)
  202. if not self.ishandlerrunning:
  203. doit()
  204. else:
  205. self.doafterhandler.append(doit)
  206. def __del__(self):
  207. for seq, id in self.handlerids:
  208. self.widget.unbind(self.widgetinst, seq, id)
  209. # define the list of event types to be handled by MultiEvent. the order is
  210. # compatible with the definition of event type constants.
  211. _types = (
  212. ("KeyPress", "Key"), ("KeyRelease",), ("ButtonPress", "Button"),
  213. ("ButtonRelease",), ("Activate",), ("Circulate",), ("Colormap",),
  214. ("Configure",), ("Deactivate",), ("Destroy",), ("Enter",), ("Expose",),
  215. ("FocusIn",), ("FocusOut",), ("Gravity",), ("Leave",), ("Map",),
  216. ("Motion",), ("MouseWheel",), ("Property",), ("Reparent",), ("Unmap",),
  217. ("Visibility",),
  218. )
  219. # which binder should be used for every event type?
  220. _binder_classes = (_ComplexBinder,) * 4 + (_SimpleBinder,) * (len(_types)-4)
  221. # A dictionary to map a type name into its number
  222. _type_names = dict([(name, number)
  223. for number in range(len(_types))
  224. for name in _types[number]])
  225. _keysym_re = re.compile(r"^\w+$")
  226. _button_re = re.compile(r"^[1-5]$")
  227. def _parse_sequence(sequence):
  228. """Get a string which should describe an event sequence. If it is
  229. successfully parsed as one, return a tuple containing the state (as an int),
  230. the event type (as an index of _types), and the detail - None if none, or a
  231. string if there is one. If the parsing is unsuccessful, return None.
  232. """
  233. if not sequence or sequence[0] != '<' or sequence[-1] != '>':
  234. return None
  235. words = string.split(sequence[1:-1], '-')
  236. modifiers = 0
  237. while words and words[0] in _modifier_names:
  238. modifiers |= 1 << _modifier_names[words[0]]
  239. del words[0]
  240. if words and words[0] in _type_names:
  241. type = _type_names[words[0]]
  242. del words[0]
  243. else:
  244. return None
  245. if _binder_classes[type] is _SimpleBinder:
  246. if modifiers or words:
  247. return None
  248. else:
  249. detail = None
  250. else:
  251. # _ComplexBinder
  252. if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]:
  253. type_re = _keysym_re
  254. else:
  255. type_re = _button_re
  256. if not words:
  257. detail = None
  258. elif len(words) == 1 and type_re.match(words[0]):
  259. detail = words[0]
  260. else:
  261. return None
  262. return modifiers, type, detail
  263. def _triplet_to_sequence(triplet):
  264. if triplet[2]:
  265. return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'-'+ \
  266. triplet[2]+'>'
  267. else:
  268. return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'>'
  269. _multicall_dict = {}
  270. def MultiCallCreator(widget):
  271. """Return a MultiCall class which inherits its methods from the
  272. given widget class (for example, Tkinter.Text). This is used
  273. instead of a templating mechanism.
  274. """
  275. if widget in _multicall_dict:
  276. return _multicall_dict[widget]
  277. class MultiCall (widget):
  278. assert issubclass(widget, Tkinter.Misc)
  279. def __init__(self, *args, **kwargs):
  280. widget.__init__(self, *args, **kwargs)
  281. # a dictionary which maps a virtual event to a tuple with:
  282. # 0. the function binded
  283. # 1. a list of triplets - the sequences it is binded to
  284. self.__eventinfo = {}
  285. self.__binders = [_binder_classes[i](i, widget, self)
  286. for i in range(len(_types))]
  287. def bind(self, sequence=None, func=None, add=None):
  288. #print "bind(%s, %s, %s) called." % (sequence, func, add)
  289. if type(sequence) is str and len(sequence) > 2 and \
  290. sequence[:2] == "<<" and sequence[-2:] == ">>":
  291. if sequence in self.__eventinfo:
  292. ei = self.__eventinfo[sequence]
  293. if ei[0] is not None:
  294. for triplet in ei[1]:
  295. self.__binders[triplet[1]].unbind(triplet, ei[0])
  296. ei[0] = func
  297. if ei[0] is not None:
  298. for triplet in ei[1]:
  299. self.__binders[triplet[1]].bind(triplet, func)
  300. else:
  301. self.__eventinfo[sequence] = [func, []]
  302. return widget.bind(self, sequence, func, add)
  303. def unbind(self, sequence, funcid=None):
  304. if type(sequence) is str and len(sequence) > 2 and \
  305. sequence[:2] == "<<" and sequence[-2:] == ">>" and \
  306. sequence in self.__eventinfo:
  307. func, triplets = self.__eventinfo[sequence]
  308. if func is not None:
  309. for triplet in triplets:
  310. self.__binders[triplet[1]].unbind(triplet, func)
  311. self.__eventinfo[sequence][0] = None
  312. return widget.unbind(self, sequence, funcid)
  313. def event_add(self, virtual, *sequences):
  314. #print "event_add(%s,%s) was called"%(repr(virtual),repr(sequences))
  315. if virtual not in self.__eventinfo:
  316. self.__eventinfo[virtual] = [None, []]
  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 added by Tkinter."%seq
  322. widget.event_add(self, virtual, seq)
  323. else:
  324. if func is not None:
  325. self.__binders[triplet[1]].bind(triplet, func)
  326. triplets.append(triplet)
  327. def event_delete(self, virtual, *sequences):
  328. if virtual not in self.__eventinfo:
  329. return
  330. func, triplets = self.__eventinfo[virtual]
  331. for seq in sequences:
  332. triplet = _parse_sequence(seq)
  333. if triplet is None:
  334. #print >> sys.stderr, "Seq. %s was deleted by Tkinter."%seq
  335. widget.event_delete(self, virtual, seq)
  336. else:
  337. if func is not None:
  338. self.__binders[triplet[1]].unbind(triplet, func)
  339. triplets.remove(triplet)
  340. def event_info(self, virtual=None):
  341. if virtual is None or virtual not in self.__eventinfo:
  342. return widget.event_info(self, virtual)
  343. else:
  344. return tuple(map(_triplet_to_sequence,
  345. self.__eventinfo[virtual][1])) + \
  346. widget.event_info(self, virtual)
  347. def __del__(self):
  348. for virtual in self.__eventinfo:
  349. func, triplets = self.__eventinfo[virtual]
  350. if func:
  351. for triplet in triplets:
  352. self.__binders[triplet[1]].unbind(triplet, func)
  353. _multicall_dict[widget] = MultiCall
  354. return MultiCall
  355. if __name__ == "__main__":
  356. # Test
  357. root = Tkinter.Tk()
  358. text = MultiCallCreator(Tkinter.Text)(root)
  359. text.pack()
  360. def bindseq(seq, n=[0]):
  361. def handler(event):
  362. print seq
  363. text.bind("<<handler%d>>"%n[0], handler)
  364. text.event_add("<<handler%d>>"%n[0], seq)
  365. n[0] += 1
  366. bindseq("<Key>")
  367. bindseq("<Control-Key>")
  368. bindseq("<Alt-Key-a>")
  369. bindseq("<Control-Key-a>")
  370. bindseq("<Alt-Control-Key-a>")
  371. bindseq("<Key-b>")
  372. bindseq("<Control-Button-1>")
  373. bindseq("<Alt-Button-1>")
  374. bindseq("<FocusOut>")
  375. bindseq("<Enter>")
  376. bindseq("<Leave>")
  377. root.mainloop()