dialogs.py 27 KB

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