controller.py 21 KB

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