dialogs.py 27 KB

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