toolbars.py 12 KB

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