toolbars.py 13 KB

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