dialogs.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. """!
  2. @package iclass::toolbars
  3. @brief wxIClass dialogs
  4. Classes:
  5. - dialogs::IClassGroupDialog
  6. - dialogs::IClassMapDialog
  7. - dialogs::IClassCategoryManagerDialog
  8. - dialogs::CategoryListCtrl
  9. - dialogs::IClassSignatureFileDialog
  10. (C) 2006-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Vaclav Petras <wenzeslaus gmail.com>
  15. @author Anna Kratochvilova <kratochanna gmail.com>
  16. """
  17. import os
  18. import wx
  19. import wx.lib.mixins.listctrl as listmix
  20. import wx.lib.scrolledpanel as scrolled
  21. from core import globalvar
  22. from gui_core.dialogs import ElementDialog, GroupDialog
  23. from gui_core import gselect
  24. from iclass.statistics import Statistics, BandStatistics
  25. import grass.script as grass
  26. class IClassGroupDialog(ElementDialog):
  27. """!Dialog for imagery group selection"""
  28. def __init__(self, parent, group = None, title = _("Select imagery group"), id = wx.ID_ANY):
  29. """!
  30. Does post init and layout.
  31. @param gui parent
  32. @param title dialog window title
  33. @param id wx id
  34. """
  35. ElementDialog.__init__(self, parent, title, label = _("Name of imagery group:"))
  36. self.element = gselect.Select(parent = self.panel, type = 'group',
  37. mapsets = [grass.gisenv()['MAPSET']],
  38. size = globalvar.DIALOG_GSELECT_SIZE)
  39. if group:
  40. self.element.SetValue(group)
  41. self.editGroup = wx.Button(parent = self.panel, id = wx.ID_ANY,
  42. label = _("Create/edit group..."))
  43. self.editGroup.Bind(wx.EVT_BUTTON, self.OnEditGroup)
  44. self.PostInit()
  45. self.__Layout()
  46. self.SetMinSize(self.GetSize())
  47. def __Layout(self):
  48. """!Do layout"""
  49. self.dataSizer.Add(self.element, proportion = 0,
  50. flag = wx.EXPAND | wx.ALL, border = 5)
  51. self.dataSizer.Add(self.editGroup, proportion = 0,
  52. flag = wx.ALL, border = 5)
  53. self.panel.SetSizer(self.sizer)
  54. self.sizer.Fit(self)
  55. def GetGroup(self):
  56. """!Returns selected group"""
  57. return self.GetElement()
  58. def OnEditGroup(self, event):
  59. """!Launch edit group dialog"""
  60. dlg = GroupDialog(parent = self, defaultGroup = self.element.GetValue())
  61. dlg.ShowModal()
  62. gr = dlg.GetSelectedGroup()
  63. if gr in dlg.GetExistGroups():
  64. self.element.SetValue(gr)
  65. dlg.Destroy()
  66. class IClassMapDialog(ElementDialog):
  67. """!Dialog for adding raster map"""
  68. def __init__(self, parent, title = _("Add raster map"), id = wx.ID_ANY):
  69. """!
  70. Does post init and layout.
  71. @param gui parent
  72. @param title dialog window title
  73. @param id wx id
  74. """
  75. ElementDialog.__init__(self, parent, title, label = _("Name of raster map:"))
  76. self.element = gselect.Select(parent = self.panel, type = 'raster',
  77. size = globalvar.DIALOG_GSELECT_SIZE)
  78. #self.firstMapCheck = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  79. #label = _("Add raster map to Training display"))
  80. #self.secondMapCheck = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  81. #label = _("Add raster map to Preview display"))
  82. # in user settings
  83. #self.firstMapCheck.SetValue(True)
  84. #self.secondMapCheck.SetValue(True)
  85. self.PostInit()
  86. self.__Layout()
  87. self.SetMinSize(self.GetSize())
  88. def __Layout(self):
  89. """!Do layout"""
  90. self.dataSizer.Add(self.element, proportion = 0,
  91. flag = wx.EXPAND | wx.ALL, border = 5)
  92. #self.dataSizer.Add(self.firstMapCheck, proportion = 0,
  93. #flag = wx.ALL, border = 5)
  94. #self.dataSizer.Add(self.secondMapCheck, proportion = 0,
  95. #flag = wx.ALL, border = 5)
  96. self.panel.SetSizer(self.sizer)
  97. self.sizer.Fit(self)
  98. def GetRasterMap(self):
  99. """!Returns selected raster map"""
  100. return self.GetElement()
  101. #def IfAddToFirstMap(self):
  102. #return self.firstMapCheck.IsChecked()
  103. #def IfAddToSecondMap(self):
  104. #return self.secondMapCheck.IsChecked()
  105. class IClassCategoryManagerDialog(wx.Dialog):
  106. """!Dialog for managing categories (classes).
  107. Alows adding, deleting class and changing its name and color.
  108. """
  109. def __init__(self, parent, title = _("Class manager"), id = wx.ID_ANY):
  110. """!
  111. Does post init and layout.
  112. @param gui parent
  113. @param title dialog window title
  114. @param id wx id
  115. """
  116. wx.Dialog.__init__(self, parent = parent, title = title, id = id)
  117. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  118. mainSizer = wx.BoxSizer(wx.VERTICAL)
  119. box = wx.StaticBox(panel, id = wx.ID_ANY,
  120. label = " %s " % _("Classes"))
  121. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  122. gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  123. gridSizer.AddGrowableCol(0)
  124. gridSizer.AddGrowableRow(2)
  125. self.catList = CategoryListCtrl(panel, mapwindow = parent, statistics = parent.statisticsDict,
  126. statisticsList = parent.statisticsList)
  127. addButton = wx.Button(panel, id = wx.ID_ADD)
  128. deleteButton = wx.Button(panel, id = wx.ID_DELETE)
  129. gridSizer.Add(item = self.catList, pos = (0, 0), span = (3, 1), flag = wx.EXPAND)
  130. gridSizer.Add(item = addButton, pos = (0, 1), flag = wx.EXPAND)
  131. gridSizer.Add(item = deleteButton, pos = (1, 1), flag = wx.EXPAND)
  132. sizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  133. mainSizer.Add(item = sizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  134. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  135. closeButton = wx.Button(panel, id = wx.ID_CLOSE)
  136. btnSizer.Add(item = wx.Size(-1, -1), proportion = 1, flag = wx.EXPAND)
  137. btnSizer.Add(item = closeButton, proportion = 0, flag = wx.ALIGN_RIGHT)
  138. mainSizer.Add(item = btnSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
  139. addButton.Bind(wx.EVT_BUTTON, self.OnAddCategory)
  140. deleteButton.Bind(wx.EVT_BUTTON, self.OnDeleteCategory)
  141. closeButton.Bind(wx.EVT_BUTTON, self.OnClose)
  142. self.Bind(wx.EVT_CLOSE, self.OnClose)
  143. panel.SetSizer(mainSizer)
  144. mainSizer.Fit(panel)
  145. self.SetSize((-1, 250))
  146. self.Layout()
  147. def OnAddCategory(self, event):
  148. self.catList.AddCategory()
  149. def OnDeleteCategory(self, event):
  150. self.catList.DeleteCategory()
  151. def OnClose(self, event):
  152. self.catList.DeselectAll()
  153. self.catList.UpdateChoice()
  154. if not isinstance(event, wx.CloseEvent):
  155. self.Destroy()
  156. event.Skip()
  157. class CategoryListCtrl(wx.ListCtrl,
  158. listmix.ListCtrlAutoWidthMixin,
  159. listmix.TextEditMixin):
  160. """! Widget for controling list of classes (categories).
  161. CategoryListCtrl updates choice in mapwindow and removes raster map
  162. when deleting class (category).
  163. It uses virtual data in the terms of @c wx.ListCtrl.
  164. @todo statistics and categories are managed here directly,
  165. it could be better to use some interface
  166. @todo delete vector features after deleting class
  167. """
  168. def __init__(self, parent, mapwindow, statistics, statisticsList, id = wx.ID_ANY):
  169. """!
  170. @param parent gui parent
  171. @param mapwindow mapwindow instance with iclass toolbar and remove raster method
  172. @param statistics dictionary of statistics (defined in statistics.py)
  173. @param statisticsList list of statistics
  174. @param id wx id
  175. """
  176. wx.ListCtrl.__init__(self, parent, id,
  177. style = wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
  178. self.columns = ((_('Class name'), 'name'),
  179. (_('Color'), 'color'))
  180. self.Populate(columns = self.columns)
  181. self.mapWindow = mapwindow
  182. self.statisticsDict = statistics
  183. self.statisticsList = statisticsList
  184. self.SetItemCount(len(statisticsList))
  185. self.rightClickedItemIdx = wx.NOT_FOUND
  186. listmix.ListCtrlAutoWidthMixin.__init__(self)
  187. listmix.TextEditMixin.__init__(self)
  188. self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnEdit)
  189. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnCategorySelected)
  190. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnClassRightUp) #wxMSW
  191. self.Bind(wx.EVT_RIGHT_UP, self.OnClassRightUp) #wxGTK
  192. def SetVirtualData(self, row, column, text):
  193. attr = self.columns[column][1]
  194. setattr(self.statisticsDict[self.statisticsList[row]], attr, text)
  195. self.UpdateChoice()
  196. toolbar = self.mapWindow.toolbars['iClass']
  197. toolbar.choice.SetSelection(row)
  198. self.Select(row)
  199. if attr == 'name':
  200. self.mapWindow.UpdateRasterName(text, toolbar.GetSelectedCategoryIdx())
  201. self.mapWindow.UpdateChangeState(changes = True)
  202. def Populate(self, columns):
  203. for i, col in enumerate(columns):
  204. self.InsertColumn(i, col[0])#wx.LIST_FORMAT_RIGHT
  205. self.SetColumnWidth(0, 100)
  206. self.SetColumnWidth(1, 100)
  207. def AddCategory(self):
  208. st = Statistics()
  209. if self.statisticsList:
  210. cat = max(self.statisticsList) + 1
  211. else:
  212. cat = 1
  213. defaultName = 'class' + '_' + str(cat) # intentionally not translatable
  214. defaultColor = '0:0:0'
  215. st.SetBaseStatistics(cat = cat, name = defaultName, color = defaultColor)
  216. self.statisticsDict[cat] = st
  217. self.statisticsList.append(cat)
  218. self.SetItemCount(len(self.statisticsList))
  219. self.UpdateChoice()
  220. self.mapWindow.UpdateChangeState(changes = True)
  221. def DeleteCategory(self):
  222. indexList = sorted(self.GetSelectedIndices(), reverse = True)
  223. cats = []
  224. for i in indexList:
  225. # remove temporary raster
  226. name = self.statisticsDict[self.statisticsList[i]].rasterName
  227. self.mapWindow.RemoveTempRaster(name)
  228. cats.append(self.statisticsList[i])
  229. del self.statisticsDict[self.statisticsList[i]]
  230. del self.statisticsList[i]
  231. self.SetItemCount(len(self.statisticsList))
  232. self.UpdateChoice()
  233. self.mapWindow.UpdateChangeState(changes = True)
  234. self.mapWindow.DeleteAreas(cats = cats)
  235. def UpdateChoice(self):
  236. toolbar = self.mapWindow.toolbars['iClass']
  237. name = toolbar.GetSelectedCategoryName()
  238. catNames = []
  239. for cat in self.statisticsList:
  240. catNames.append(self.statisticsDict[cat].name)
  241. toolbar.SetCategories(catNames = catNames, catIdx = self.statisticsList)
  242. if name in catNames:
  243. toolbar.choice.SetStringSelection(name)
  244. elif catNames:
  245. toolbar.choice.SetSelection(0)
  246. if toolbar.choice.IsEmpty():
  247. toolbar.EnableControls(False)
  248. else:
  249. toolbar.EnableControls(True)
  250. # don't forget to update maps, histo, ...
  251. def GetSelectedIndices(self, state = wx.LIST_STATE_SELECTED):
  252. indices = []
  253. lastFound = -1
  254. while True:
  255. index = self.GetNextItem(lastFound, wx.LIST_NEXT_ALL, state)
  256. if index == -1:
  257. break
  258. else:
  259. lastFound = index
  260. indices.append(index)
  261. return indices
  262. def OnEdit(self, event):
  263. currentItem = event.m_itemIndex
  264. currentCol = event.m_col
  265. if currentCol == 1:
  266. dlg = wx.ColourDialog(self)
  267. dlg.GetColourData().SetChooseFull(True)
  268. if dlg.ShowModal() == wx.ID_OK:
  269. color = dlg.GetColourData().GetColour().Get()
  270. color = ':'.join(map(str, color))
  271. self.SetVirtualData(currentItem, currentCol, color)
  272. dlg.Destroy()
  273. event.Skip()
  274. def OnCategorySelected(self, event):
  275. """!Highlight selected areas"""
  276. indexList = self.GetSelectedIndices()
  277. cats = []
  278. for i in indexList:
  279. cats.append(self.statisticsList[i])
  280. self.mapWindow.HighlightCategory(cats)
  281. if event:
  282. event.Skip()
  283. def OnClassRightUp(self, event):
  284. """!Show context menu on right click"""
  285. item, flags = self.HitTest((event.GetX(), event.GetY()))
  286. if item != wx.NOT_FOUND and flags & wx.LIST_HITTEST_ONITEM:
  287. self.rightClickedItemIdx = item
  288. self.popupZoomtoAreas = wx.NewId()
  289. self.Bind(wx.EVT_MENU, self.OnZoomToAreasByCat, id = self.popupZoomtoAreas)
  290. # generate popup-menu
  291. menu = wx.Menu()
  292. menu.Append(self.popupZoomtoAreas, _("Zoom to training areas of selected class"))
  293. self.PopupMenu(menu)
  294. menu.Destroy()
  295. def OnZoomToAreasByCat(self, event):
  296. """!Zoom to areas of given category"""
  297. cat = self.statisticsList[self.rightClickedItemIdx]
  298. self.mapWindow.ZoomToAreasByCat(cat)
  299. def DeselectAll(self):
  300. """!Deselect all items"""
  301. indexList = self.GetSelectedIndices()
  302. for i in indexList:
  303. self.Select(i, on = 0)
  304. # no highlight
  305. self.OnCategorySelected(None)
  306. def OnGetItemText(self, item, col):
  307. cat = self.statisticsList[item]
  308. return getattr(self.statisticsDict[cat], self.columns[col][1])
  309. def OnGetItemImage(self, item):
  310. return -1
  311. def OnGetItemAttr(self, item):
  312. return None
  313. class IClassSignatureFileDialog(wx.Dialog):
  314. def __init__(self, parent, group, file = None, title = _("Save signature file"), id = wx.ID_ANY,
  315. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  316. **kwargs):
  317. """!Dialog for saving signature file
  318. @param parent window
  319. @param group group name
  320. @param file signature file name
  321. @param title window title
  322. """
  323. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  324. self.fileName = file
  325. env = grass.gisenv()
  326. # inconsistent group and subgroup name
  327. # path: grassdata/nc_spm_08/landsat/group/test_group/subgroup/test_group@landsat/sig/sigFile
  328. self.baseFilePath = os.path.join(env['GISDBASE'],
  329. env['LOCATION_NAME'],
  330. env['MAPSET'],
  331. 'group', group.split('@')[0], # !
  332. 'subgroup', group,
  333. 'sig')
  334. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  335. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  336. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  337. self.btnOK.SetDefault()
  338. self.btnOK.Enable(False)
  339. self.__layout()
  340. self.fileNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
  341. self.OnTextChanged(None)
  342. def OnTextChanged(self, event):
  343. """!Name for signature file given"""
  344. file = self.fileNameCtrl.GetValue()
  345. if len(file) > 0:
  346. self.btnOK.Enable(True)
  347. else:
  348. self.btnOK.Enable(False)
  349. path = os.path.join(self.baseFilePath, file)
  350. self.filePathText.SetLabel(path)
  351. bestSize = self.pathPanel.GetBestVirtualSize()
  352. self.pathPanel.SetVirtualSize(bestSize)
  353. self.pathPanel.Scroll(*bestSize)
  354. def __layout(self):
  355. """!Do layout"""
  356. sizer = wx.BoxSizer(wx.VERTICAL)
  357. dataSizer = wx.BoxSizer(wx.VERTICAL)
  358. dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  359. label = _("Enter name of signature file:")),
  360. proportion = 0, flag = wx.ALL, border = 3)
  361. self.fileNameCtrl = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (400, -1))
  362. if self.fileName:
  363. self.fileNameCtrl.SetValue(self.fileName)
  364. dataSizer.Add(item = self.fileNameCtrl,
  365. proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
  366. dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  367. label = _("Signature file path:")),
  368. proportion = 0, flag = wx.ALL, border = 3)
  369. self.pathPanel = scrolled.ScrolledPanel(self.panel, size = (-1, 40))
  370. pathSizer = wx.BoxSizer()
  371. self.filePathText = wx.StaticText(parent = self.pathPanel, id = wx.ID_ANY,
  372. label = self.baseFilePath)
  373. pathSizer.Add(self.filePathText, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  374. self.pathPanel.SetupScrolling(scroll_x = True, scroll_y = False)
  375. self.pathPanel.SetSizer(pathSizer)
  376. dataSizer.Add(item = self.pathPanel,
  377. proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
  378. # buttons
  379. btnSizer = wx.StdDialogButtonSizer()
  380. btnSizer.AddButton(self.btnCancel)
  381. btnSizer.AddButton(self.btnOK)
  382. btnSizer.Realize()
  383. sizer.Add(item = dataSizer, proportion = 1,
  384. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  385. sizer.Add(item = btnSizer, proportion = 0,
  386. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  387. self.panel.SetSizer(sizer)
  388. sizer.Fit(self)
  389. self.SetMinSize(self.GetSize())
  390. def GetFileName(self, fullPath = False):
  391. """!Returns signature file name
  392. @param fullPath return full path of sig. file
  393. """
  394. if fullPath:
  395. return os.path.join(self.baseFilePath, self.fileNameCtrl.GetValue())
  396. return self.fileNameCtrl.GetValue()