controller.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. # -*- coding: utf-8 -*-
  2. """
  3. @package rdigit.controller
  4. @brief rdigit controller for drawing and rasterizing
  5. Classes:
  6. - controller::RDigitController
  7. (C) 2014 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. @author Anna Petrasova <kratochanna gmail.com>
  12. """
  13. import os
  14. import tempfile
  15. import wx
  16. import uuid
  17. from wx.lib.newevent import NewEvent
  18. from grass.script import core as gcore
  19. from grass.script import raster as grast
  20. from grass.exceptions import CalledModuleError, ScriptError
  21. from grass.pydispatch.signal import Signal
  22. from core.gcmd import GError, GMessage
  23. from core.settings import UserSettings
  24. from core.gthread import gThread
  25. from rdigit.dialogs import NewRasterDialog
  26. updateProgress, EVT_UPDATE_PROGRESS = NewEvent()
  27. class RDigitController(wx.EvtHandler):
  28. """Controller object for raster digitizer.
  29. Inherits from EvtHandler to be able to send wx events from thraed.
  30. """
  31. def __init__(self, giface, mapWindow):
  32. """Constructs controller
  33. :param giface: grass interface object
  34. :param mapWindow: instance of BufferedMapWindow
  35. """
  36. wx.EvtHandler.__init__(self)
  37. self._giface = giface
  38. self._mapWindow = mapWindow
  39. # thread for running rasterization process
  40. self._thread = gThread()
  41. # name of raster map which is edited (also new one)
  42. self._editedRaster = None
  43. # name of optional background raster
  44. self._backgroundRaster = None
  45. # name of temporary raster used to backup original state
  46. self._backupRasterName = None
  47. # GraphicsSet for drawing areas, lines, points
  48. self._areas = None
  49. self._lines = None
  50. self._points = None
  51. # list of all GraphicsItems in the order of drawing
  52. self._all = []
  53. # if in state of drawing lin or area
  54. self._drawing = False
  55. # if running digitizing process in thread (to block drawing)
  56. self._running = False
  57. # color used to draw (should be moved to settings)
  58. self._drawColor = wx.GREEN
  59. # transparency used to draw (should be moved to settings)
  60. self._drawTransparency = 100
  61. # current selected drawing method
  62. self._graphicsType = 'area'
  63. # last edited cell value
  64. self._currentCellValue = None
  65. # last edited buffer value
  66. self._currentWidthValue = None
  67. self._oldMouseUse = None
  68. self._oldCursor = None
  69. # signal to add new raster to toolbar items
  70. self.newRasterCreated = Signal('RDigitController:newRasterCreated')
  71. # signal to add just used cell value in toolbar combo
  72. self.newFeatureCreated = Signal('RDigitController:newFeatureCreated')
  73. # signal to upload unique categories of background map into toolbar combo
  74. self.uploadMapCategories = Signal('RDigitController:uploadMapCategories')
  75. self.quitDigitizer = Signal('RDigitController:quitDigitizer')
  76. self.showNotification = Signal('RDigitController:showNotification')
  77. def _connectAll(self):
  78. self._mapWindow.mouseLeftDown.connect(self._start)
  79. self._mapWindow.mouseLeftUp.connect(self._addPoint)
  80. self._mapWindow.mouseRightUp.connect(self._finish)
  81. self._mapWindow.Unbind(wx.EVT_CONTEXT_MENU)
  82. def _disconnectAll(self):
  83. self._mapWindow.mouseLeftDown.disconnect(self._start)
  84. self._mapWindow.mouseLeftUp.disconnect(self._addPoint)
  85. self._mapWindow.mouseRightUp.connect(self._finish)
  86. self._mapWindow.Bind(wx.EVT_CONTEXT_MENU, self._mapWindow.OnContextMenu)
  87. def _start(self, x, y):
  88. """Start digitizing a new object.
  89. :param x: x coordinate in map units
  90. :param y: y coordinate in map units
  91. """
  92. if self._running:
  93. return
  94. if not self._editedRaster:
  95. GMessage(parent=self._mapWindow, message=_("Please select first the raster map"))
  96. return
  97. if not self._drawing:
  98. if self._graphicsType == 'area':
  99. item = self._areas.AddItem(coords=[])
  100. item.SetPropertyVal('penName', 'pen1')
  101. self._all.append(item)
  102. elif self._graphicsType == 'line':
  103. item = self._lines.AddItem(coords=[])
  104. item.SetPropertyVal('penName', 'pen1')
  105. self._all.append(item)
  106. elif self._graphicsType == 'point':
  107. item = self._points.AddItem(coords=[])
  108. item.SetPropertyVal('penName', 'pen1')
  109. self._all.append(item)
  110. self._drawing = True
  111. def _addPoint(self, x, y):
  112. """Add point to an object.
  113. :param x: x coordinate in map units
  114. :param y: y coordinate in map units
  115. """
  116. if self._running:
  117. return
  118. if not self._drawing:
  119. return
  120. if self._graphicsType == 'area':
  121. area = self._areas.GetItem(-1)
  122. coords = area.GetCoords() + [[x, y]]
  123. area.SetCoords(coords)
  124. self.showNotification.emit(text=_("Right click to finish area"))
  125. elif self._graphicsType == 'line':
  126. line = self._lines.GetItem(-1)
  127. coords = line.GetCoords() + [[x, y]]
  128. line.SetCoords(coords)
  129. self.showNotification.emit(text=_("Right click to finish line"))
  130. elif self._graphicsType == 'point':
  131. point = self._points.GetItem(-1)
  132. point.SetCoords([x, y])
  133. self._finish(x, y)
  134. # draw
  135. self._mapWindow.ClearLines()
  136. self._lines.Draw(pdc=self._mapWindow.pdcTmp)
  137. self._areas.Draw(pdc=self._mapWindow.pdcTmp)
  138. self._points.Draw(pdc=self._mapWindow.pdcTmp)
  139. self._mapWindow.Refresh()
  140. def _finish(self, x, y):
  141. """Finish digitizing a new object and redraws.
  142. Saves current cell value and buffer width for that object.
  143. :param x: x coordinate in map units
  144. :param y: y coordinate in map units
  145. """
  146. if self._running:
  147. return
  148. if self._graphicsType == 'point':
  149. item = self._points.GetItem(-1)
  150. elif self._graphicsType == 'area':
  151. item = self._areas.GetItem(-1)
  152. elif self._graphicsType == 'line':
  153. item = self._lines.GetItem(-1)
  154. else:
  155. return
  156. self._drawing = False
  157. item.SetPropertyVal('brushName', 'done')
  158. item.AddProperty('cellValue')
  159. item.AddProperty('widthValue')
  160. item.SetPropertyVal('cellValue', self._currentCellValue)
  161. item.SetPropertyVal('widthValue', self._currentWidthValue)
  162. self.newFeatureCreated.emit()
  163. self._mapWindow.ClearLines()
  164. self._points.Draw(pdc=self._mapWindow.pdcTmp)
  165. self._areas.Draw(pdc=self._mapWindow.pdcTmp)
  166. self._lines.Draw(pdc=self._mapWindow.pdcTmp)
  167. self._mapWindow.Refresh()
  168. def SelectType(self, drawingType):
  169. """Selects method (area/line/point) for drawing.
  170. Connects and disconnects signal to allow other tools
  171. in map toolbar to work.
  172. """
  173. if self._graphicsType and not drawingType:
  174. self._mapWindow.ClearLines(pdc=self._mapWindow.pdcTmp)
  175. self._mapWindow.mouse['end'] = self._mapWindow.mouse['begin']
  176. # disconnect mouse events
  177. self._disconnectAll()
  178. self._mapWindow.SetNamedCursor(self._oldCursor)
  179. self._mapWindow.mouse['use'] = self._oldMouseUse
  180. elif self._graphicsType is None and drawingType:
  181. self._connectAll()
  182. # change mouse['box'] and pen to draw line during dragging
  183. # TODO: better solution for drawing this line
  184. self._mapWindow.mouse['use'] = None
  185. self._mapWindow.mouse['box'] = "line"
  186. self._mapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  187. # change the cursor
  188. self._mapWindow.SetNamedCursor('pencil')
  189. self._graphicsType = drawingType
  190. def SetCellValue(self, value):
  191. self._currentCellValue = value
  192. def SetWidthValue(self, value):
  193. self._currentWidthValue = value
  194. def ChangeDrawColor(self, color):
  195. self._drawColor = color[:3] + (self._drawTransparency,)
  196. for each in (self._areas, self._lines, self._points):
  197. each.GetPen('pen1').SetColour(self._drawColor)
  198. each.GetBrush('done').SetColour(self._drawColor)
  199. self._mapWindow.UpdateMap(render=False)
  200. def Start(self):
  201. """Registers graphics to map window,
  202. connect required mouse signals.
  203. """
  204. self._oldMouseUse = self._mapWindow.mouse['use']
  205. self._oldCursor = self._mapWindow.GetNamedCursor()
  206. self._connectAll()
  207. # change mouse['box'] and pen to draw line during dragging
  208. # TODO: better solution for drawing this line
  209. self._mapWindow.mouse['use'] = None
  210. self._mapWindow.mouse['box'] = "line"
  211. self._mapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  212. color = self._drawColor[:3] + (self._drawTransparency,)
  213. self._areas = self._mapWindow.RegisterGraphicsToDraw(graphicsType='polygon',
  214. mapCoords=True)
  215. self._areas.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
  216. self._areas.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
  217. self._lines = self._mapWindow.RegisterGraphicsToDraw(graphicsType='line',
  218. mapCoords=True)
  219. self._lines.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
  220. self._lines.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
  221. self._points = self._mapWindow.RegisterGraphicsToDraw(graphicsType='point',
  222. mapCoords=True)
  223. self._points.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
  224. self._points.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
  225. # change the cursor
  226. self._mapWindow.SetNamedCursor('pencil')
  227. def Stop(self):
  228. """Before stopping digitizer, asks to save edits"""
  229. dlg = wx.MessageDialog(self._mapWindow, _("Do you want to save changes?"),
  230. _("Save raster map changes"), wx.YES_NO)
  231. if dlg.ShowModal() == wx.ID_YES:
  232. self._running = True
  233. self._thread.Run(callable=self._exportRaster,
  234. ondone=lambda event: self._updateAndQuit())
  235. else:
  236. self.quitDigitizer.emit()
  237. def Save(self):
  238. """Saves current edits to a raster map"""
  239. self._thread.Run(callable=self._exportRaster,
  240. ondone=lambda event: self._update())
  241. def Undo(self):
  242. """Undo a change, goes object back (finished or not finished)"""
  243. if len(self._all):
  244. removed = self._all.pop(-1)
  245. # try to remove from each, it fails quietly when theitem is not there
  246. self._areas.DeleteItem(removed)
  247. self._lines.DeleteItem(removed)
  248. self._points.DeleteItem(removed)
  249. self._drawing = False
  250. self._mapWindow.UpdateMap(render=False)
  251. def CleanUp(self, restore=True):
  252. """Cleans up drawing, temporary maps.
  253. :param restore: if restore previous cursor, mouse['use']
  254. """
  255. try:
  256. gcore.run_command('g.remove', type='rast', flags='f', name=self._backupRasterName, quiet=True)
  257. except CalledModuleError:
  258. pass
  259. self._mapWindow.ClearLines(pdc=self._mapWindow.pdcTmp)
  260. self._mapWindow.mouse['end'] = self._mapWindow.mouse['begin']
  261. # disconnect mouse events
  262. if self._graphicsType:
  263. self._disconnectAll()
  264. # unregister
  265. self._mapWindow.UnregisterGraphicsToDraw(self._areas)
  266. self._mapWindow.UnregisterGraphicsToDraw(self._lines)
  267. self._mapWindow.UnregisterGraphicsToDraw(self._points)
  268. #self._registeredGraphics = None
  269. self._mapWindow.UpdateMap(render=False)
  270. if restore:
  271. # restore mouse['use'] and cursor to the state before measuring starts
  272. self._mapWindow.SetNamedCursor(self._oldCursor)
  273. self._mapWindow.mouse['use'] = self._oldMouseUse
  274. def _updateAndQuit(self):
  275. """Called when thread is done. Updates map and calls to quits digitizer."""
  276. self._running = False
  277. self._mapWindow.UpdateMap(render=True)
  278. self.quitDigitizer.emit()
  279. def _update(self):
  280. """Called when thread is done. Updates map."""
  281. self._running = False
  282. self._mapWindow.UpdateMap(render=True)
  283. def SelectOldMap(self, name):
  284. """After selecting old raster, creates a backup copy for editing."""
  285. try:
  286. self._backupRaster(name)
  287. except ScriptError:
  288. GError(parent=self._mapWindow, message=_("Failed to create backup copy of edited raster map."))
  289. return False
  290. self._editedRaster = name
  291. return True
  292. def SelectNewMap(self):
  293. """After selecting new raster, shows dialog to choose name,
  294. background map and type of the new map."""
  295. dlg = NewRasterDialog(parent=self._mapWindow)
  296. if dlg.ShowModal() == wx.ID_OK:
  297. try:
  298. self._createNewMap(mapName=dlg.GetMapName(),
  299. backgroundMap=dlg.GetBackgroundMapName(),
  300. mapType=dlg.GetMapType())
  301. except ScriptError:
  302. GError(parent=self._mapWindow, message=_("Failed to create new raster map."))
  303. return False
  304. finally:
  305. dlg.Destroy()
  306. return True
  307. else:
  308. dlg.Destroy()
  309. return False
  310. def _createNewMap(self, mapName, backgroundMap, mapType):
  311. """Creates a new raster map based on specified background and type."""
  312. name = mapName.split('@')[0]
  313. background = backgroundMap.split('@')[0]
  314. types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'}
  315. if background:
  316. back = background
  317. else:
  318. back = 'null()'
  319. try:
  320. grast.mapcalc(exp="{name} = {mtype}({back})".format(name=name, mtype=types[mapType],
  321. back=back),
  322. overwrite=True, quiet=True)
  323. if background:
  324. self._backgroundRaster = backgroundMap
  325. gcore.run_command('r.colors', map=name, raster=self._backgroundRaster, quiet=True)
  326. if mapType == 'CELL':
  327. values = gcore.read_command('r.describe', flags='1n',
  328. map=backgroundMap, quiet=True).strip()
  329. if values:
  330. self.uploadMapCategories.emit(values=values.split('\n'))
  331. except CalledModuleError:
  332. raise ScriptError
  333. self._backupRaster(name)
  334. name = name + '@' + gcore.gisenv()['MAPSET']
  335. self._editedRaster = name
  336. self.newRasterCreated.emit(name=name)
  337. def _backupRaster(self, name):
  338. """Creates a temporary backup raster necessary for undo behavior.
  339. :param str name: name of raster map for which we create backup
  340. """
  341. name = name.split('@')[0]
  342. backup = name + '_backupcopy_' + str(os.getpid())
  343. try:
  344. gcore.run_command('g.copy', rast=[name, backup], quiet=True)
  345. except CalledModuleError:
  346. raise ScriptError
  347. self._backupRasterName = backup
  348. def _exportRaster(self):
  349. """Rasterizes digitized features.
  350. Uses r.in.poly and r.grow for buffering features. Creates separate raster
  351. maps depending on common cell values and buffering width necessary to
  352. keep the order of editing. These rasters are then patched together.
  353. Sets default color table for the newly digitized raster.
  354. """
  355. if not self._editedRaster:
  356. return
  357. if len(self._all) < 1:
  358. return
  359. tempRaster = 'tmp_rdigit_rast_' + str(os.getpid())
  360. text = []
  361. rastersToPatch = []
  362. i = 0
  363. lastCellValue = lastWidthValue = None
  364. evt = updateProgress(range=len(self._all), value=0, text=_("Rasterizing..."))
  365. wx.PostEvent(self, evt)
  366. lastCellValue = self._all[0].GetPropertyVal('cellValue')
  367. lastWidthValue = self._all[0].GetPropertyVal('widthValue')
  368. for item in self._all:
  369. if item.GetPropertyVal('widthValue') and \
  370. (lastCellValue != item.GetPropertyVal('cellValue') or
  371. lastWidthValue != item.GetPropertyVal('widthValue')):
  372. if text:
  373. out = self._rasterize(text, lastWidthValue, tempRaster)
  374. rastersToPatch.append(out)
  375. text = []
  376. self._writeItem(item, text)
  377. out = self._rasterize(text, item.GetPropertyVal('widthValue'),
  378. tempRaster)
  379. rastersToPatch.append(out)
  380. text = []
  381. else:
  382. self._writeItem(item, text)
  383. lastCellValue = item.GetPropertyVal('cellValue')
  384. lastWidthValue = item.GetPropertyVal('widthValue')
  385. i += 1
  386. evt = updateProgress(range=len(self._all), value=i, text=_("Rasterizing..."))
  387. wx.PostEvent(self, evt)
  388. if text:
  389. out = self._rasterize(text, item.GetPropertyVal('widthValue'),
  390. tempRaster)
  391. rastersToPatch.append(out)
  392. gcore.run_command('r.patch', input=sorted(rastersToPatch, reverse=True) + [self._backupRasterName],
  393. output=self._editedRaster, overwrite=True, quiet=True)
  394. gcore.run_command('g.remove', type='rast', flags='f', name=rastersToPatch + [tempRaster],
  395. quiet=True)
  396. try:
  397. if not self._backgroundRaster:
  398. table = UserSettings.Get(group='rasterLayer', key='colorTable', subkey='selection')
  399. gcore.run_command('r.colors', color=table, map=self._editedRaster, quiet=True)
  400. else:
  401. gcore.run_command('r.colors', map=self._editedRaster,
  402. raster=self._backgroundRaster, quiet=True)
  403. except CalledModuleError:
  404. GError(parent=self._mapWindow,
  405. message=_("Failed to set default color table for edited raster map"))
  406. def _writeFeature(self, item, vtype, text):
  407. """Writes digitized features in r.in.poly format."""
  408. coords = item.GetCoords()
  409. if vtype == 'P':
  410. coords = [coords]
  411. cellValue = item.GetPropertyVal('cellValue')
  412. record = '{vtype}\n'.format(vtype=vtype)
  413. for coord in coords:
  414. record += ' '.join([str(c) for c in coord])
  415. record += '\n'
  416. record += '= {cellValue}\n'.format(cellValue=cellValue)
  417. text.append(record)
  418. def _writeItem(self, item, text):
  419. if item in self._areas.GetAllItems():
  420. self._writeFeature(item, vtype='A', text=text)
  421. elif item in self._lines.GetAllItems():
  422. self._writeFeature(item, vtype='L', text=text)
  423. elif item in self._points.GetAllItems():
  424. self._writeFeature(item, vtype='P', text=text)
  425. def _rasterize(self, text, bufferDist, tempRaster):
  426. """Performs the actual rasterization using r.in.poly
  427. and buffering with r.grow if required.
  428. :param str text: string in r.in.poly format
  429. :param float bufferDist: buffer distance in map units
  430. :param str tempRaster: name of temporary raster used in computation
  431. :return: output raster map name as a result of digitization
  432. """
  433. output = 'x' + str(uuid.uuid4())[:8]
  434. asciiFile = tempfile.NamedTemporaryFile(delete=False)
  435. asciiFile.write('\n'.join(text))
  436. asciiFile.close()
  437. if bufferDist:
  438. gcore.run_command('r.in.poly', input=asciiFile.name, output=tempRaster,
  439. overwrite=True, quiet=True)
  440. gcore.run_command('r.grow', input=tempRaster, output=output,
  441. flags='m', radius=bufferDist, quiet=True)
  442. else:
  443. gcore.run_command('r.in.poly', input=asciiFile.name, output=output,
  444. quiet=True)
  445. os.unlink(asciiFile.name)
  446. return output