dialogs.py 26 KB

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