toolbars.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. """!
  2. @package iclass.toolbars
  3. @brief wxIClass toolbars and icons.
  4. Classes:
  5. - toolbars::IClassMapToolbar
  6. - toolbars::IClassToolbar
  7. - toolbars::IClassMapManagerToolbar
  8. - toolbars::IClassMiscToolbar
  9. (C) 2006-2011 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Vaclav Petras <wenzeslaus gmail.com>
  14. @author Anna Kratochvilova <kratochanna gmail.com>
  15. """
  16. import wx
  17. from core.utils import _
  18. from gui_core.toolbars import BaseToolbar, BaseIcons
  19. from icons.icon import MetaIcon
  20. from iclass.dialogs import IClassMapDialog, ContrastColor
  21. from gui_core.forms import GUI
  22. import grass.script as grass
  23. iClassIcons = {
  24. 'opacity' : MetaIcon(img = 'layer-opacity',
  25. label = _('Set opacity level')),
  26. 'classManager' : MetaIcon(img = 'table-manager',
  27. label = _('Class manager')),
  28. 'selectGroup' : MetaIcon(img = 'layer-group-add',
  29. label = _('Select imagery group')),
  30. 'run' : MetaIcon(img = 'execute',
  31. label = _('Run analysis')),
  32. 'sigFile' : MetaIcon(img = 'script-save',
  33. label = _('Save signature file')),
  34. 'delCmd' : MetaIcon(img = 'layer-remove',
  35. label = _('Remove selected map layer')),
  36. 'exportAreas' : MetaIcon(img = 'layer-export',
  37. label = _('Export training areas to vector map')),
  38. 'importAreas' : MetaIcon(img = 'layer-import',
  39. label = _('Import training areas from vector map')),
  40. 'addRgb' : MetaIcon(img = 'layer-rgb-add',
  41. label = _('Add RGB map layer'))
  42. }
  43. class IClassMapToolbar(BaseToolbar):
  44. """!IClass Map toolbar
  45. """
  46. def __init__(self, parent, toolSwitcher):
  47. """!IClass Map toolbar constructor
  48. """
  49. BaseToolbar.__init__(self, parent, toolSwitcher)
  50. self.InitToolbar(self._toolbarData())
  51. self._default = self.pan
  52. # add tool to toggle active map window
  53. self.togglemapid = wx.NewId()
  54. self.togglemap = wx.Choice(parent = self, id = self.togglemapid,
  55. choices = [_('Training'), _('Preview')])
  56. self.InsertControl(9, self.togglemap)
  57. self.SetToolShortHelp(self.togglemapid, '%s %s %s' % (_('Set map canvas for '),
  58. BaseIcons["zoomBack"].GetLabel(),
  59. _('/ Zoom to map')))
  60. for tool in (self.pan, self.zoomIn, self.zoomOut):
  61. self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
  62. # realize the toolbar
  63. self.Realize()
  64. self.EnableTool(self.zoomBack, False)
  65. def GetActiveMapTool(self):
  66. """!Return widget for selecting active maps"""
  67. return self.togglemap
  68. def GetActiveMap(self):
  69. """!Get currently selected map"""
  70. return self.togglemap.GetSelection()
  71. def SetActiveMap(self, index):
  72. """!Set currently selected map"""
  73. return self.togglemap.SetSelection(index)
  74. def _toolbarData(self):
  75. """!Toolbar data"""
  76. icons = BaseIcons
  77. return self._getToolbarData((("displaymap", icons["display"],
  78. self.parent.OnDraw),
  79. ("rendermap", icons["render"],
  80. self.parent.OnRender),
  81. ("erase", icons["erase"],
  82. self.parent.OnErase),
  83. (None, ),
  84. ("pan", icons["pan"],
  85. self.parent.OnPan,
  86. wx.ITEM_CHECK),
  87. ("zoomIn", icons["zoomIn"],
  88. self.parent.OnZoomIn,
  89. wx.ITEM_CHECK),
  90. ("zoomOut", icons["zoomOut"],
  91. self.parent.OnZoomOut,
  92. wx.ITEM_CHECK),
  93. ("zoomMenu", icons["zoomMenu"],
  94. self.parent.OnZoomMenu),
  95. (None, ),
  96. ("zoomBack", icons["zoomBack"],
  97. self.parent.OnZoomBack),
  98. ("zoomToMap", icons["zoomExtent"],
  99. self.parent.OnZoomToMap)
  100. ))
  101. class IClassToolbar(BaseToolbar):
  102. """!IClass toolbar
  103. """
  104. def __init__(self, parent, stats_data):
  105. """!IClass toolbar constructor
  106. """
  107. self.stats_data = stats_data
  108. BaseToolbar.__init__(self, parent)
  109. self.InitToolbar(self._toolbarData())
  110. self.choice = wx.Choice(parent = self, id = wx.ID_ANY, size = (110, -1))
  111. choiceid = self.InsertControl(3, self.choice)
  112. self.choice.Bind(wx.EVT_CHOICE, self.OnSelectCategory)
  113. # stupid workaround to insert small space between controls
  114. self.InsertControl(4, wx.StaticText(self, id = wx.ID_ANY, label = ' '))
  115. self.combo = wx.ComboBox(self, id = wx.ID_ANY, size = (130, -1),
  116. style = wx.TE_PROCESS_ENTER)
  117. self.InitStddev()
  118. comboid = self.InsertControl(5, self.combo)
  119. self.EnableControls(False)
  120. self.combo.Bind(wx.EVT_COMBOBOX, self.OnStdChangeSelection)
  121. self.combo.Bind(wx.EVT_TEXT_ENTER, self.OnStdChangeText)
  122. self.stats_data.statisticsAdded.connect(self.Update)
  123. self.stats_data.statisticsDeleted.connect(self.Update)
  124. self.stats_data.allStatisticsDeleted.connect(self.Update)
  125. self.stats_data.statisticsSet.connect(self.Update)
  126. # realize the toolbar
  127. self.Realize()
  128. def _toolbarData(self):
  129. """!Toolbar data"""
  130. icons = iClassIcons
  131. return self._getToolbarData((("selectGroup", icons['selectGroup'],
  132. lambda event : self.parent.AddBands()),
  133. (None, ),
  134. ("classManager", icons['classManager'],
  135. self.parent.OnCategoryManager),
  136. (None, ),
  137. ("runAnalysis", icons['run'],
  138. self.parent.OnRunAnalysis),
  139. (None, ),
  140. ("importAreas", icons['importAreas'],
  141. self.parent.OnImportAreas),
  142. ("exportAreas", icons['exportAreas'],
  143. self.parent.OnExportAreas),
  144. ("sigFile", icons['sigFile'],
  145. self.parent.OnSaveSigFile),
  146. ))
  147. def OnMotion(self, event):
  148. print self.choice.GetStringSelection()
  149. def OnSelectCategory(self, event):
  150. idx = self.choice.GetSelection()
  151. cat = self.choice.GetClientData(idx)
  152. self._updateColor(cat)
  153. self.parent.CategoryChanged(currentCat = cat)
  154. def _updateColor(self, cat):
  155. if cat:
  156. stat = self.stats_data.GetStatistics(cat)
  157. back_c = wx.Colour(*map(int, stat.color.split(':')))
  158. text_c = wx.Colour(*ContrastColor(back_c))
  159. else:
  160. back_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  161. text_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT)
  162. self.choice.SetForegroundColour(text_c)
  163. self.choice.SetBackgroundColour(back_c)
  164. def SetCategories(self, catNames, catIdx):
  165. self.choice.Clear()
  166. for name, idx in zip(catNames, catIdx):
  167. self.choice.Append(name, idx)
  168. def GetSelectedCategoryName(self):
  169. return self.choice.GetStringSelection()
  170. def GetSelectedCategoryIdx(self):
  171. idx = self.choice.GetSelection()
  172. if idx != wx.NOT_FOUND:
  173. return self.choice.GetClientData(idx)
  174. return None
  175. def OnStdChangeSelection(self, event):
  176. idx = self.combo.GetSelection()
  177. nstd = self.combo.GetClientData(idx)
  178. self.StddevChanged(nstd)
  179. def OnStdChangeText(self, event):
  180. val = self.combo.GetValue().strip()
  181. try:
  182. nstd = float(val)
  183. except ValueError:
  184. try:
  185. nstd = float(val.split()[0])
  186. except ValueError:
  187. nstd = None
  188. if nstd is not None:
  189. self.StddevChanged(nstd)
  190. def StddevChanged(self, nstd):
  191. idx = self.GetSelectedCategoryIdx()
  192. if not idx:
  193. return
  194. self.parent.StddevChanged(cat = idx, nstd = nstd)
  195. def UpdateStddev(self, nstd):
  196. self.combo.SetValue(' '.join(("%.2f" % nstd, _('std dev'))))
  197. def InitStddev(self):
  198. for nstd in range(50, 250, 25):
  199. nstd /= 100.
  200. self.combo.Append(item = ' '.join(("%.2f" % nstd, _('std dev'))), clientData = nstd)
  201. self.combo.SetSelection(4) # 1.5
  202. def EnableControls(self, enable = True):
  203. self.combo.Enable(enable)
  204. self.choice.Enable(enable)
  205. def Update(self, *args, **kwargs):
  206. name = self.GetSelectedCategoryName()
  207. catNames = []
  208. cats = self.stats_data.GetCategories()
  209. for cat in cats:
  210. stat = self.stats_data.GetStatistics(cat)
  211. catNames.append(stat.name)
  212. self.SetCategories(catNames = catNames, catIdx = cats)
  213. if name in catNames:
  214. self.choice.SetStringSelection(name)
  215. cat = self.GetSelectedCategoryIdx()
  216. elif catNames:
  217. self.choice.SetSelection(0)
  218. cat = self.GetSelectedCategoryIdx()
  219. else:
  220. cat = None
  221. if self.choice.IsEmpty():
  222. self.EnableControls(False)
  223. else:
  224. self.EnableControls(True)
  225. self._updateColor(cat)
  226. self.parent.CategoryChanged(cat)
  227. # don't forget to update maps, histo, ...
  228. class IClassMapManagerToolbar(BaseToolbar):
  229. """!IClass toolbar
  230. """
  231. def __init__(self, parent, mapManager):
  232. """!IClass toolbar constructor
  233. """
  234. BaseToolbar.__init__(self, parent)
  235. self.InitToolbar(self._toolbarData())
  236. self.choice = wx.Choice(parent = self, id = wx.ID_ANY, size = (300, -1))
  237. self.choiceid = self.AddControl(self.choice)
  238. self.choice.Bind(wx.EVT_CHOICE, self.OnSelectLayer)
  239. self.mapManager = mapManager
  240. # realize the toolbar
  241. self.Realize()
  242. def _toolbarData(self):
  243. """!Toolbar data"""
  244. return self._getToolbarData((("addRast", BaseIcons['addRast'],
  245. self.OnAddRast),
  246. ('addRgb', iClassIcons['addRgb'],
  247. self.OnAddRGB),
  248. ("delRast", iClassIcons['delCmd'],
  249. self.OnDelRast),
  250. ("setOpacity", iClassIcons['opacity'],
  251. self.OnSetOpacity),
  252. ))
  253. def OnSelectLayer(self, event):
  254. layer = self.choice.GetStringSelection()
  255. self.mapManager.SelectLayer(name = layer)
  256. def OnAddRast(self, event):
  257. dlg = IClassMapDialog(self, title = _("Add raster map"), element = 'raster')
  258. if dlg.ShowModal() == wx.ID_OK:
  259. raster = grass.find_file(name = dlg.GetMap(), element = 'cell')
  260. if raster['fullname']:
  261. self.mapManager.AddLayer(name = raster['fullname'])
  262. dlg.Destroy()
  263. def OnAddRGB(self, event):
  264. cmd = ['d.rgb']
  265. GUI(parent = self.parent).ParseCommand(cmd, completed = (self.GetOptData, '', ''))
  266. def GetOptData(self, dcmd, layer, params, propwin):
  267. if dcmd:
  268. self.mapManager.AddLayerRGB(cmd = dcmd)
  269. def OnDelRast(self, event):
  270. layer = self.choice.GetStringSelection()
  271. idx = self.choice.GetSelection()
  272. if layer:
  273. self.mapManager.RemoveLayer(name = layer, idx = idx)
  274. def OnSetOpacity(self, event):
  275. layer = self.choice.GetStringSelection()
  276. idx = self.choice.GetSelection()
  277. if idx == wx.NOT_FOUND:
  278. return
  279. self.mapManager.SetOpacity(name = layer)
  280. class IClassMiscToolbar(BaseToolbar):
  281. """!IClass toolbar
  282. """
  283. def __init__(self, parent):
  284. """!IClass toolbar constructor
  285. """
  286. BaseToolbar.__init__(self, parent)
  287. self.InitToolbar(self._toolbarData())
  288. # realize the toolbar
  289. self.Realize()
  290. def _toolbarData(self):
  291. """!Toolbar data"""
  292. icons = BaseIcons
  293. return self._getToolbarData((("help", icons['help'],
  294. self.parent.OnHelp),
  295. ("quit", icons['quit'],
  296. self.parent.OnCloseWindow),
  297. ))