toolbars.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 IMGDIR
  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. class MyToolbar(BaseToolbar):
  79. def __init__(self, parent):
  80. BaseToolbar.__init__(self, parent)
  81. self.InitToolbar(self._toolbarData())
  82. self.Realize()
  83. def _toolbarData(self):
  84. return self._getToolbarData((("help", Icons["help"],
  85. self.parent.OnHelp),
  86. ))
  87. """
  88. def __init__(self, parent, toolSwitcher=None, style=wx.NO_BORDER|wx.TB_HORIZONTAL):
  89. self.parent = parent
  90. wx.ToolBar.__init__(self, parent=self.parent, id=wx.ID_ANY,
  91. style=style)
  92. self._default = None
  93. self.SetToolBitmapSize(globalvar.toolbarSize)
  94. self.toolSwitcher = toolSwitcher
  95. self.handlers = {}
  96. def InitToolbar(self, toolData):
  97. """Initialize toolbar, add tools to the toolbar
  98. """
  99. for tool in toolData:
  100. self.CreateTool(*tool)
  101. self._data = toolData
  102. def _toolbarData(self):
  103. """Toolbar data (virtual)"""
  104. return None
  105. def CreateTool(self, label, bitmap, kind,
  106. shortHelp, longHelp, handler, pos = -1):
  107. """Add tool to the toolbar
  108. :param pos: if -1 add tool, if > 0 insert at given pos
  109. :return: id of tool
  110. """
  111. bmpDisabled = wx.NullBitmap
  112. tool = -1
  113. if label:
  114. tool = vars(self)[label] = wx.NewId()
  115. Debug.msg(3, "CreateTool(): tool=%d, label=%s bitmap=%s" % \
  116. (tool, label, bitmap))
  117. if pos < 0:
  118. toolWin = self.AddLabelTool(tool, label, bitmap,
  119. bmpDisabled, kind,
  120. shortHelp, longHelp)
  121. else:
  122. toolWin = self.InsertLabelTool(pos, tool, label, bitmap,
  123. bmpDisabled, kind,
  124. shortHelp, longHelp)
  125. self.handlers[tool] = handler
  126. self.Bind(wx.EVT_TOOL, handler, toolWin)
  127. self.Bind(wx.EVT_TOOL, self.OnTool, toolWin)
  128. else: # separator
  129. self.AddSeparator()
  130. return tool
  131. def EnableLongHelp(self, enable = True):
  132. """Enable/disable long help
  133. :param enable: True for enable otherwise disable
  134. """
  135. for tool in self._data:
  136. if tool[0] == '': # separator
  137. continue
  138. if enable:
  139. self.SetToolLongHelp(vars(self)[tool[0]], tool[4])
  140. else:
  141. self.SetToolLongHelp(vars(self)[tool[0]], "")
  142. def OnTool(self, event):
  143. """Tool selected
  144. """
  145. if self.toolSwitcher:
  146. Debug.msg(3, "BaseToolbar.OnTool(): id = %s" % event.GetId())
  147. self.toolSwitcher.ToolChanged(event.GetId())
  148. event.Skip()
  149. def SelectTool(self, id):
  150. self.ToggleTool(id, True)
  151. self.toolSwitcher.ToolChanged(id)
  152. self.handlers[id](event=None)
  153. def SelectDefault(self):
  154. """Select default tool"""
  155. self.SelectTool(self._default)
  156. def FixSize(self, width):
  157. """Fix toolbar width on Windows
  158. .. todo::
  159. Determine why combobox causes problems here
  160. """
  161. if platform.system() == 'Windows':
  162. size = self.GetBestSize()
  163. self.SetSize((size[0] + width, size[1]))
  164. def Enable(self, tool, enable = True):
  165. """Enable/Disable defined tool
  166. :param tool: name
  167. :param enable: True to enable otherwise disable tool
  168. """
  169. try:
  170. id = getattr(self, tool)
  171. except AttributeError:
  172. # TODO: test everything that this is not raised
  173. # this error was ignored for a long time
  174. raise AttributeError("Toolbar does not have a tool %s." % tool)
  175. return
  176. self.EnableTool(id, enable)
  177. def EnableAll(self, enable = True):
  178. """Enable/Disable all tools
  179. :param enable: True to enable otherwise disable tool
  180. """
  181. for item in self._toolbarData():
  182. if not item[0]:
  183. continue
  184. self.Enable(item[0], enable)
  185. def _getToolbarData(self, data):
  186. """Define tool
  187. """
  188. retData = list()
  189. for args in data:
  190. retData.append(self._defineTool(*args))
  191. return retData
  192. def _defineTool(self, name = None, icon = None, handler = None, item = wx.ITEM_NORMAL, pos = -1):
  193. """Define tool
  194. """
  195. if name:
  196. return (name, icon.GetBitmap(),
  197. item, icon.GetLabel(), icon.GetDesc(),
  198. handler, pos)
  199. return ("", "", "", "", "", "") # separator
  200. def _onMenu(self, data):
  201. """Toolbar pop-up menu"""
  202. menu = wx.Menu()
  203. for icon, handler in data:
  204. item = wx.MenuItem(menu, wx.ID_ANY, icon.GetLabel())
  205. item.SetBitmap(icon.GetBitmap(self.parent.iconsize))
  206. menu.AppendItem(item)
  207. self.Bind(wx.EVT_MENU, handler, item)
  208. self.PopupMenu(menu)
  209. menu.Destroy()
  210. def CreateSelectionButton(self, tooltip = _("Select graphics tool")):
  211. """Add button to toolbar for selection of graphics drawing mode.
  212. Button must be custom (not toolbar tool) to set smaller width.
  213. """
  214. arrowPath = os.path.join(IMGDIR, 'small_down_arrow.png')
  215. if os.path.isfile(arrowPath) and os.path.getsize(arrowPath):
  216. bitmap = wx.Bitmap(name = arrowPath)
  217. else:
  218. bitmap = wx.ArtProvider.GetBitmap(id = wx.ART_MISSING_IMAGE, client = wx.ART_TOOLBAR)
  219. button = wx.BitmapButton(parent=self, id=wx.ID_ANY, size=((-1, self.GetToolSize()[1])),
  220. bitmap=bitmap, style=wx.NO_BORDER)
  221. button.SetToolTipString(tooltip)
  222. return button
  223. class ToolSwitcher:
  224. """Class handling switching tools in toolbar and custom toggle buttons."""
  225. def __init__(self):
  226. self._groups = defaultdict(lambda: defaultdict(list))
  227. self._toolsGroups = defaultdict(list)
  228. # emitted when tool is changed
  229. self.toggleToolChanged = Signal('ToolSwitcher.toggleToolChanged')
  230. def AddToolToGroup(self, group, toolbar, tool):
  231. """Adds tool from toolbar to group of exclusive tools.
  232. :param group: name of group (e.g. 'mouseUse')
  233. :param toolbar: instance of toolbar
  234. :param tool: id of a tool from the toolbar
  235. """
  236. self._groups[group][toolbar].append(tool)
  237. self._toolsGroups[tool].append(group)
  238. def AddCustomToolToGroup(self, group, btnId, toggleHandler):
  239. """Adds custom tool from to group of exclusive tools (some toggle button).
  240. :param group: name of group (e.g. 'mouseUse')
  241. :param btnId: id of a tool (typically button)
  242. :param toggleHandler: handler to be called to switch the button
  243. """
  244. self._groups[group]['custom'].append((btnId, toggleHandler))
  245. self._toolsGroups[btnId].append(group)
  246. def RemoveCustomToolFromGroup(self, tool):
  247. """Removes custom tool from group.
  248. :param tool: id of the button
  249. """
  250. if not tool in self._toolsGroups:
  251. return
  252. for group in self._toolsGroups[tool]:
  253. self._groups[group]['custom'] = \
  254. [(bid, hdlr) for (bid, hdlr)
  255. in self._groups[group]['custom'] if bid != tool]
  256. def RemoveToolbarFromGroup(self, group, toolbar):
  257. """Removes toolbar from group.
  258. Before toolbar is destroyed, it must be removed from group, too.
  259. Otherwise we can expect some DeadObject errors.
  260. :param group: name of group (e.g. 'mouseUse')
  261. :param toolbar: instance of toolbar
  262. """
  263. for tb in self._groups[group]:
  264. if tb == toolbar:
  265. del self._groups[group][tb]
  266. break
  267. def IsToolInGroup(self, tool, group):
  268. """Checks whether a tool is in a specified group.
  269. :param tool: tool id
  270. :param group: name of group (e.g. 'mouseUse')
  271. """
  272. for group in self._toolsGroups[tool]:
  273. for tb in self._groups[group]:
  274. if tb.FindById(tool):
  275. return True
  276. return False
  277. def ToolChanged(self, tool):
  278. """When any tool/button is pressed, other tools from group must be unchecked.
  279. :param tool: id of a tool/button
  280. """
  281. for group in self._toolsGroups[tool]:
  282. for tb in self._groups[group]:
  283. if tb == 'custom':
  284. for btnId, handler in self._groups[group][tb]:
  285. if btnId != tool:
  286. handler(False)
  287. else:
  288. for tl in self._groups[group][tb]:
  289. if tb.FindById(tl): # check if still exists
  290. if tl != tool:
  291. tb.ToggleTool(tl, False)
  292. else:
  293. tb.ToggleTool(tool, True)
  294. self.toggleToolChanged.emit(id=tool)