controller.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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()
  141. self._areas.Draw()
  142. self._points.Draw()
  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()
  169. self._areas.Draw()
  170. self._lines.Draw()
  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. pdc=self._mapWindow.pdcTransparent,
  223. mapCoords=True)
  224. self._areas.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
  225. self._areas.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
  226. self._lines = self._mapWindow.RegisterGraphicsToDraw(graphicsType='line',
  227. pdc=self._mapWindow.pdcTransparent,
  228. mapCoords=True)
  229. self._lines.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
  230. self._lines.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
  231. self._points = self._mapWindow.RegisterGraphicsToDraw(graphicsType='point',
  232. pdc=self._mapWindow.pdcTransparent,
  233. mapCoords=True)
  234. self._points.AddPen('pen1', wx.Pen(colour=color, width=2, style=wx.SOLID))
  235. self._points.AddBrush('done', wx.Brush(colour=color, style=wx.SOLID))
  236. # change the cursor
  237. self._mapWindow.SetNamedCursor('pencil')
  238. def Stop(self):
  239. """Before stopping digitizer, asks to save edits"""
  240. dlg = wx.MessageDialog(self._mapWindow, _("Do you want to save changes?"),
  241. _("Save raster map changes"), wx.YES_NO)
  242. if dlg.ShowModal() == wx.ID_YES:
  243. self._running = True
  244. self._thread.Run(callable=self._exportRaster,
  245. ondone=lambda event: self._updateAndQuit())
  246. else:
  247. self.quitDigitizer.emit()
  248. def Save(self):
  249. """Saves current edits to a raster map"""
  250. self._thread.Run(callable=self._exportRaster,
  251. ondone=lambda event: self._update())
  252. def Undo(self):
  253. """Undo a change, goes object back (finished or not finished)"""
  254. if len(self._all):
  255. removed = self._all.pop(-1)
  256. # try to remove from each, it fails quietly when theitem is not there
  257. self._areas.DeleteItem(removed)
  258. self._lines.DeleteItem(removed)
  259. self._points.DeleteItem(removed)
  260. self._drawing = False
  261. self._mapWindow.UpdateMap(render=False)
  262. def CleanUp(self, restore=True):
  263. """Cleans up drawing, temporary maps.
  264. :param restore: if restore previous cursor, mouse['use']
  265. """
  266. try:
  267. gcore.run_command('g.remove', type='raster', flags='f', name=self._backupRasterName, quiet=True)
  268. except CalledModuleError:
  269. pass
  270. self._mapWindow.ClearLines(pdc=self._mapWindow.pdcTmp)
  271. self._mapWindow.mouse['end'] = self._mapWindow.mouse['begin']
  272. # disconnect mouse events
  273. if self._graphicsType:
  274. self._disconnectAll()
  275. # unregister
  276. self._mapWindow.UnregisterGraphicsToDraw(self._areas)
  277. self._mapWindow.UnregisterGraphicsToDraw(self._lines)
  278. self._mapWindow.UnregisterGraphicsToDraw(self._points)
  279. #self._registeredGraphics = None
  280. self._mapWindow.UpdateMap(render=False)
  281. if restore:
  282. # restore mouse['use'] and cursor to the state before measuring starts
  283. self._mapWindow.SetNamedCursor(self._oldCursor)
  284. self._mapWindow.mouse['use'] = self._oldMouseUse
  285. def _updateAndQuit(self):
  286. """Called when thread is done. Updates map and calls to quits digitizer."""
  287. self._running = False
  288. self._mapWindow.UpdateMap(render=True)
  289. self.quitDigitizer.emit()
  290. def _update(self):
  291. """Called when thread is done. Updates map."""
  292. self._running = False
  293. self._mapWindow.UpdateMap(render=True)
  294. def SelectOldMap(self, name):
  295. """After selecting old raster, creates a backup copy for editing."""
  296. try:
  297. self._backupRaster(name)
  298. except ScriptError:
  299. GError(parent=self._mapWindow, message=_("Failed to create backup copy of edited raster map."))
  300. return False
  301. self._editedRaster = name
  302. self._mapType = grast.raster_info(map=name)['datatype']
  303. self._editOldRaster = True
  304. return True
  305. def SelectNewMap(self):
  306. """After selecting new raster, shows dialog to choose name,
  307. background map and type of the new map."""
  308. dlg = NewRasterDialog(parent=self._mapWindow)
  309. dlg.CenterOnParent()
  310. if dlg.ShowModal() == wx.ID_OK:
  311. try:
  312. self._createNewMap(mapName=dlg.GetMapName(),
  313. backgroundMap=dlg.GetBackgroundMapName(),
  314. mapType=dlg.GetMapType())
  315. except ScriptError:
  316. GError(parent=self._mapWindow, message=_("Failed to create new raster map."))
  317. return False
  318. finally:
  319. dlg.Destroy()
  320. return True
  321. else:
  322. dlg.Destroy()
  323. return False
  324. def _createNewMap(self, mapName, backgroundMap, mapType):
  325. """Creates a new raster map based on specified background and type."""
  326. name = mapName.split('@')[0]
  327. background = backgroundMap.split('@')[0]
  328. types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'}
  329. if background:
  330. back = background
  331. else:
  332. back = 'null()'
  333. try:
  334. grast.mapcalc(exp="{name} = {mtype}({back})".format(name=name, mtype=types[mapType],
  335. back=back),
  336. overwrite=True, quiet=True)
  337. if background:
  338. self._backgroundRaster = backgroundMap
  339. gcore.run_command('r.colors', map=name, raster=self._backgroundRaster, quiet=True)
  340. if mapType == 'CELL':
  341. values = gcore.read_command('r.describe', flags='1n',
  342. map=name, quiet=True).strip()
  343. if values:
  344. self.uploadMapCategories.emit(values=values.split('\n'))
  345. except CalledModuleError:
  346. raise ScriptError
  347. self._backupRaster(name)
  348. name = name + '@' + gcore.gisenv()['MAPSET']
  349. self._editedRaster = name
  350. self._mapType = mapType
  351. self.newRasterCreated.emit(name=name)
  352. def _backupRaster(self, name):
  353. """Creates a temporary backup raster necessary for undo behavior.
  354. :param str name: name of raster map for which we create backup
  355. """
  356. name = name.split('@')[0]
  357. backup = name + '_backupcopy_' + str(os.getpid())
  358. try:
  359. gcore.run_command('g.copy', raster=[name, backup], quiet=True)
  360. except CalledModuleError:
  361. raise ScriptError
  362. self._backupRasterName = backup
  363. def _exportRaster(self):
  364. """Rasterizes digitized features.
  365. Uses r.in.poly and r.grow for buffering features. Creates separate raster
  366. maps depending on common cell values and buffering width necessary to
  367. keep the order of editing. These rasters are then patched together.
  368. Sets default color table for the newly digitized raster.
  369. """
  370. if not self._editedRaster or self._running:
  371. return
  372. if self._drawing:
  373. self._finish()
  374. if len(self._all) < 1:
  375. return
  376. tempRaster = 'tmp_rdigit_rast_' + str(os.getpid())
  377. text = []
  378. rastersToPatch = []
  379. i = 0
  380. lastCellValue = lastWidthValue = None
  381. evt = updateProgress(range=len(self._all), value=0, text=_("Rasterizing..."))
  382. wx.PostEvent(self, evt)
  383. lastCellValue = self._all[0].GetPropertyVal('cellValue')
  384. lastWidthValue = self._all[0].GetPropertyVal('widthValue')
  385. for item in self._all:
  386. if item.GetPropertyVal('widthValue') and \
  387. (lastCellValue != item.GetPropertyVal('cellValue') or
  388. lastWidthValue != item.GetPropertyVal('widthValue')):
  389. if text:
  390. out = self._rasterize(text, lastWidthValue, self._mapType, tempRaster)
  391. rastersToPatch.append(out)
  392. text = []
  393. self._writeItem(item, text)
  394. out = self._rasterize(text, item.GetPropertyVal('widthValue'),
  395. self._mapType, tempRaster)
  396. rastersToPatch.append(out)
  397. text = []
  398. else:
  399. self._writeItem(item, text)
  400. lastCellValue = item.GetPropertyVal('cellValue')
  401. lastWidthValue = item.GetPropertyVal('widthValue')
  402. i += 1
  403. evt = updateProgress(range=len(self._all), value=i, text=_("Rasterizing..."))
  404. wx.PostEvent(self, evt)
  405. if text:
  406. out = self._rasterize(text, item.GetPropertyVal('widthValue'),
  407. self._mapType, tempRaster)
  408. rastersToPatch.append(out)
  409. gcore.run_command('r.patch', input=rastersToPatch[::-1] + [self._backupRasterName],
  410. output=self._editedRaster, overwrite=True, quiet=True)
  411. gcore.run_command('g.remove', type='raster', flags='f', name=rastersToPatch + [tempRaster],
  412. quiet=True)
  413. try:
  414. # setting the right color table
  415. if self._editOldRaster:
  416. return
  417. if not self._backgroundRaster:
  418. table = UserSettings.Get(group='rasterLayer', key='colorTable', subkey='selection')
  419. if not table:
  420. table = 'rainbow'
  421. gcore.run_command('r.colors', color=table, map=self._editedRaster, quiet=True)
  422. else:
  423. gcore.run_command('r.colors', map=self._editedRaster,
  424. raster=self._backgroundRaster, quiet=True)
  425. except CalledModuleError:
  426. GError(parent=self._mapWindow,
  427. message=_("Failed to set default color table for edited raster map"))
  428. def _writeFeature(self, item, vtype, text):
  429. """Writes digitized features in r.in.poly format."""
  430. coords = item.GetCoords()
  431. if vtype == 'P':
  432. coords = [coords]
  433. cellValue = item.GetPropertyVal('cellValue')
  434. record = '{vtype}\n'.format(vtype=vtype)
  435. for coord in coords:
  436. record += ' '.join([str(c) for c in coord])
  437. record += '\n'
  438. record += '= {cellValue}\n'.format(cellValue=cellValue)
  439. text.append(record)
  440. def _writeItem(self, item, text):
  441. if item in self._areas.GetAllItems():
  442. self._writeFeature(item, vtype='A', text=text)
  443. elif item in self._lines.GetAllItems():
  444. self._writeFeature(item, vtype='L', text=text)
  445. elif item in self._points.GetAllItems():
  446. self._writeFeature(item, vtype='P', text=text)
  447. def _rasterize(self, text, bufferDist, mapType, tempRaster):
  448. """Performs the actual rasterization using r.in.poly
  449. and buffering with r.grow if required.
  450. :param str text: string in r.in.poly format
  451. :param float bufferDist: buffer distance in map units
  452. :param str mapType: CELL, FCELL, DCELL
  453. :param str tempRaster: name of temporary raster used in computation
  454. :return: output raster map name as a result of digitization
  455. """
  456. output = 'x' + str(uuid.uuid4())[:8]
  457. asciiFile = tempfile.NamedTemporaryFile(delete=False)
  458. asciiFile.write('\n'.join(text))
  459. asciiFile.close()
  460. if bufferDist:
  461. bufferDist /= 2.
  462. gcore.run_command('r.in.poly', input=asciiFile.name, output=tempRaster,
  463. type_=mapType, overwrite=True, quiet=True)
  464. gcore.run_command('r.grow', input=tempRaster, output=output,
  465. flags='m', radius=bufferDist, quiet=True)
  466. else:
  467. gcore.run_command('r.in.poly', input=asciiFile.name, output=output,
  468. type_=mapType, quiet=True)
  469. os.unlink(asciiFile.name)
  470. return output