vclean.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. """
  2. @package modules.vclean
  3. @brief Dialog for interactive construction of vector cleaning
  4. operations
  5. Classes:
  6. - vclean::VectorCleaningFrame
  7. (C) 2010-2011 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Markus Metz
  11. """
  12. import os
  13. import sys
  14. import wx
  15. import wx.lib.scrolledpanel as scrolled
  16. if __name__ == '__main__':
  17. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  18. from core.gcmd import RunCommand, GError
  19. from core import globalvar
  20. from gui_core.gselect import Select
  21. from core.settings import UserSettings
  22. class VectorCleaningFrame(wx.Frame):
  23. def __init__(self, parent, id=wx.ID_ANY, title=_('Set up vector cleaning tools'),
  24. style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
  25. **kwargs):
  26. """!
  27. Dialog for interactively defining vector cleaning tools
  28. """
  29. wx.Frame.__init__(self, parent, id, title, style=style, **kwargs)
  30. self.parent = parent # GMFrame
  31. if self.parent:
  32. self.log = self.parent.GetLogWindow()
  33. else:
  34. self.log = None
  35. # grass command
  36. self.cmd = 'v.clean'
  37. # statusbar
  38. self.CreateStatusBar()
  39. # icon
  40. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  41. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  42. # input map to clean
  43. self.inmap = ''
  44. # cleaned output map
  45. self.outmap = ''
  46. self.ftype = ''
  47. # cleaning tools
  48. self.toolslines = {}
  49. self.tool_desc_list = [
  50. _('break lines/boundaries'),
  51. _('remove duplicates'),
  52. _('remove dangles'),
  53. _('change boundary dangles to lines'),
  54. _('remove bridges'),
  55. _('change bridges to lines'),
  56. _('snap lines/boundaries'),
  57. _('remove duplicate area centroids'),
  58. _('break polygons'),
  59. _('prune lines/boundaries'),
  60. _('remove small areas'),
  61. _('remove lines/boundaries of zero length'),
  62. _('remove small angles at nodes')
  63. ]
  64. self.tool_list = [
  65. 'break',
  66. 'rmdupl',
  67. 'rmdangle',
  68. 'chdangle',
  69. 'rmbridge',
  70. 'chbridge',
  71. 'snap',
  72. 'rmdac',
  73. 'bpol',
  74. 'prune',
  75. 'rmarea',
  76. 'rmline',
  77. 'rmsa'
  78. ]
  79. self.ftype = [
  80. 'point',
  81. 'line',
  82. 'boundary',
  83. 'centroid',
  84. 'area',
  85. 'face']
  86. self.n_ftypes = len(self.ftype)
  87. self.tools_string = ''
  88. self.thresh_string = ''
  89. self.ftype_string = ''
  90. self.SetStatusText(_("Set up vector cleaning tools"))
  91. self.elem = 'vector'
  92. self.ctlabel = _('Choose cleaning tools and set thresholds')
  93. # top controls
  94. self.inmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  95. label=_('Select input vector map:'))
  96. self.selectionInput = Select(parent=self.panel, id=wx.ID_ANY,
  97. size=globalvar.DIALOG_GSELECT_SIZE,
  98. type='vector')
  99. self.ftype_check = {}
  100. ftypeBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  101. label=_(' Feature type: '))
  102. self.ftypeSizer = wx.StaticBoxSizer(ftypeBox, wx.HORIZONTAL)
  103. self.outmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  104. label=_('Select output vector map:'))
  105. self.selectionOutput = Select(parent=self.panel, id=wx.ID_ANY,
  106. size=globalvar.DIALOG_GSELECT_SIZE,
  107. type='vector')
  108. self.overwrite = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
  109. label=_('Allow output files to overwrite existing files'))
  110. self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  111. # cleaning tools
  112. self.ct_label = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  113. label=self.ctlabel)
  114. self.ct_panel = self._toolsPanel()
  115. # buttons to manage cleaning tools
  116. self.btn_add = wx.Button(parent=self.panel, id=wx.ID_ADD)
  117. self.btn_remove = wx.Button(parent=self.panel, id=wx.ID_REMOVE)
  118. self.btn_moveup = wx.Button(parent=self.panel, id=wx.ID_UP)
  119. self.btn_movedown = wx.Button(parent=self.panel, id=wx.ID_DOWN)
  120. # add one tool as default
  121. self.AddTool()
  122. self.selected = -1
  123. # Buttons
  124. self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
  125. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Run"))
  126. self.btn_run.SetDefault()
  127. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  128. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  129. self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
  130. # bindings
  131. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  132. self.btn_run.Bind(wx.EVT_BUTTON, self.OnCleaningRun)
  133. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  134. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  135. self.btn_add.Bind(wx.EVT_BUTTON, self.OnAddTool)
  136. self.btn_remove.Bind(wx.EVT_BUTTON, self.OnClearTool)
  137. self.btn_moveup.Bind(wx.EVT_BUTTON, self.OnMoveToolUp)
  138. self.btn_movedown.Bind(wx.EVT_BUTTON, self.OnMoveToolDown)
  139. # layout
  140. self._layout()
  141. self.SetMinSize(self.GetBestSize())
  142. self.CentreOnScreen()
  143. def _layout(self):
  144. sizer = wx.BoxSizer(wx.VERTICAL)
  145. #
  146. # input output
  147. #
  148. inSizer = wx.GridBagSizer(hgap=5, vgap=5)
  149. inSizer.Add(item=self.inmaplabel, pos=(0, 0),
  150. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  151. inSizer.Add(item=self.selectionInput, pos=(1, 0),
  152. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  153. self.ftype_check = [
  154. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('point')),
  155. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('line')),
  156. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('boundary')),
  157. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('centroid')),
  158. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('area')),
  159. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('face'))
  160. ]
  161. typeoptSizer = wx.BoxSizer(wx.HORIZONTAL)
  162. for num in range(0, self.n_ftypes):
  163. type_box = self.ftype_check[num]
  164. typeoptSizer.Add(item=type_box, flag=wx.ALIGN_LEFT, border=1)
  165. self.ftypeSizer.Add(item=typeoptSizer,
  166. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=2)
  167. outSizer = wx.GridBagSizer(hgap=5, vgap=5)
  168. outSizer.Add(item=self.outmaplabel, pos=(0, 0),
  169. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  170. outSizer.Add(item=self.selectionOutput, pos=(1, 0),
  171. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  172. replaceSizer = wx.BoxSizer(wx.HORIZONTAL)
  173. replaceSizer.Add(item=self.overwrite, proportion=1,
  174. flag=wx.ALL | wx.EXPAND, border=1)
  175. outSizer.Add(item=replaceSizer, pos=(2, 0),
  176. flag=wx.ALL | wx.EXPAND, border=1)
  177. #
  178. # tools selection
  179. #
  180. bodySizer = wx.GridBagSizer(hgap=5, vgap=5)
  181. bodySizer.Add(item=self.ct_label, pos=(0, 0), span=(1, 2),
  182. flag=wx.ALL, border=5)
  183. bodySizer.Add(item=self.ct_panel, pos=(1, 0), span=(1, 2))
  184. manageBoxSizer = wx.GridBagSizer(hgap=10, vgap=1)
  185. # start with row 1 for nicer layout
  186. manageBoxSizer.Add(item=self.btn_add, pos=(1, 0), border=2, flag=wx.ALL | wx.EXPAND)
  187. manageBoxSizer.Add(item=self.btn_remove, pos=(2, 0), border=2, flag=wx.ALL | wx.EXPAND)
  188. manageBoxSizer.Add(item=self.btn_moveup, pos=(3, 0), border=2, flag=wx.ALL | wx.EXPAND)
  189. manageBoxSizer.Add(item=self.btn_movedown, pos=(4, 0), border=2, flag=wx.ALL | wx.EXPAND)
  190. bodySizer.Add(item=manageBoxSizer, pos=(1, 2),
  191. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
  192. bodySizer.AddGrowableCol(2)
  193. #
  194. # standard buttons
  195. #
  196. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  197. btnSizer.Add(self.btn_close,
  198. flag=wx.LEFT | wx.RIGHT, border=5)
  199. btnSizer.Add(self.btn_run,
  200. flag=wx.LEFT | wx.RIGHT, border=5)
  201. btnSizer.Add(self.btn_clipboard,
  202. flag=wx.LEFT | wx.RIGHT, border=5)
  203. btnSizer.Add(self.btn_help,
  204. flag=wx.LEFT | wx.RIGHT, border=5)
  205. #
  206. # put it all together
  207. #
  208. sizer.Add(item=inSizer, proportion=0,
  209. flag=wx.ALL | wx.EXPAND, border=5)
  210. sizer.Add(item=self.ftypeSizer, proportion=0,
  211. flag=wx.ALL | wx.EXPAND, border=5)
  212. sizer.Add(item=outSizer, proportion=0,
  213. flag=wx.ALL | wx.EXPAND, border=5)
  214. sizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
  215. style=wx.LI_HORIZONTAL), proportion=0,
  216. flag=wx.EXPAND | wx.ALL, border=5)
  217. sizer.Add(item=bodySizer, proportion=1,
  218. flag=wx.ALL | wx.EXPAND, border=5)
  219. sizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
  220. style=wx.LI_HORIZONTAL), proportion=0,
  221. flag=wx.EXPAND | wx.ALL, border=5)
  222. sizer.Add(item=btnSizer, proportion=0,
  223. flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
  224. self.panel.SetAutoLayout(True)
  225. self.panel.SetSizer(sizer)
  226. sizer.Fit(self.panel)
  227. self.Layout()
  228. def _toolsPanel(self):
  229. ct_panel = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY,
  230. size=(500, 240),
  231. style=wx.SUNKEN_BORDER)
  232. self.ct_sizer = wx.GridBagSizer(vgap=2, hgap=4)
  233. ct_panel.SetSizer(self.ct_sizer)
  234. ct_panel.SetAutoLayout(True)
  235. return ct_panel
  236. def OnAddTool(self, event):
  237. """!Add tool button pressed"""
  238. self.AddTool()
  239. def AddTool(self):
  240. snum = len(self.toolslines.keys())
  241. num = snum + 1
  242. # tool number
  243. tool_no = wx.StaticText(parent=self.ct_panel, id=3000 + num,
  244. label=str(num) + '.')
  245. # tool
  246. tool_cbox = wx.ComboBox(parent=self.ct_panel, id=1000 + num,
  247. size=(300, -1), choices=self.tool_desc_list,
  248. style=wx.CB_DROPDOWN |
  249. wx.CB_READONLY | wx.TE_PROCESS_ENTER)
  250. self.Bind(wx.EVT_COMBOBOX, self.OnSetTool, tool_cbox)
  251. # threshold
  252. txt_ctrl = wx.TextCtrl(parent=self.ct_panel, id=2000 + num, value='0.00',
  253. size=(100, -1),
  254. style=wx.TE_NOHIDESEL)
  255. self.Bind(wx.EVT_TEXT, self.OnThreshValue, txt_ctrl)
  256. # select
  257. select = wx.CheckBox(parent=self.ct_panel, id=num)
  258. select.SetValue(False)
  259. self.Bind(wx.EVT_CHECKBOX, self.OnSelect, select)
  260. # start with row 1 and col 1 for nicer layout
  261. self.ct_sizer.Add(item=tool_no, pos=(num, 1),
  262. flag=wx.ALIGN_CENTER_VERTICAL, border=5)
  263. self.ct_sizer.Add(item=tool_cbox, pos=(num, 2),
  264. flag=wx.ALIGN_CENTER | wx.RIGHT, border=5)
  265. self.ct_sizer.Add(item=txt_ctrl, pos=(num, 3),
  266. flag=wx.ALIGN_CENTER | wx.RIGHT, border=5)
  267. self.ct_sizer.Add(item=select, pos=(num, 4),
  268. flag=wx.ALIGN_CENTER | wx.RIGHT)
  269. self.toolslines[num] = {'tool_desc': '',
  270. 'tool': '',
  271. 'thresh': '0.00'}
  272. self.ct_panel.Layout()
  273. self.ct_panel.SetupScrolling()
  274. def OnClearTool(self, event):
  275. """!Remove tool button pressed"""
  276. id = self.selected
  277. if id > 0:
  278. self.FindWindowById(id + 1000).SetValue('')
  279. self.toolslines[id]['tool_desc'] = ''
  280. self.toolslines[id]['tool'] = ''
  281. self.SetStatusText(_("%s. cleaning tool removed, will be ignored") % id)
  282. else:
  283. self.SetStatusText(_("Please select a cleaning tool to remove"))
  284. def OnMoveToolUp(self, event):
  285. """!Move up tool button pressed"""
  286. id = self.selected
  287. if id > 1:
  288. id_up = id - 1
  289. this_toolline = self.toolslines[id]
  290. up_toolline = self.toolslines[id_up]
  291. self.FindWindowById(id_up).SetValue(True)
  292. self.FindWindowById(id_up + 1000).SetValue(this_toolline['tool_desc'])
  293. self.FindWindowById(id_up + 2000).SetValue(this_toolline['thresh'])
  294. self.toolslines[id_up] = this_toolline
  295. self.FindWindowById(id).SetValue(False)
  296. self.FindWindowById(id + 1000).SetValue(up_toolline['tool_desc'])
  297. self.FindWindowById(id + 2000).SetValue(up_toolline['thresh'])
  298. self.toolslines[id] = up_toolline
  299. self.selected = id_up
  300. self.SetStatusText(_("%s. cleaning tool moved up") % id)
  301. elif id == 1:
  302. self.SetStatusText(_("1. cleaning tool can not be moved up "))
  303. elif id == -1:
  304. self.SetStatusText(_("Please select a cleaning tool to move up"))
  305. def OnMoveToolDown(self, event):
  306. """!Move down tool button pressed"""
  307. id = self.selected
  308. snum = len(self.toolslines.keys())
  309. if id > 0 and id < snum:
  310. id_down = id + 1
  311. this_toolline = self.toolslines[id]
  312. down_toolline = self.toolslines[id_down]
  313. self.FindWindowById(id_down).SetValue(True)
  314. self.FindWindowById(id_down + 1000).SetValue(this_toolline['tool_desc'])
  315. self.FindWindowById(id_down + 2000).SetValue(this_toolline['thresh'])
  316. self.toolslines[id_down] = this_toolline
  317. self.FindWindowById(id).SetValue(False)
  318. self.FindWindowById(id + 1000).SetValue(down_toolline['tool_desc'])
  319. self.FindWindowById(id + 2000).SetValue(down_toolline['thresh'])
  320. self.toolslines[id] = down_toolline
  321. self.selected = id_down
  322. self.SetStatusText(_("%s. cleaning tool moved down") % id)
  323. elif id == snum:
  324. self.SetStatusText(_("Last cleaning tool can not be moved down "))
  325. elif id == -1:
  326. self.SetStatusText(_("Please select a cleaning tool to move down"))
  327. def OnSetTool(self, event):
  328. """!Tool was defined"""
  329. id = event.GetId()
  330. tool_no = id - 1000
  331. num = self.FindWindowById(id).GetCurrentSelection()
  332. self.toolslines[tool_no]['tool_desc'] = self.tool_desc_list[num]
  333. self.toolslines[tool_no]['tool'] = self.tool_list[num]
  334. self.SetStatusText(str(tool_no) + '. ' + _("cleaning tool: '%s'") % (self.tool_list[num]))
  335. def OnThreshValue(self, event):
  336. """!Threshold value was entered"""
  337. id = event.GetId()
  338. num = id - 2000
  339. self.toolslines[num]['thresh'] = self.FindWindowById(id).GetValue()
  340. self.SetStatusText(_("Threshold for %(num)s. tool '%(tool)s': %(thresh)s") % \
  341. {'num': num,
  342. 'tool': self.toolslines[num]['tool'],
  343. 'thresh': self.toolslines[num]['thresh']})
  344. def OnSelect(self, event):
  345. """!Tool was selected"""
  346. id = event.GetId()
  347. if self.selected > -1 and self.selected != id:
  348. win = self.FindWindowById(self.selected)
  349. win.SetValue(False)
  350. if self.selected != id:
  351. self.selected = id
  352. else:
  353. self.selected = -1
  354. def OnDone(self, cmd, returncode):
  355. """!Command done"""
  356. self.SetStatusText('')
  357. def OnCleaningRun(self, event):
  358. """!Builds options and runs v.clean
  359. """
  360. self.GetCmdStrings()
  361. err = list()
  362. for p, name in ((self.inmap, _('Name of input vector map')),
  363. (self.outmap, _('Name for output vector map')),
  364. (self.tools_string, _('Tools')),
  365. (self.thresh_string, _('Threshold'))):
  366. if not p:
  367. err.append(_("'%s' not defined") % name)
  368. if err:
  369. GError(_("Some parameters not defined. Operation "
  370. "canceled.\n\n%s") % '\n'.join(err),
  371. parent=self)
  372. return
  373. self.SetStatusText(_("Executing selected cleaning operations..."))
  374. snum = len(self.toolslines.keys())
  375. if self.log:
  376. cmd = [self.cmd,
  377. 'input=%s' % self.inmap,
  378. 'output=%s' % self.outmap,
  379. 'tool=%s' % self.tools_string,
  380. 'thres=%s' % self.thresh_string]
  381. if self.ftype_string:
  382. cmd.append('type=%s' % self.ftype_string)
  383. if self.overwrite.IsChecked():
  384. cmd.append('--overwrite')
  385. self.log.RunCmd(cmd, onDone=self.OnDone)
  386. self.parent.Raise()
  387. else:
  388. if self.overwrite.IsChecked():
  389. overwrite = True
  390. else:
  391. overwrite = False
  392. RunCommand(self.cmd,
  393. input=self.inmap,
  394. output=self.outmap,
  395. type=self.ftype_string,
  396. tool=self.tools_string,
  397. thresh=self.thresh_string,
  398. overwrite=overwrite)
  399. def OnClose(self, event):
  400. self.Destroy()
  401. def OnHelp(self, event):
  402. """!Show GRASS manual page"""
  403. RunCommand('g.manual',
  404. quiet=True,
  405. parent=self,
  406. entry=self.cmd)
  407. def OnCopy(self, event):
  408. """!Copy the command"""
  409. cmddata = wx.TextDataObject()
  410. # get tool and thresh strings
  411. self.GetCmdStrings()
  412. cmdstring = '%s' % (self.cmd)
  413. # list -> string
  414. cmdstring += ' input=%s output=%s type=%s tool=%s thres=%s' % \
  415. (self.inmap, self.outmap, self.ftype_string, self.tools_string, self.thresh_string)
  416. if self.overwrite.IsChecked():
  417. cmdstring += ' --overwrite'
  418. cmddata.SetText(cmdstring)
  419. if wx.TheClipboard.Open():
  420. wx.TheClipboard.SetData(cmddata)
  421. wx.TheClipboard.Close()
  422. self.SetStatusText(_("Vector cleaning command copied to clipboard"))
  423. def GetCmdStrings(self):
  424. self.tools_string = ''
  425. self.thresh_string = ''
  426. self.ftype_string = ''
  427. # feature types
  428. first = 1
  429. for num in range(0, self.n_ftypes - 1):
  430. if self.ftype_check[num].IsChecked():
  431. if first:
  432. self.ftype_string = '%s' % self.ftype[num]
  433. first = 0
  434. else:
  435. self.ftype_string += ',%s' % self.ftype[num]
  436. # cleaning tools
  437. first = 1
  438. snum = len(self.toolslines.keys())
  439. for num in range(1, snum + 1):
  440. if self.toolslines[num]['tool']:
  441. if first:
  442. self.tools_string = '%s' % self.toolslines[num]['tool']
  443. self.thresh_string = '%s' % self.toolslines[num]['thresh']
  444. first = 0
  445. else:
  446. self.tools_string += ',%s' % self.toolslines[num]['tool']
  447. self.thresh_string += ',%s' % self.toolslines[num]['thresh']
  448. self.inmap = self.selectionInput.GetValue()
  449. self.outmap = self.selectionOutput.GetValue()
  450. if __name__ == '__main__':
  451. app = wx.App()
  452. frame = VectorCleaningFrame(parent=None)
  453. frame.Show()
  454. app.MainLoop()