toolbars.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. """!
  2. @package gui_core.toolbars
  3. @brief Base classes toolbar widgets
  4. Classes:
  5. - toolbars::BaseToolbar
  6. (C) 2007-2011 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Michael Barton
  10. @author Jachym Cepicky
  11. @author Martin Landa <landa.martin gmail.com>
  12. """
  13. import platform
  14. import wx
  15. from core import globalvar
  16. from core.debug import Debug
  17. from core.utils import _
  18. from icons.icon import MetaIcon
  19. from collections import defaultdict
  20. from grass.pydispatch.signal import Signal
  21. BaseIcons = {
  22. 'display' : MetaIcon(img = 'show',
  23. label = _('Display map'),
  24. desc = _('Re-render modified map layers only')),
  25. 'render' : MetaIcon(img = 'layer-redraw',
  26. label = _('Render map'),
  27. desc = _('Force re-rendering all map layers')),
  28. 'erase' : MetaIcon(img = 'erase',
  29. label = _('Erase display'),
  30. desc = _('Erase display canvas with given background color')),
  31. 'pointer' : MetaIcon(img = 'pointer',
  32. label = _('Pointer')),
  33. 'zoomIn' : MetaIcon(img = 'zoom-in',
  34. label = _('Zoom in'),
  35. desc = _('Drag or click mouse to zoom')),
  36. 'zoomOut' : MetaIcon(img = 'zoom-out',
  37. label = _('Zoom out'),
  38. desc = _('Drag or click mouse to unzoom')),
  39. 'zoomBack' : MetaIcon(img = 'zoom-last',
  40. label = _('Return to previous zoom')),
  41. 'zoomMenu' : MetaIcon(img = 'zoom-more',
  42. label = _('Various zoom options'),
  43. desc = _('Zoom to computational, default, saved region, ...')),
  44. 'zoomExtent' : MetaIcon(img = 'zoom-extent',
  45. label = _('Zoom to selected map layer(s)')),
  46. 'pan' : MetaIcon(img = 'pan',
  47. label = _('Pan'),
  48. desc = _('Drag with mouse to pan')),
  49. 'saveFile' : MetaIcon(img = 'map-export',
  50. label = _('Save display to graphic file')),
  51. 'print' : MetaIcon(img = 'print',
  52. label = _('Print display')),
  53. 'font' : MetaIcon(img = 'font',
  54. label = _('Select font')),
  55. 'help' : MetaIcon(img = 'help',
  56. label = _('Show manual')),
  57. 'quit' : MetaIcon(img = 'quit',
  58. label = _('Quit')),
  59. 'addRast' : MetaIcon(img = 'layer-raster-add',
  60. label = _('Add raster map layer')),
  61. 'addVect' : MetaIcon(img = 'layer-vector-add',
  62. label = _('Add vector map layer')),
  63. 'overlay' : MetaIcon(img = 'overlay-add',
  64. label = _('Add map elements'),
  65. desc = _('Overlay elements like scale and legend onto map')),
  66. 'histogramD' : MetaIcon(img = 'layer-raster-histogram',
  67. label = _('Create histogram with d.histogram')),
  68. 'settings' : MetaIcon(img = 'settings',
  69. label = _("Settings")),
  70. }
  71. class BaseToolbar(wx.ToolBar):
  72. """!Abstract toolbar class.
  73. Following code shows how to create new basic toolbar:
  74. @code
  75. class MyToolbar(BaseToolbar):
  76. def __init__(self, parent):
  77. BaseToolbar.__init__(self, parent)
  78. self.InitToolbar(self._toolbarData())
  79. self.Realize()
  80. def _toolbarData(self):
  81. return self._getToolbarData((("help", Icons["help"],
  82. self.parent.OnHelp),
  83. ))
  84. @endcode
  85. """
  86. def __init__(self, parent, toolSwitcher=None, style=wx.NO_BORDER|wx.TB_HORIZONTAL):
  87. self.parent = parent
  88. wx.ToolBar.__init__(self, parent=self.parent, id=wx.ID_ANY,
  89. style=style)
  90. self._default = None
  91. self.SetToolBitmapSize(globalvar.toolbarSize)
  92. self.toolSwitcher = toolSwitcher
  93. self.handlers = {}
  94. def InitToolbar(self, toolData):
  95. """!Initialize toolbar, add tools to the toolbar
  96. """
  97. for tool in toolData:
  98. self.CreateTool(*tool)
  99. self._data = toolData
  100. def _toolbarData(self):
  101. """!Toolbar data (virtual)"""
  102. return None
  103. def CreateTool(self, label, bitmap, kind,
  104. shortHelp, longHelp, handler, pos = -1):
  105. """!Add tool to the toolbar
  106. @param pos if -1 add tool, if > 0 insert at given pos
  107. @return id of tool
  108. """
  109. bmpDisabled = wx.NullBitmap
  110. tool = -1
  111. if label:
  112. tool = vars(self)[label] = wx.NewId()
  113. Debug.msg(3, "CreateTool(): tool=%d, label=%s bitmap=%s" % \
  114. (tool, label, bitmap))
  115. if pos < 0:
  116. toolWin = self.AddLabelTool(tool, label, bitmap,
  117. bmpDisabled, kind,
  118. shortHelp, longHelp)
  119. else:
  120. toolWin = self.InsertLabelTool(pos, tool, label, bitmap,
  121. bmpDisabled, kind,
  122. shortHelp, longHelp)
  123. self.handlers[tool] = handler
  124. self.Bind(wx.EVT_TOOL, handler, toolWin)
  125. self.Bind(wx.EVT_TOOL, self.OnTool, toolWin)
  126. else: # separator
  127. self.AddSeparator()
  128. return tool
  129. def EnableLongHelp(self, enable = True):
  130. """!Enable/disable long help
  131. @param enable True for enable otherwise disable
  132. """
  133. for tool in self._data:
  134. if tool[0] == '': # separator
  135. continue
  136. if enable:
  137. self.SetToolLongHelp(vars(self)[tool[0]], tool[4])
  138. else:
  139. self.SetToolLongHelp(vars(self)[tool[0]], "")
  140. def OnTool(self, event):
  141. """!Tool selected
  142. """
  143. if self.toolSwitcher:
  144. Debug.msg(3, "BaseToolbar.OnTool(): id = %s" % event.GetId())
  145. self.toolSwitcher.ToolChanged(event.GetId())
  146. event.Skip()
  147. def SelectTool(self, id):
  148. self.ToggleTool(id, True)
  149. self.toolSwitcher.ToolChanged(id)
  150. self.handlers[id](event=None)
  151. def SelectDefault(self):
  152. """!Select default tool"""
  153. self.SelectTool(self._default)
  154. def FixSize(self, width):
  155. """!Fix toolbar width on Windows
  156. @todo Determine why combobox causes problems here
  157. """
  158. if platform.system() == 'Windows':
  159. size = self.GetBestSize()
  160. self.SetSize((size[0] + width, size[1]))
  161. def Enable(self, tool, enable = True):
  162. """!Enable/Disable defined tool
  163. @param tool name
  164. @param enable True to enable otherwise disable tool
  165. """
  166. try:
  167. id = getattr(self, tool)
  168. except AttributeError:
  169. # TODO: test everything that this is not raised
  170. # this error was ignored for a long time
  171. raise AttributeError("Toolbar does not have a tool %s." % tool)
  172. return
  173. self.EnableTool(id, enable)
  174. def EnableAll(self, enable = True):
  175. """!Enable/Disable all tools
  176. @param enable True to enable otherwise disable tool
  177. """
  178. for item in self._toolbarData():
  179. if not item[0]:
  180. continue
  181. self.Enable(item[0], enable)
  182. def _getToolbarData(self, data):
  183. """!Define tool
  184. """
  185. retData = list()
  186. for args in data:
  187. retData.append(self._defineTool(*args))
  188. return retData
  189. def _defineTool(self, name = None, icon = None, handler = None, item = wx.ITEM_NORMAL, pos = -1):
  190. """!Define tool
  191. """
  192. if name:
  193. return (name, icon.GetBitmap(),
  194. item, icon.GetLabel(), icon.GetDesc(),
  195. handler, pos)
  196. return ("", "", "", "", "", "") # separator
  197. def _onMenu(self, data):
  198. """!Toolbar pop-up menu"""
  199. menu = wx.Menu()
  200. for icon, handler in data:
  201. item = wx.MenuItem(menu, wx.ID_ANY, icon.GetLabel())
  202. item.SetBitmap(icon.GetBitmap(self.parent.iconsize))
  203. menu.AppendItem(item)
  204. self.Bind(wx.EVT_MENU, handler, item)
  205. self.PopupMenu(menu)
  206. menu.Destroy()
  207. class ToolSwitcher:
  208. """!Class handling switching tools in toolbar and custom toggle buttons."""
  209. def __init__(self):
  210. self._groups = defaultdict(lambda: defaultdict(list))
  211. self._toolsGroups = defaultdict(list)
  212. # emitted when tool is changed
  213. self.toggleToolChanged = Signal('ToolSwitcher.toggleToolChanged')
  214. def AddToolToGroup(self, group, toolbar, tool):
  215. """!Adds tool from toolbar to group of exclusive tools.
  216. @param group name of group (e.g. 'mouseUse')
  217. @param toolbar instance of toolbar
  218. @param tool id of a tool from the toolbar
  219. """
  220. self._groups[group][toolbar].append(tool)
  221. self._toolsGroups[tool].append(group)
  222. def AddCustomToolToGroup(self, group, btnId, toggleHandler):
  223. """!Adds custom tool from to group of exclusive tools (some toggle button).
  224. @param group name of group (e.g. 'mouseUse')
  225. @param btnId id of a tool (typically button)
  226. @param toggleHandler handler to be called to switch the button
  227. """
  228. self._groups[group]['custom'].append((btnId, toggleHandler))
  229. self._toolsGroups[btnId].append(group)
  230. def RemoveCustomToolFromGroup(self, tool):
  231. """!Removes custom tool from group.
  232. @param tool id of the button
  233. """
  234. if not tool in self._toolsGroups:
  235. return
  236. for group in self._toolsGroups[tool]:
  237. self._groups[group]['custom'] = \
  238. [(bid, hdlr) for (bid, hdlr)
  239. in self._groups[group]['custom'] if bid != tool]
  240. def RemoveToolbarFromGroup(self, group, toolbar):
  241. """!Removes toolbar from group.
  242. Before toolbar is destroyed, it must be removed from group, too.
  243. Otherwise we can expect some DeadObject errors.
  244. @param group name of group (e.g. 'mouseUse')
  245. @param toolbar instance of toolbar
  246. """
  247. for tb in self._groups[group]:
  248. if tb == toolbar:
  249. del self._groups[group][tb]
  250. break
  251. def ToolChanged(self, tool):
  252. """!When any tool/button is pressed, other tools from group must be unchecked.
  253. @param tool id of a tool/button
  254. """
  255. for group in self._toolsGroups[tool]:
  256. for tb in self._groups[group]:
  257. if tb == 'custom':
  258. for btnId, handler in self._groups[group][tb]:
  259. if btnId != tool:
  260. handler(False)
  261. else:
  262. for tl in self._groups[group][tb]:
  263. if tb.FindById(tl): # check if still exists
  264. if tl != tool:
  265. tb.ToggleTool(tl, False)
  266. else:
  267. tb.ToggleTool(tool, True)
  268. self.toggleToolChanged.emit(id=tool)