toolbars.py 12 KB

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