dialogs.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. """
  2. @package iclass.dialogs
  3. @brief wxIClass dialogs
  4. Classes:
  5. - dialogs::IClassGroupDialog
  6. - dialogs::IClassMapDialog
  7. - dialogs::IClassCategoryManagerDialog
  8. - dialogs::CategoryListCtrl
  9. - dialogs::IClassSignatureFileDialog
  10. - dialogs::IClassExportAreasDialog
  11. (C) 2006-2011 by the GRASS Development Team
  12. This program is free software under the GNU General Public
  13. License (>=v2). Read the file COPYING that comes with GRASS
  14. for details.
  15. @author Vaclav Petras <wenzeslaus gmail.com>
  16. @author Anna Kratochvilova <kratochanna gmail.com>
  17. """
  18. import os
  19. import wx
  20. import wx.lib.mixins.listctrl as listmix
  21. import wx.lib.scrolledpanel as scrolled
  22. from core import globalvar
  23. from core.utils import _
  24. from core.settings import UserSettings
  25. from core.gcmd import GError, RunCommand, GMessage
  26. from gui_core.dialogs import SimpleDialog, GroupDialog
  27. from gui_core import gselect
  28. from gui_core.widgets import SimpleValidator
  29. from iclass.statistics import Statistics, BandStatistics
  30. import grass.script as grass
  31. class IClassGroupDialog(SimpleDialog):
  32. """Dialog for imagery group selection"""
  33. def __init__(self, parent, group = None, subgroup = None,
  34. title = _("Select imagery group"), id = wx.ID_ANY):
  35. """
  36. Does post init and layout.
  37. :param parent: gui parent
  38. :param title: dialog window title
  39. :param id: wx id
  40. """
  41. SimpleDialog.__init__(self, parent, title)
  42. self.use_subg = True
  43. self.groupSelect = gselect.Select(parent = self.panel, type = 'group',
  44. mapsets = [grass.gisenv()['MAPSET']],
  45. size = globalvar.DIALOG_GSELECT_SIZE,
  46. validator = SimpleValidator(callback = self.ValidatorCallback))
  47. # TODO use when subgroup will be optional
  48. #self.subg_chbox = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  49. # label = _("Use subgroup"))
  50. self.subGroupSelect = gselect.SubGroupSelect(parent = self.panel)
  51. self.groupSelect.SetFocus()
  52. if group:
  53. self.groupSelect.SetValue(group)
  54. self.GroupSelected()
  55. if subgroup:
  56. self.subGroupSelect.SetValue(subgroup)
  57. self.editGroup = wx.Button(parent = self.panel, id = wx.ID_ANY,
  58. label = _("Create/edit group..."))
  59. self.editGroup.Bind(wx.EVT_BUTTON, self.OnEditGroup)
  60. self.groupSelect.GetTextCtrl().Bind(wx.EVT_TEXT,
  61. lambda event : wx.CallAfter(self.GroupSelected))
  62. self.warning = _("Name of imagery group is missing.")
  63. self._layout()
  64. self.SetMinSize(self.GetSize())
  65. def _layout(self):
  66. """Do layout"""
  67. self.dataSizer.Add(wx.StaticText(self.panel, id = wx.ID_ANY,
  68. label = _("Name of imagery group:")),
  69. proportion = 0,
  70. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  71. border = 5)
  72. self.dataSizer.Add(self.groupSelect, proportion = 0,
  73. flag = wx.EXPAND | wx.ALL, border = 5)
  74. # TODO use when subgroup will be optional
  75. #self.dataSizer.Add(self.subg_chbox, proportion = 0,
  76. # flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  77. self.dataSizer.Add(wx.StaticText(self.panel, id = wx.ID_ANY,
  78. label = _("Name of imagery subgroup:")),
  79. proportion = 0, flag = wx.EXPAND | wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  80. border = 5)
  81. self.dataSizer.Add(self.subGroupSelect, proportion = 0,
  82. flag = wx.EXPAND | wx.ALL, border = 5)
  83. self.dataSizer.Add(self.editGroup, proportion = 0,
  84. flag = wx.ALL, border = 5)
  85. self.panel.SetSizer(self.sizer)
  86. self.sizer.Fit(self)
  87. #TODO use when subgroup will be optional
  88. #self.subg_panel.Show(False)
  89. #self.subg_chbox.Bind(wx.EVT_CHECKBOX, self.OnSubgChbox)
  90. def OnSubgChbox(self, event):
  91. self.use_subg = self.subg_chbox.GetValue()
  92. if self.use_subg:
  93. self.subg_panel.Show()
  94. #self.SubGroupSelected()
  95. else:
  96. self.subg_panel.Hide()
  97. #self.GroupSelected()
  98. self.SetMinSize(self.GetBestSize())
  99. self.Layout()
  100. def GetData(self):
  101. """Returns selected group and subgroup"""
  102. if self.use_subg:
  103. ret = (self.groupSelect.GetValue(), self.subGroupSelect.GetValue())
  104. else:
  105. ret = (self.groupSelect.GetValue(), None)
  106. return ret
  107. def OnEditGroup(self, event):
  108. """Launch edit group dialog"""
  109. g, s = self.GetData()
  110. dlg = GroupDialog(parent=self, defaultGroup=g, defaultSubgroup=s)
  111. dlg.ShowModal()
  112. gr, s = dlg.GetSelectedGroup()
  113. if gr in dlg.GetExistGroups():
  114. self.groupSelect.SetValue(gr)
  115. self.GroupSelected()
  116. wx.CallAfter(self.subGroupSelect.SetValue, s)
  117. dlg.Destroy()
  118. def GroupSelected(self):
  119. group = self.GetSelectedGroup()
  120. self.subGroupSelect.Insert(group)
  121. def GetSelectedGroup(self):
  122. """Return currently selected group (without mapset)"""
  123. return self.groupSelect.GetValue().split('@')[0]
  124. def GetGroupBandsErr(self, parent):
  125. """Get list of raster bands which are in the soubgroup of group with both having same name.
  126. If the group does not exists or it does not contain any bands in subgoup with same name,
  127. error dialog is shown.
  128. """
  129. gr, s = self.GetData()
  130. group = grass.find_file(name=gr, element='group')
  131. bands = []
  132. g = group['name']
  133. if g:
  134. if self.use_subg:
  135. if s == '':
  136. GError(_("Please choose a subgroup."), parent=parent)
  137. return bands
  138. if s not in self.GetSubgroups(g):
  139. GError(_("Subgroup <%s> not found in group <%s>") % (s, g), parent=parent)
  140. return bands
  141. bands = self.GetGroupBands(g, s)
  142. if not bands:
  143. if self.use_subg:
  144. GError(_("No data found in subgroup <%s> of group <%s>.\n" \
  145. ".") \
  146. % (s, g), parent=parent)
  147. else:
  148. GError(_("No data found in group <%s>.\n" \
  149. ".") \
  150. % g, parent=parent)
  151. else:
  152. GError(_("Group <%s> not found") % gr, parent=parent)
  153. return bands
  154. def GetGroupBands(self, group, subgroup):
  155. """Get list of raster bands which are in the soubgroup of group with both having same name."""
  156. kwargs = {}
  157. if subgroup:
  158. kwargs['subgroup'] = subgroup
  159. res = RunCommand('i.group',
  160. flags='g',
  161. group=group,
  162. read = True, **kwargs).strip()
  163. bands = None
  164. if res.split('\n')[0]:
  165. bands = res.split('\n')
  166. return bands
  167. def GetSubgroups(self, group):
  168. return RunCommand('i.group', group=group,
  169. read=True, flags='sg').splitlines()
  170. class IClassMapDialog(SimpleDialog):
  171. """Dialog for adding raster/vector map"""
  172. def __init__(self, parent, title, element):
  173. """
  174. :param parent: gui parent
  175. :param title: dialog title
  176. :param element: element type ('raster', 'vector')
  177. """
  178. SimpleDialog.__init__(self, parent, title = title)
  179. self.elementType = element
  180. self.element = gselect.Select(parent = self.panel, type = element,
  181. size = globalvar.DIALOG_GSELECT_SIZE,
  182. validator = SimpleValidator(callback = self.ValidatorCallback))
  183. self.element.SetFocus()
  184. self.warning = _("Name of map is missing.")
  185. self._layout()
  186. self.SetMinSize(self.GetSize())
  187. def _layout(self):
  188. """Do layout"""
  189. if self.elementType == 'raster':
  190. label = _("Name of raster map:")
  191. elif self.elementType == 'vector':
  192. label = _("Name of vector map:")
  193. self.dataSizer.Add(wx.StaticText(self.panel, id = wx.ID_ANY,
  194. label = label),
  195. proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
  196. self.dataSizer.Add(self.element, proportion = 0,
  197. flag = wx.EXPAND | wx.ALL, border = 5)
  198. self.panel.SetSizer(self.sizer)
  199. self.sizer.Fit(self)
  200. def GetMap(self):
  201. """Returns selected raster/vector map"""
  202. return self.element.GetValue()
  203. class IClassCategoryManagerDialog(wx.Dialog):
  204. """Dialog for managing categories (classes).
  205. Alows adding, deleting class and changing its name and color.
  206. """
  207. def __init__(self, parent, title = _("Class manager"), id = wx.ID_ANY):
  208. """
  209. Does post init and layout.
  210. :param parent: gui parent
  211. :param title: dialog window title
  212. :param id: wx id
  213. """
  214. wx.Dialog.__init__(self, parent = parent, title = title, id = id)
  215. self.parent = parent
  216. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  217. mainSizer = wx.BoxSizer(wx.VERTICAL)
  218. box = wx.StaticBox(panel, id = wx.ID_ANY,
  219. label = " %s " % _("Classes"))
  220. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  221. gridSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
  222. self.catList = CategoryListCtrl(panel, mapwindow = parent,
  223. stats_data = parent.stats_data)
  224. addButton = wx.Button(panel, id = wx.ID_ADD)
  225. deleteButton = wx.Button(panel, id = wx.ID_DELETE)
  226. gridSizer.Add(item = self.catList, pos = (0, 0), span = (3, 1), flag = wx.EXPAND)
  227. gridSizer.Add(item = addButton, pos = (0, 1), flag = wx.EXPAND)
  228. gridSizer.Add(item = deleteButton, pos = (1, 1), flag = wx.EXPAND)
  229. gridSizer.AddGrowableCol(0)
  230. gridSizer.AddGrowableRow(2)
  231. sizer.Add(item = gridSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  232. mainSizer.Add(item = sizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  233. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  234. closeButton = wx.Button(panel, id = wx.ID_CLOSE)
  235. btnSizer.Add(item = wx.Size(-1, -1), proportion = 1, flag = wx.EXPAND)
  236. btnSizer.Add(item = closeButton, proportion = 0, flag = wx.ALIGN_RIGHT)
  237. mainSizer.Add(item = btnSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
  238. addButton.Bind(wx.EVT_BUTTON, self.OnAddCategory)
  239. deleteButton.Bind(wx.EVT_BUTTON, self.OnDeleteCategory)
  240. closeButton.Bind(wx.EVT_BUTTON, self.OnClose)
  241. self.Bind(wx.EVT_CLOSE, self.OnClose)
  242. panel.SetSizer(mainSizer)
  243. mainSizer.Fit(self)
  244. self.SetSize((400, 250))
  245. self.Layout()
  246. def OnAddCategory(self, event):
  247. if self.parent.stats_data.GetCategories():
  248. cat = max(self.parent.stats_data.GetCategories()) + 1
  249. else:
  250. cat = 1
  251. defaultName = 'class' + '_' + str(cat) # intentionally not translatable
  252. defaultColor = '0:0:0'
  253. self.catList.AddCategory(cat = cat, name = defaultName, color = defaultColor)
  254. def OnDeleteCategory(self, event):
  255. self.catList.DeleteCategory()
  256. def OnClose(self, event):
  257. self.catList.DeselectAll()
  258. self.Hide()
  259. #if not isinstance(event, wx.CloseEvent):
  260. #self.Destroy()
  261. #event.Skip()
  262. def GetListCtrl(self):
  263. """Returns list widget"""
  264. return self.catList
  265. class CategoryListCtrl(wx.ListCtrl,
  266. listmix.ListCtrlAutoWidthMixin,
  267. listmix.TextEditMixin):
  268. """Widget for controling list of classes (categories).
  269. CategoryListCtrl updates choice in mapwindow and removes raster map
  270. when deleting class (category).
  271. It uses virtual data in the terms of @c wx.ListCtrl.
  272. .. todo::
  273. delete vector features after deleting class
  274. """
  275. def __init__(self, parent, mapwindow, stats_data, id = wx.ID_ANY):
  276. """
  277. :param parent: gui parent
  278. :param mapwindow: mapwindow instance with iclass toolbar and remove raster method
  279. :param stats_data: StatisticsData instance (defined in statistics.py)
  280. :param id: wx id
  281. """
  282. wx.ListCtrl.__init__(self, parent, id,
  283. style = wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES)
  284. self.columns = ((_('Class name'), 'name'),
  285. (_('Color'), 'color'))
  286. self.Populate(columns = self.columns)
  287. self.mapWindow = mapwindow
  288. self.stats_data = stats_data
  289. self.SetItemCount(len(self.stats_data.GetCategories()))
  290. self.rightClickedItemIdx = wx.NOT_FOUND
  291. listmix.ListCtrlAutoWidthMixin.__init__(self)
  292. listmix.TextEditMixin.__init__(self)
  293. self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnEdit)
  294. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnCategorySelected)
  295. self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnClassRightUp) #wxMSW
  296. self.Bind(wx.EVT_RIGHT_UP, self.OnClassRightUp) #wxGTK
  297. self.stats_data.statisticsAdded.connect(self.Update)
  298. self.stats_data.statisticsDeleted.connect(self.Update)
  299. self.stats_data.allStatisticsDeleted.connect(self.Update)
  300. self.stats_data.statisticsSet.connect(self.Update)
  301. def Update(self):
  302. self.SetItemCount(len(self.stats_data.GetCategories()))
  303. def SetVirtualData(self, row, column, text):
  304. attr = self.columns[column][1]
  305. if attr == 'name':
  306. try:
  307. text.encode('ascii')
  308. except UnicodeEncodeError:
  309. GMessage(parent = self, message = _("Please use only ASCII characters."))
  310. return
  311. cat = self.stats_data.GetCategories()[row]
  312. self.stats_data.GetStatistics(cat).SetStatistics(stats = {attr : text})
  313. toolbar = self.mapWindow.toolbars['iClass']
  314. toolbar.choice.SetSelection(row)
  315. self.Select(row)
  316. if attr == 'name':
  317. self.mapWindow.UpdateRasterName(text, toolbar.GetSelectedCategoryIdx())
  318. self.mapWindow.UpdateChangeState(changes = True)
  319. def Populate(self, columns):
  320. for i, col in enumerate(columns):
  321. self.InsertColumn(i, col[0])#wx.LIST_FORMAT_RIGHT
  322. self.SetColumnWidth(0, 100)
  323. self.SetColumnWidth(1, 100)
  324. def AddCategory(self, cat, name, color):
  325. """Add category record (used when importing areas)"""
  326. self.stats_data.AddStatistics(cat, name, color)
  327. self.SetItemCount(len(self.stats_data.GetCategories()))
  328. self.mapWindow.UpdateChangeState(changes = True)
  329. def DeleteCategory(self):
  330. indexList = sorted(self.GetSelectedIndices(), reverse = True)
  331. del_cats = []
  332. cats = self.stats_data.GetCategories()
  333. for i in indexList:
  334. # remove temporary raster
  335. cat = cats[i]
  336. stat = self.stats_data.GetStatistics(cat)
  337. name = stat.rasterName
  338. self.mapWindow.RemoveTempRaster(name)
  339. del_cats.append(cat)
  340. self.stats_data.DeleteStatistics(cat)
  341. self.SetItemCount(len(self.stats_data.GetCategories()))
  342. self.mapWindow.UpdateChangeState(changes = True)
  343. self.mapWindow.DeleteAreas(cats = del_cats)
  344. def GetSelectedIndices(self, state = wx.LIST_STATE_SELECTED):
  345. indices = []
  346. lastFound = -1
  347. while True:
  348. index = self.GetNextItem(lastFound, wx.LIST_NEXT_ALL, state)
  349. if index == -1:
  350. break
  351. else:
  352. lastFound = index
  353. indices.append(index)
  354. return indices
  355. def OnEdit(self, event):
  356. currentItem = event.m_itemIndex
  357. currentCol = event.m_col
  358. if currentCol == 1:
  359. col = self.OnGetItemText(currentItem, currentCol)
  360. col = map(int, col.split(':'))
  361. col_data = wx.ColourData()
  362. col_data.SetColour(wx.Colour(*col))
  363. dlg = wx.ColourDialog(self, col_data)
  364. dlg.GetColourData().SetChooseFull(True)
  365. if dlg.ShowModal() == wx.ID_OK:
  366. color = dlg.GetColourData().GetColour().Get()
  367. color = ':'.join(map(str, color))
  368. self.SetVirtualData(currentItem, currentCol, color)
  369. dlg.Destroy()
  370. wx.CallAfter(self.SetFocus)
  371. event.Skip()
  372. def OnCategorySelected(self, event):
  373. """Highlight selected areas"""
  374. indexList = self.GetSelectedIndices()
  375. sel_cats = []
  376. cats = self.stats_data.GetCategories()
  377. for i in indexList:
  378. sel_cats.append(cats[i])
  379. self.mapWindow.HighlightCategory(sel_cats)
  380. if event:
  381. event.Skip()
  382. def OnClassRightUp(self, event):
  383. """Show context menu on right click"""
  384. item, flags = self.HitTest((event.GetX(), event.GetY()))
  385. if item != wx.NOT_FOUND and flags & wx.LIST_HITTEST_ONITEM:
  386. self.rightClickedItemIdx = item
  387. if not hasattr(self, "popupZoomtoAreas"):
  388. self.popupZoomtoAreas = wx.NewId()
  389. self.Bind(wx.EVT_MENU, self.OnZoomToAreasByCat, id = self.popupZoomtoAreas)
  390. # generate popup-menu
  391. menu = wx.Menu()
  392. menu.Append(self.popupZoomtoAreas, _("Zoom to training areas of selected class"))
  393. self.PopupMenu(menu)
  394. menu.Destroy()
  395. def OnZoomToAreasByCat(self, event):
  396. """Zoom to areas of given category"""
  397. cat = self.stats_data.GetCategories()[self.rightClickedItemIdx]
  398. self.mapWindow.ZoomToAreasByCat(cat)
  399. def DeselectAll(self):
  400. """Deselect all items"""
  401. indexList = self.GetSelectedIndices()
  402. for i in indexList:
  403. self.Select(i, on = 0)
  404. # no highlight
  405. self.OnCategorySelected(None)
  406. def OnGetItemText(self, item, col):
  407. cat = self.stats_data.GetCategories()[item]
  408. stat = self.stats_data.GetStatistics(cat)
  409. return getattr(stat, self.columns[col][1])
  410. def OnGetItemImage(self, item):
  411. return -1
  412. def OnGetItemAttr(self, item):
  413. return None
  414. def OnGetItemAttr(self, item):
  415. """Set correct class color for a item"""
  416. back_c = wx.Colour(*map(int, self.OnGetItemText(item, 1).split(':')))
  417. text_c = wx.Colour(*ContrastColor(back_c))
  418. # if it is in scope of the method, gui falls, using self solved it
  419. self.l = wx.ListItemAttr(colText = text_c, colBack = back_c)
  420. return self.l
  421. def ContrastColor(color):
  422. """Decides which value shoud have text to be contrast with backgroud color
  423. (bright bg -> black, dark bg -> white)
  424. .. todo::
  425. could be useful by other apps, consider moving it into gui_core
  426. """
  427. #gacek, http://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color
  428. a = 1 - ( 0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2])/255;
  429. if a < 0.5:
  430. d = 0
  431. else:
  432. d = 255
  433. # maybe return just bool if text shoud be dark or bright
  434. return (d, d, d)
  435. class IClassSignatureFileDialog(wx.Dialog):
  436. def __init__(self, parent, group, subgroup,
  437. file = None, title = _("Save signature file"), id = wx.ID_ANY,
  438. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  439. **kwargs):
  440. """Dialog for saving signature file
  441. :param parent: window
  442. :param group: group name
  443. :param file: signature file name
  444. :param title: window title
  445. """
  446. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  447. self.fileName = file
  448. env = grass.gisenv()
  449. # inconsistent group and subgroup name
  450. # path: grassdata/nc_spm_08/landsat/group/test_group/subgroup/test_group/sig/sigFile
  451. self.baseFilePath = os.path.join(env['GISDBASE'],
  452. env['LOCATION_NAME'],
  453. env['MAPSET'],
  454. 'group', group,
  455. 'subgroup', subgroup,
  456. 'sig')
  457. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  458. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  459. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  460. self.btnOK.SetDefault()
  461. self.btnOK.Enable(False)
  462. self.__layout()
  463. self.fileNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
  464. self.OnTextChanged(None)
  465. def OnTextChanged(self, event):
  466. """Name for signature file given"""
  467. file = self.fileNameCtrl.GetValue()
  468. if len(file) > 0:
  469. self.btnOK.Enable(True)
  470. else:
  471. self.btnOK.Enable(False)
  472. path = os.path.join(self.baseFilePath, file)
  473. self.filePathText.SetLabel(path)
  474. bestSize = self.pathPanel.GetBestVirtualSize()
  475. self.pathPanel.SetVirtualSize(bestSize)
  476. self.pathPanel.Scroll(*bestSize)
  477. def __layout(self):
  478. """Do layout"""
  479. sizer = wx.BoxSizer(wx.VERTICAL)
  480. dataSizer = wx.BoxSizer(wx.VERTICAL)
  481. dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  482. label = _("Enter name of signature file:")),
  483. proportion = 0, flag = wx.ALL, border = 3)
  484. self.fileNameCtrl = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (400, -1))
  485. if self.fileName:
  486. self.fileNameCtrl.SetValue(self.fileName)
  487. dataSizer.Add(item = self.fileNameCtrl,
  488. proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
  489. dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  490. label = _("Signature file path:")),
  491. proportion = 0, flag = wx.ALL, border = 3)
  492. self.pathPanel = scrolled.ScrolledPanel(self.panel, size = (-1, 40))
  493. pathSizer = wx.BoxSizer()
  494. self.filePathText = wx.StaticText(parent = self.pathPanel, id = wx.ID_ANY,
  495. label = self.baseFilePath)
  496. pathSizer.Add(self.filePathText, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1)
  497. self.pathPanel.SetupScrolling(scroll_x = True, scroll_y = False)
  498. self.pathPanel.SetSizer(pathSizer)
  499. dataSizer.Add(item = self.pathPanel,
  500. proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
  501. # buttons
  502. btnSizer = wx.StdDialogButtonSizer()
  503. btnSizer.AddButton(self.btnCancel)
  504. btnSizer.AddButton(self.btnOK)
  505. btnSizer.Realize()
  506. sizer.Add(item = dataSizer, proportion = 1,
  507. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  508. sizer.Add(item = btnSizer, proportion = 0,
  509. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  510. self.panel.SetSizer(sizer)
  511. sizer.Fit(self)
  512. self.SetMinSize(self.GetSize())
  513. def GetFileName(self, fullPath = False):
  514. """Returns signature file name
  515. :param fullPath: return full path of sig. file
  516. """
  517. if fullPath:
  518. return os.path.join(self.baseFilePath, self.fileNameCtrl.GetValue())
  519. return self.fileNameCtrl.GetValue()
  520. class IClassExportAreasDialog(wx.Dialog):
  521. def __init__(self, parent, vectorName = None, title = _("Export training areas"), id = wx.ID_ANY,
  522. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  523. **kwargs):
  524. """Dialog for export of training areas to vector layer
  525. :param parent: window
  526. :param vectorName: name of vector layer for export
  527. :param title: window title
  528. """
  529. wx.Dialog.__init__(self, parent, id, title, style = style, **kwargs)
  530. self.vectorName = vectorName
  531. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  532. self.btnCancel = wx.Button(parent = self.panel, id = wx.ID_CANCEL)
  533. self.btnOK = wx.Button(parent = self.panel, id = wx.ID_OK)
  534. self.btnOK.SetDefault()
  535. self.btnOK.Enable(False)
  536. self.btnOK.Bind(wx.EVT_BUTTON, self.OnOK)
  537. self.__layout()
  538. self.vectorNameCtrl.Bind(wx.EVT_TEXT, self.OnTextChanged)
  539. self.OnTextChanged(None)
  540. wx.CallAfter(self.vectorNameCtrl.SetFocus)
  541. def OnTextChanged(self, event):
  542. """Name of new vector map given.
  543. Enable/diable OK button.
  544. """
  545. file = self.vectorNameCtrl.GetValue()
  546. if len(file) > 0:
  547. self.btnOK.Enable(True)
  548. else:
  549. self.btnOK.Enable(False)
  550. def __layout(self):
  551. """Do layout"""
  552. sizer = wx.BoxSizer(wx.VERTICAL)
  553. dataSizer = wx.BoxSizer(wx.VERTICAL)
  554. dataSizer.Add(item = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  555. label = _("Enter name of new vector map:")),
  556. proportion = 0, flag = wx.ALL, border = 3)
  557. self.vectorNameCtrl = gselect.Select(parent = self.panel, type = 'vector',
  558. mapsets = [grass.gisenv()['MAPSET']],
  559. size = globalvar.DIALOG_GSELECT_SIZE)
  560. if self.vectorName:
  561. self.vectorNameCtrl.SetValue(self.vectorName)
  562. dataSizer.Add(item = self.vectorNameCtrl,
  563. proportion = 0, flag = wx.ALL | wx.EXPAND, border = 3)
  564. self.withTableCtrl = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  565. label = _("Export attribute table"))
  566. self.withTableCtrl.SetValue(True)
  567. self.withTableCtrl.SetToolTipString(_("Export attribute table containing"
  568. " computed statistical data"))
  569. dataSizer.Add(item = self.withTableCtrl,
  570. proportion = 0, flag = wx.ALL, border = 3)
  571. # buttons
  572. btnSizer = wx.StdDialogButtonSizer()
  573. btnSizer.AddButton(self.btnCancel)
  574. btnSizer.AddButton(self.btnOK)
  575. btnSizer.Realize()
  576. sizer.Add(item = dataSizer, proportion = 1,
  577. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  578. sizer.Add(item = btnSizer, proportion = 0,
  579. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  580. self.panel.SetSizer(sizer)
  581. sizer.Fit(self)
  582. self.SetMinSize(self.GetSize())
  583. def GetVectorName(self):
  584. """Returns vector name"""
  585. return self.vectorNameCtrl.GetValue()
  586. def WithTable(self):
  587. """Returns true if attribute table should be exported too"""
  588. return self.withTableCtrl.IsChecked()
  589. def OnOK(self, event):
  590. """Checks if map exists and can be overwritten."""
  591. overwrite = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  592. vName = self.GetVectorName()
  593. res = grass.find_file(vName, element = 'vector')
  594. if res['fullname'] and overwrite is False:
  595. qdlg = wx.MessageDialog(parent = self,
  596. message = _("Vector map <%s> already exists."
  597. " Do you want to overwrite it?" % vName) ,
  598. caption = _("Vector <%s> exists" % vName),
  599. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  600. if qdlg.ShowModal() == wx.ID_YES:
  601. event.Skip()
  602. qdlg.Destroy()
  603. else:
  604. event.Skip()