toolbars.py 13 KB

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