controller.py 23 KB

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