toolbars.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. ("zoomRegion", icons["zoomRegion"],
  94. self.parent.OnZoomToWind),
  95. ("zoomMenu", icons["zoomMenu"],
  96. self.parent.OnZoomMenu),
  97. (None, ),
  98. ("zoomBack", icons["zoomBack"],
  99. self.parent.OnZoomBack),
  100. ("zoomToMap", icons["zoomExtent"],
  101. self.parent.OnZoomToMap)
  102. ))
  103. class IClassToolbar(BaseToolbar):
  104. """!IClass toolbar
  105. """
  106. def __init__(self, parent, stats_data):
  107. """!IClass toolbar constructor
  108. """
  109. self.stats_data = stats_data
  110. BaseToolbar.__init__(self, parent)
  111. self.InitToolbar(self._toolbarData())
  112. self.choice = wx.Choice(parent = self, id = wx.ID_ANY, size = (110, -1))
  113. choiceid = self.InsertControl(3, self.choice)
  114. self.choice.Bind(wx.EVT_CHOICE, self.OnSelectCategory)
  115. # stupid workaround to insert small space between controls
  116. self.InsertControl(4, wx.StaticText(self, id = wx.ID_ANY, label = ' '))
  117. self.combo = wx.ComboBox(self, id = wx.ID_ANY, size = (130, -1),
  118. style = wx.TE_PROCESS_ENTER)
  119. self.InitStddev()
  120. comboid = self.InsertControl(5, self.combo)
  121. self.EnableControls(False)
  122. self.combo.Bind(wx.EVT_COMBOBOX, self.OnStdChangeSelection)
  123. self.combo.Bind(wx.EVT_TEXT_ENTER, self.OnStdChangeText)
  124. self.stats_data.statisticsAdded.connect(self.Update)
  125. self.stats_data.statisticsDeleted.connect(self.Update)
  126. self.stats_data.allStatisticsDeleted.connect(self.Update)
  127. self.stats_data.statisticsSet.connect(self.Update)
  128. # realize the toolbar
  129. self.Realize()
  130. def _toolbarData(self):
  131. """!Toolbar data"""
  132. icons = iClassIcons
  133. return self._getToolbarData((("selectGroup", icons['selectGroup'],
  134. lambda event : self.parent.AddBands()),
  135. (None, ),
  136. ("classManager", icons['classManager'],
  137. self.parent.OnCategoryManager),
  138. (None, ),
  139. ("runAnalysis", icons['run'],
  140. self.parent.OnRunAnalysis),
  141. (None, ),
  142. ("importAreas", icons['importAreas'],
  143. self.parent.OnImportAreas),
  144. ("exportAreas", icons['exportAreas'],
  145. self.parent.OnExportAreas),
  146. ("sigFile", icons['sigFile'],
  147. self.parent.OnSaveSigFile),
  148. ))
  149. def OnMotion(self, event):
  150. print self.choice.GetStringSelection()
  151. def OnSelectCategory(self, event):
  152. idx = self.choice.GetSelection()
  153. cat = self.choice.GetClientData(idx)
  154. self._updateColor(cat)
  155. self.parent.CategoryChanged(currentCat = cat)
  156. def _updateColor(self, cat):
  157. if cat:
  158. stat = self.stats_data.GetStatistics(cat)
  159. back_c = wx.Colour(*map(int, stat.color.split(':')))
  160. text_c = wx.Colour(*ContrastColor(back_c))
  161. else:
  162. back_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  163. text_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT)
  164. self.choice.SetForegroundColour(text_c)
  165. self.choice.SetBackgroundColour(back_c)
  166. def SetCategories(self, catNames, catIdx):
  167. self.choice.Clear()
  168. for name, idx in zip(catNames, catIdx):
  169. self.choice.Append(name, idx)
  170. def GetSelectedCategoryName(self):
  171. return self.choice.GetStringSelection()
  172. def GetSelectedCategoryIdx(self):
  173. idx = self.choice.GetSelection()
  174. if idx != wx.NOT_FOUND:
  175. return self.choice.GetClientData(idx)
  176. return None
  177. def OnStdChangeSelection(self, event):
  178. idx = self.combo.GetSelection()
  179. nstd = self.combo.GetClientData(idx)
  180. self.StddevChanged(nstd)
  181. def OnStdChangeText(self, event):
  182. val = self.combo.GetValue().strip()
  183. try:
  184. nstd = float(val)
  185. except ValueError:
  186. try:
  187. nstd = float(val.split()[0])
  188. except ValueError:
  189. nstd = None
  190. if nstd is not None:
  191. self.StddevChanged(nstd)
  192. def StddevChanged(self, nstd):
  193. idx = self.GetSelectedCategoryIdx()
  194. if not idx:
  195. return
  196. self.parent.StddevChanged(cat = idx, nstd = nstd)
  197. def UpdateStddev(self, nstd):
  198. self.combo.SetValue(' '.join(("%.2f" % nstd, _('std dev'))))
  199. def InitStddev(self):
  200. for nstd in range(50, 250, 25):
  201. nstd /= 100.
  202. self.combo.Append(item = ' '.join(("%.2f" % nstd, _('std dev'))), clientData = nstd)
  203. self.combo.SetSelection(4) # 1.5
  204. def EnableControls(self, enable = True):
  205. self.combo.Enable(enable)
  206. self.choice.Enable(enable)
  207. def Update(self, *args, **kwargs):
  208. name = self.GetSelectedCategoryName()
  209. catNames = []
  210. cats = self.stats_data.GetCategories()
  211. for cat in cats:
  212. stat = self.stats_data.GetStatistics(cat)
  213. catNames.append(stat.name)
  214. self.SetCategories(catNames = catNames, catIdx = cats)
  215. if name in catNames:
  216. self.choice.SetStringSelection(name)
  217. cat = self.GetSelectedCategoryIdx()
  218. elif catNames:
  219. self.choice.SetSelection(0)
  220. cat = self.GetSelectedCategoryIdx()
  221. else:
  222. cat = None
  223. if self.choice.IsEmpty():
  224. self.EnableControls(False)
  225. else:
  226. self.EnableControls(True)
  227. self._updateColor(cat)
  228. self.parent.CategoryChanged(cat)
  229. # don't forget to update maps, histo, ...
  230. class IClassMapManagerToolbar(BaseToolbar):
  231. """!IClass toolbar
  232. """
  233. def __init__(self, parent, mapManager):
  234. """!IClass toolbar constructor
  235. """
  236. BaseToolbar.__init__(self, parent)
  237. self.InitToolbar(self._toolbarData())
  238. self.choice = wx.Choice(parent = self, id = wx.ID_ANY, size = (300, -1))
  239. self.choiceid = self.AddControl(self.choice)
  240. self.choice.Bind(wx.EVT_CHOICE, self.OnSelectLayer)
  241. self.mapManager = mapManager
  242. # realize the toolbar
  243. self.Realize()
  244. def _toolbarData(self):
  245. """!Toolbar data"""
  246. return self._getToolbarData((("addRast", BaseIcons['addRast'],
  247. self.OnAddRast),
  248. ('addRgb', iClassIcons['addRgb'],
  249. self.OnAddRGB),
  250. ("delRast", iClassIcons['delCmd'],
  251. self.OnDelRast),
  252. ("setOpacity", iClassIcons['opacity'],
  253. self.OnSetOpacity),
  254. ))
  255. def OnSelectLayer(self, event):
  256. layer = self.choice.GetStringSelection()
  257. self.mapManager.SelectLayer(name = layer)
  258. def OnAddRast(self, event):
  259. dlg = IClassMapDialog(self, title = _("Add raster map"), element = 'raster')
  260. if dlg.ShowModal() == wx.ID_OK:
  261. raster = grass.find_file(name = dlg.GetMap(), element = 'cell')
  262. if raster['fullname']:
  263. self.mapManager.AddLayer(name = raster['fullname'])
  264. dlg.Destroy()
  265. def OnAddRGB(self, event):
  266. cmd = ['d.rgb']
  267. GUI(parent = self.parent).ParseCommand(cmd, completed = (self.GetOptData, '', ''))
  268. def GetOptData(self, dcmd, layer, params, propwin):
  269. if dcmd:
  270. self.mapManager.AddLayerRGB(cmd = dcmd)
  271. def OnDelRast(self, event):
  272. layer = self.choice.GetStringSelection()
  273. idx = self.choice.GetSelection()
  274. if layer:
  275. self.mapManager.RemoveLayer(name = layer, idx = idx)
  276. def OnSetOpacity(self, event):
  277. layer = self.choice.GetStringSelection()
  278. idx = self.choice.GetSelection()
  279. if idx == wx.NOT_FOUND:
  280. return
  281. self.mapManager.SetOpacity(name = layer)
  282. class IClassMiscToolbar(BaseToolbar):
  283. """!IClass toolbar
  284. """
  285. def __init__(self, parent):
  286. """!IClass toolbar constructor
  287. """
  288. BaseToolbar.__init__(self, parent)
  289. self.InitToolbar(self._toolbarData())
  290. # realize the toolbar
  291. self.Realize()
  292. def _toolbarData(self):
  293. """!Toolbar data"""
  294. icons = BaseIcons
  295. return self._getToolbarData((("help", icons['help'],
  296. self.parent.OnHelp),
  297. ("quit", icons['quit'],
  298. self.parent.OnCloseWindow),
  299. ))