controller.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. self._thread.Run(callable=self._exportRaster,
  267. ondone=lambda event: self._updateAndQuit())
  268. else:
  269. self.quitDigitizer.emit()
  270. def Save(self):
  271. """Saves current edits to a raster map"""
  272. self._thread.Run(callable=self._exportRaster,
  273. ondone=lambda event: self._update())
  274. def Undo(self):
  275. """Undo a change, goes object back (finished or not finished)"""
  276. if len(self._all):
  277. removed = self._all.pop(-1)
  278. # try to remove from each, it fails quietly when theitem is not
  279. # there
  280. self._areas.DeleteItem(removed)
  281. self._lines.DeleteItem(removed)
  282. self._points.DeleteItem(removed)
  283. self._drawing = False
  284. self._mapWindow.UpdateMap(render=False)
  285. def CleanUp(self, restore=True):
  286. """Cleans up drawing, temporary maps.
  287. :param restore: if restore previous cursor, mouse['use']
  288. """
  289. try:
  290. gcore.run_command(
  291. 'g.remove',
  292. type='raster',
  293. flags='f',
  294. name=self._backupRasterName,
  295. quiet=True)
  296. except CalledModuleError:
  297. pass
  298. self._mapWindow.ClearLines(pdc=self._mapWindow.pdcTmp)
  299. self._mapWindow.mouse['end'] = self._mapWindow.mouse['begin']
  300. # disconnect mouse events
  301. if self._graphicsType:
  302. self._disconnectAll()
  303. # unregister
  304. self._mapWindow.UnregisterGraphicsToDraw(self._areas)
  305. self._mapWindow.UnregisterGraphicsToDraw(self._lines)
  306. self._mapWindow.UnregisterGraphicsToDraw(self._points)
  307. #self._registeredGraphics = None
  308. self._mapWindow.UpdateMap(render=False)
  309. if restore:
  310. # restore mouse['use'] and cursor to the state before measuring
  311. # starts
  312. self._mapWindow.SetNamedCursor(self._oldCursor)
  313. self._mapWindow.mouse['use'] = self._oldMouseUse
  314. def _updateAndQuit(self):
  315. """Called when thread is done. Updates map and calls to quits digitizer."""
  316. self._running = False
  317. self._mapWindow.UpdateMap(render=True)
  318. self.quitDigitizer.emit()
  319. def _update(self):
  320. """Called when thread is done. Updates map."""
  321. self._running = False
  322. self._mapWindow.UpdateMap(render=True)
  323. def SelectOldMap(self, name):
  324. """After selecting old raster, creates a backup copy for editing."""
  325. try:
  326. self._backupRaster(name)
  327. except ScriptError:
  328. GError(parent=self._mapWindow, message=_(
  329. "Failed to create backup copy of edited raster map."))
  330. return False
  331. self._editedRaster = name
  332. self._mapType = grast.raster_info(map=name)['datatype']
  333. self._editOldRaster = True
  334. return True
  335. def SelectNewMap(self):
  336. """After selecting new raster, shows dialog to choose name,
  337. background map and type of the new map."""
  338. dlg = NewRasterDialog(parent=self._mapWindow)
  339. dlg.CenterOnParent()
  340. if dlg.ShowModal() == wx.ID_OK:
  341. try:
  342. self._createNewMap(mapName=dlg.GetMapName(),
  343. backgroundMap=dlg.GetBackgroundMapName(),
  344. mapType=dlg.GetMapType())
  345. except ScriptError:
  346. GError(parent=self._mapWindow, message=_(
  347. "Failed to create new raster map."))
  348. return False
  349. finally:
  350. dlg.Destroy()
  351. return True
  352. else:
  353. dlg.Destroy()
  354. return False
  355. def _createNewMap(self, mapName, backgroundMap, mapType):
  356. """Creates a new raster map based on specified background and type."""
  357. name = mapName.split('@')[0]
  358. background = backgroundMap.split('@')[0]
  359. types = {'CELL': 'int', 'FCELL': 'float', 'DCELL': 'double'}
  360. if background:
  361. back = background
  362. else:
  363. back = 'null()'
  364. try:
  365. grast.mapcalc(
  366. exp="{name} = {mtype}({back})".format(
  367. name=name,
  368. mtype=types[mapType],
  369. back=back),
  370. overwrite=True,
  371. quiet=True)
  372. if background:
  373. self._backgroundRaster = backgroundMap
  374. gcore.run_command(
  375. 'r.colors',
  376. map=name,
  377. raster=self._backgroundRaster,
  378. quiet=True)
  379. if mapType == 'CELL':
  380. values = gcore.read_command('r.describe', flags='1n',
  381. map=name, quiet=True).strip()
  382. if values:
  383. self.uploadMapCategories.emit(
  384. values=values.split('\n'))
  385. except CalledModuleError:
  386. raise ScriptError
  387. self._backupRaster(name)
  388. name = name + '@' + gcore.gisenv()['MAPSET']
  389. self._editedRaster = name
  390. self._mapType = mapType
  391. self.newRasterCreated.emit(name=name)
  392. def _backupRaster(self, name):
  393. """Creates a temporary backup raster necessary for undo behavior.
  394. :param str name: name of raster map for which we create backup
  395. """
  396. name = name.split('@')[0]
  397. backup = name + '_backupcopy_' + str(os.getpid())
  398. try:
  399. gcore.run_command('g.copy', raster=[name, backup], quiet=True)
  400. except CalledModuleError:
  401. raise ScriptError
  402. self._backupRasterName = backup
  403. def _exportRaster(self):
  404. """Rasterizes digitized features.
  405. Uses r.in.poly and r.grow for buffering features. Creates separate raster
  406. maps depending on common cell values and buffering width necessary to
  407. keep the order of editing. These rasters are then patched together.
  408. Sets default color table for the newly digitized raster.
  409. """
  410. if not self._editedRaster or self._running:
  411. return
  412. self._running = True
  413. if self._drawing:
  414. self._finish()
  415. if len(self._all) < 1:
  416. new = self._editedRaster
  417. if '@' in self._editedRaster:
  418. new = self._editedRaster.split('@')[0]
  419. gcore.run_command('g.copy', raster=[self._backupRasterName, new],
  420. overwrite=True, quiet=True)
  421. else:
  422. tempRaster = 'tmp_rdigit_rast_' + str(os.getpid())
  423. text = []
  424. rastersToPatch = []
  425. i = 0
  426. lastCellValue = lastWidthValue = None
  427. evt = updateProgress(
  428. range=len(self._all),
  429. value=0, text=_("Rasterizing..."))
  430. wx.PostEvent(self, evt)
  431. lastCellValue = self._all[0].GetPropertyVal('cellValue')
  432. lastWidthValue = self._all[0].GetPropertyVal('widthValue')
  433. for item in self._all:
  434. if item.GetPropertyVal('widthValue') and \
  435. (lastCellValue != item.GetPropertyVal('cellValue') or
  436. lastWidthValue != item.GetPropertyVal('widthValue')):
  437. if text:
  438. out = self._rasterize(
  439. text, lastWidthValue, self._mapType, tempRaster)
  440. rastersToPatch.append(out)
  441. text = []
  442. self._writeItem(item, text)
  443. out = self._rasterize(
  444. text, item.GetPropertyVal('widthValue'),
  445. self._mapType, tempRaster)
  446. rastersToPatch.append(out)
  447. text = []
  448. else:
  449. self._writeItem(item, text)
  450. lastCellValue = item.GetPropertyVal('cellValue')
  451. lastWidthValue = item.GetPropertyVal('widthValue')
  452. i += 1
  453. evt = updateProgress(
  454. range=len(self._all),
  455. value=i, text=_("Rasterizing..."))
  456. wx.PostEvent(self, evt)
  457. if text:
  458. out = self._rasterize(text, item.GetPropertyVal('widthValue'),
  459. self._mapType, tempRaster)
  460. rastersToPatch.append(out)
  461. gcore.run_command(
  462. 'r.patch', input=rastersToPatch[:: -1] +
  463. [self._backupRasterName],
  464. output=self._editedRaster, overwrite=True, quiet=True)
  465. gcore.run_command(
  466. 'g.remove',
  467. type='raster',
  468. flags='f',
  469. name=rastersToPatch +
  470. [tempRaster],
  471. quiet=True)
  472. try:
  473. # setting the right color table
  474. if self._editOldRaster:
  475. return
  476. if not self._backgroundRaster:
  477. table = UserSettings.Get(
  478. group='rasterLayer',
  479. key='colorTable',
  480. subkey='selection')
  481. if not table:
  482. table = 'rainbow'
  483. gcore.run_command(
  484. 'r.colors',
  485. color=table,
  486. map=self._editedRaster,
  487. quiet=True)
  488. else:
  489. gcore.run_command('r.colors', map=self._editedRaster,
  490. raster=self._backgroundRaster, quiet=True)
  491. except CalledModuleError:
  492. self._running = False
  493. GError(parent=self._mapWindow, message=_(
  494. "Failed to set default color table for edited raster map"))
  495. def _writeFeature(self, item, vtype, text):
  496. """Writes digitized features in r.in.poly format."""
  497. coords = item.GetCoords()
  498. if vtype == 'P':
  499. coords = [coords]
  500. cellValue = item.GetPropertyVal('cellValue')
  501. record = '{vtype}\n'.format(vtype=vtype)
  502. for coord in coords:
  503. record += ' '.join([str(c) for c in coord])
  504. record += '\n'
  505. record += '= {cellValue}\n'.format(cellValue=cellValue)
  506. text.append(record)
  507. def _writeItem(self, item, text):
  508. if item in self._areas.GetAllItems():
  509. self._writeFeature(item, vtype='A', text=text)
  510. elif item in self._lines.GetAllItems():
  511. self._writeFeature(item, vtype='L', text=text)
  512. elif item in self._points.GetAllItems():
  513. self._writeFeature(item, vtype='P', text=text)
  514. def _rasterize(self, text, bufferDist, mapType, tempRaster):
  515. """Performs the actual rasterization using r.in.poly
  516. and buffering with r.grow if required.
  517. :param str text: string in r.in.poly format
  518. :param float bufferDist: buffer distance in map units
  519. :param str mapType: CELL, FCELL, DCELL
  520. :param str tempRaster: name of temporary raster used in computation
  521. :return: output raster map name as a result of digitization
  522. """
  523. output = 'x' + str(uuid.uuid4())[:8]
  524. asciiFile = tempfile.NamedTemporaryFile(delete=False)
  525. asciiFile.write('\n'.join(text))
  526. asciiFile.close()
  527. if bufferDist:
  528. bufferDist /= 2.
  529. gcore.run_command(
  530. 'r.in.poly',
  531. input=asciiFile.name,
  532. output=tempRaster,
  533. type_=mapType,
  534. overwrite=True,
  535. quiet=True)
  536. gcore.run_command('r.grow', input=tempRaster, output=output,
  537. flags='m', radius=bufferDist, quiet=True)
  538. else:
  539. gcore.run_command('r.in.poly', input=asciiFile.name, output=output,
  540. type_=mapType, quiet=True)
  541. os.unlink(asciiFile.name)
  542. return output