toolbars.py 12 KB

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