-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmenu.py
383 lines (292 loc) · 13.2 KB
/
menu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's Menu Model (encapsulates wx.MenuBar, wx.Menu and wx.MenuItems)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart"
__license__ = "LGPL 3.0"
# Initial implementation was inspired on PythonCard's menu module, altought
# it was almost completely discarded and re-written from scratch to make it
# simpler and cleaner, following the general gui2py component object model
# Note: some wx stubs ("dummy window") where necessary for this simplification
import wx
from .event import FormEvent
from .component import Component, Spec, StyleSpec, EventSpec, InitSpec, DimensionSpec
from . import images
from . import registry
DEBUG = False
class wx_DummyWindow:
"Class to emulate (and normalize) menues in wx whit gui object model"
# if using custom-draw menues (agw.FlatMenu) this would not be necesary
# (so wx_Menu* could be replaced someday..)
# note that wx ignores dimension and almost all event on menus
# Font and Background/Textcolour seems to work only on MSW
def __init__(self, parent, *args, **kwargs):
self.parent = parent
def GetParent(self):
return self.parent
def Reparent(self, new_parent):
self.parent = new_parent
def GetSize(self):
return [-1, -1]
GetSizeTuple = GetClientSize = GetSize
GetPositionTuple = GetSizeTuple
def GetCharWidth(self):
return 0
def GetCharHeight(self):
return 0
def Dummy(self, *args, **kwargs):
pass
Show = SetSize = Refresh = Move = SetToolTip = Dummy
SetClientSize = Dummy
IsShown = lambda self: True
def Bind(self, evt, handler, id=None):
# this should reach top level window:
if evt == wx.EVT_SIZE:
pass
else:
if DEBUG: print "binding MENU", self.__class__.__name__, id, handler
self.parent.Bind(evt, handler, id=id or self.GetId())
def Unbind(self, evt, id=None):
if DEBUG: print "unbinding MENU", self.Text, self.GetId()
self.parent.Unbind(evt, id=id or self.GetId())
class wx_MenuItem(wx_DummyWindow, wx.MenuItem):
def __init__(self, parent, *args, **kwargs):
wx_DummyWindow.__init__(self, parent, *args, **kwargs)
wx.MenuItem.__init__(self, parentMenu=parent,
id=kwargs['id'],
text=kwargs['label'],
kind=kwargs['style'],
#subMenu=None,
)
if self.GetKind() == wx.ITEM_SEPARATOR:
self.parent.AppendSeparator() # do not use AppendItem on MSW
#elif self.GetKind() == wx.ITEM_CHECK:
# self.parent.AppendCheckItem(wx.NewId(), self.GetText())
else:
# in phoenix (2.9.5), kwargs is helpString, so set it here:
self.SetHelp(kwargs['help'])
self.parent.AppendItem(self)
def Enable(self, value):
# avoid assertion in Enable: invalid menu item
if not self.GetKind() == wx.ITEM_SEPARATOR:
wx.MenuItem.Enable(self, value)
def Destroy(self):
self.parent.RemoveItem(self)
wx.MenuItem.Destroy(self)
def Check(self, value):
# avoid assertion in Check(): invalid menu item
if self.GetKind() == wx.ITEM_CHECK:
wx.MenuItem.Check(self, value)
GetForegroundColour = wx.MenuItem.GetTextColour
SetForegroundColour = wx.MenuItem.SetTextColour
class MenuItem(Component):
"A MenuItem represents one selectable item in a Menu"
_wx_class = wx_MenuItem
_registry = registry.MENU
label = InitSpec(lambda self: self.wx_obj.GetText(),
lambda self, label: self.wx_obj.SetText(label),
optional=False, default='MenuItem', type="string",
doc="text to show as caption")
help = InitSpec(lambda self: self.wx_obj.GetHelp(),
lambda self, label: self.wx_obj.SetHelp(label),
optional=True, default='', type="string",
doc="text to show as help in the status bar?")
onclick = EventSpec('click', binding=wx.EVT_MENU, kind=FormEvent)
def rebuild(self, **kwargs):
# avoid recreating the object (not supported yet!)
Component.rebuild(self, False, **kwargs)
class MenuItemCheckable(MenuItem):
"A MenuItem represents one selectable item in a Menu"
_wx_class = wx_MenuItem
_registry = registry.MENU
_style = wx.ITEM_CHECK
checked = Spec(lambda self: self.wx_obj.IsChecked(),
lambda self, value: self.wx_obj.Check(value),
default=False, type="boolean")
class MenuItemSeparator(MenuItem):
_style = wx.ITEM_SEPARATOR
class wx_Menu(wx_DummyWindow, wx.Menu):
def __init__(self, parent, *args, **kwargs):
wx_DummyWindow.__init__(self, parent, *args, **kwargs)
# if this is a popup menu, call constructor with:
# kwargs.get("label"), kwargs.get("style")
wx.Menu.__init__(self)
if isinstance(parent, wx.MenuBar):
self.parent.Append(self, kwargs.get("label"))
else:
self.parent.AppendSubMenu(submenu=self,
text=kwargs.get("label"))
id = self.parent.GetLastId()
self.GetId = lambda: id
def Destroy(self):
if isinstance(self.parent, wx.MenuBar):
self.parent.RemoveItem(self)
else:
self.parent.Remove(self.GetId())
try:
wx.Menu.Destroy(self)
except TypeError:
# we were removed! ignore "got _wxPyDeadObject instance instead"
pass
# unsupported methods:
GetBackgroundColour = SetBackgroundColour = wx_DummyWindow.Dummy
SetFont = wx_DummyWindow.Dummy
GetFont = lambda self: wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
GetForegroundColour = lambda self: 'black'
SetForegroundColour = wx_DummyWindow.Dummy
def Enable(self, value):
"enable or disable all menu items"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
it.Enable(value)
def IsEnabled(self, *args, **kwargs):
"check if all menu items are enabled"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
if not it.IsEnabled():
return False
return True
def SetItemLabel(self, menu, label):
#return #return menu.GetTitle()
id = menu.GetId()
print "MENUID", id
self.SetLabel(id, label)
#menu.SetLabel(menu.GetTitle())
pass
def GetItemLabel(self, menu):
#return menu.GetTitle()
try:
return self.GetLabel(menu.GetId())
except:
import pdb; pdb.set_trace()
def GetLastId(self):
return list(self.GetMenuItems())[-1].GetId()
class Menu(Component):
"A Menu contains 0..n MenuItem objects."
_wx_class = wx_Menu
_registry = registry.MENU
def _set_label(self, value):
# note that wx.Menu.SetTitle() does not work on gtk for menubars
#self.wx_obj.SetTitle(value) # do not use SetTitle (in msw is shown)
self.wx_obj.parent.SetItemLabel(self.wx_obj, value)
def _get_label(self):
# note that wx.Menu.GetTitle() does not work on windows for menubars
return self.wx_obj.parent.GetItemLabel(self.wx_obj)
def find(self, item_id=None):
"Recursively find a menu item by its id (useful for event handlers)"
for it in self:
if it.id == item_id:
return it
elif isinstance(it, Menu):
found = it.find(item_id)
if found:
return found
def rebuild(self, **kwargs):
# avoid recreating the object (not supported yet!)
Component.rebuild(self, False, **kwargs)
label = InitSpec(_get_label, _set_label,
optional=False, default='Menu', type="string",
doc="text to show as caption")
class wx_MenuBar(wx_DummyWindow, wx.MenuBar):
def __init__(self, parent, *args, **kwargs):
# it should receive (self, parent, id, pos, size, style, name)
# but it doesnt!
# TypeError: new_MenuBar() takes at most 1 argument (7 given)
wx_DummyWindow.__init__(self, parent, *args, **kwargs)
wx.MenuBar.__init__(self)
# unsupported methods:
GetBackgroundColour = SetBackgroundColour = wx_DummyWindow.Dummy
SetFont = wx_DummyWindow.Dummy
GetFont = lambda self: wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
GetForegroundColour = lambda self: 'black'
SetForegroundColour = wx_DummyWindow.Dummy
def Enable(self, value):
"enable or disable all top menus"
for i in range(self.GetMenuCount()):
self.EnableTop(i, value)
def IsEnabled(self, *args, **kwargs):
"check if all top menus are enabled"
for i in range(self.GetMenuCount()):
if not self.IsEnabledTop(i):
return False
return True
def RemoveItem(self, menu):
"Helper method to remove a menu avoiding using its position"
menus = self.GetMenus() # get the list of (menu, title)
menus = [submenu for submenu in menus if submenu[0] != menu]
self.SetMenus(menus)
def SetItemLabel(self, menu, label):
menus = self.GetMenus() # get the list of (menu, title)
pos = [submenu[0] for submenu in menus].index(menu)
self.SetMenuLabel(pos, label)
def GetItemLabel(self, menu):
menus = self.GetMenus() # get the list of (menu, title)
for submenu, title in menus:
if submenu == menu:
return title
def GetLastId(self):
return -1 #self.GetMenus()[-1][0].GetId()
class MenuBar(Component):
_wx_class = wx_MenuBar
_image = images.menubar
_registry = registry.CONTROLS
def __init__(self, *args, **kwargs):
Component.__init__(self, *args, **kwargs)
if hasattr(self, "_designer") and self.designer:
# create a basic menu
id = wx.NewId()
m = Menu(self, label='Menu', name="menu_%s" % id, id=id)
id = wx.NewId()
mi = MenuItem(m, label='MenuItem', name='menu_item_%s' % id, id=id)
mi.designer = self.designer
self._parent.menubar = self # add the menubar to the window
def set_parent(self, new_parent, init=False):
Component.set_parent(self, new_parent, init)
# if new_parent is rebuild, reparent (even to None) to avoid segv:
if not init:
wx_obj = new_parent and new_parent.wx_obj
self.wx_obj.Reparent(wx_obj)
def find(self, item_id=None):
"Recursively find a menu item by its id (useful for event handlers)"
for it in self:
found = it.find(item_id)
if found:
return found
# update metadata for the add context menu at the designer:
MenuBar._meta.valid_children = [Menu, ]
Menu._meta.valid_children = [MenuItem, MenuItemCheckable, MenuItemSeparator, Menu]
# Unit Test
if __name__ == '__main__' :
import sys, os
# disable ubuntu unity menubar
os.environ['UBUNTU_MENUPROXY'] = '0'
app = wx.App(redirect=False)
from gui.windows import Window
w = Window(title="hello world", name="frmTest", tool_window=False,
resizable=True, visible=False, pos=(180, 0))
mb = MenuBar(w, name="menubar")
m1 = Menu(mb, label='File', name="mnu_file")
mi11 = MenuItem(m1, label='Open', name='menu_file_open')
mi12 = MenuItem(m1, label='Save', name='menu_file_save', enabled=False)
mi13 = MenuItem(m1, label='Quit', name='menu_file_quit')
m11 = Menu(m1, label='Recent files', name="mnu_recent_file")
mi111 = MenuItem(m11, label='file1', name='menu_recent_file1')
mi112 = MenuItem(m11, label='file2', name='menu_recent_file2')
mi113 = MenuItem(m11, label='file3', name='menu_recent_file3')
m2 = Menu(mb, label='Edit', name="mnu_edit")
mi21 = MenuItem(m2, label='Copy', name='menu_edit_copy')
mi22 = MenuItem(m2, label='Cut', name='menu_edit_cut')
mi23 = MenuItem(m2, label='Paste', name='menu_edit_paste')
m2.enabled = False # disable a whole menu
def disable_all(event):
mb.enabled = False # disable the menubar
def enable_edit(event):
m2.enabled = not m2.enabled
mi11.label = "Close" if m2.enabled else "Open"
mi12.enabled = not mi12.enabled
mi11.onclick = enable_edit
mi13.onclick = disable_all
from gui.tools.inspector import InspectorTool
InspectorTool().show(w)
w.show()
app.MainLoop()