toolbars.py 13 KB

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