wxdisplay.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. """!
  2. @package vdigit.wxdisplay
  3. @brief wxGUI vector digitizer (display driver)
  4. Code based on wxVdigit C++ component from GRASS 6.4.0
  5. (gui/wxpython/vdigit). Converted to Python in 2010/12-2011/01.
  6. List of classes:
  7. - wxdisplay::DisplayDriver
  8. (C) 2007-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Martin Landa <landa.martin gmail.com>
  12. """
  13. import locale
  14. import wx
  15. from core.debug import Debug
  16. from core.settings import UserSettings
  17. try:
  18. from grass.lib.gis import *
  19. from grass.lib.vector import *
  20. from grass.lib.vedit import *
  21. except ImportError:
  22. pass
  23. log = None
  24. progress = None
  25. last_error = ''
  26. def print_error(msg, type):
  27. """!Redirect stderr"""
  28. global log
  29. if log:
  30. log.write(msg)
  31. else:
  32. print msg
  33. global last_error
  34. last_error += ' ' + msg
  35. return 0
  36. def print_progress(value):
  37. """!Redirect progress info"""
  38. global progress
  39. if progress:
  40. progress.SetValue(value)
  41. else:
  42. print value
  43. return 0
  44. def GetLastError():
  45. global last_error
  46. ret = last_error
  47. if ret[-1] != '.':
  48. ret += '.'
  49. last_error = '' # reset
  50. return ret
  51. errtype = CFUNCTYPE(UNCHECKED(c_int), String, c_int)
  52. errfunc = errtype(print_error)
  53. pertype = CFUNCTYPE(UNCHECKED(c_int), c_int)
  54. perfunc = pertype(print_progress)
  55. class DisplayDriver:
  56. def __init__(self, device, deviceTmp, mapObj, window, glog, gprogress):
  57. """!Display driver used by vector digitizer
  58. @param device wx.PseudoDC device where to draw vector objects
  59. @param deviceTmp wx.PseudoDC device where to draw temporary vector objects
  60. @param mapOng Map Object (render.Map)
  61. @param windiow parent window for dialogs
  62. @param glog logging device (None to discard messages)
  63. @param gprogress progress bar device (None to discard message)
  64. """
  65. global errfunc, perfunc, log, progress
  66. log = glog
  67. progress = gprogress
  68. G_gisinit('wxvdigit')
  69. locale.setlocale(locale.LC_NUMERIC, 'C')
  70. G_set_error_routine(errfunc)
  71. G_set_percent_routine(perfunc)
  72. # G_set_fatal_error(FATAL_RETURN)
  73. self.mapInfo = None # open vector map (Map_Info structure)
  74. self.poMapInfo = None # pointer to self.mapInfo
  75. self.is3D = False # is open vector map 3D
  76. self.dc = device # PseudoDC devices
  77. self.dcTmp = deviceTmp
  78. self.mapObj = mapObj
  79. self.region = mapObj.GetCurrentRegion()
  80. self.window = window
  81. self.log = log # log device
  82. self.firstNode = True # track PseudoDC Id of selected features
  83. self.lastNodeId = -1
  84. # GRASS lib
  85. self.poPoints = Vect_new_line_struct()
  86. self.poCats = Vect_new_cats_struct()
  87. # selected objects
  88. self.selected = {
  89. 'field' : -1, # field number
  90. 'cats' : list(), # list of cats
  91. 'ids' : list(), # list of ids
  92. 'idsDupl' : list(), # list of duplicated features
  93. }
  94. # digitizer settings
  95. self.settings = {
  96. 'highlight' : None,
  97. 'highlightDupl' : { 'enabled' : False,
  98. 'color' : None },
  99. 'point' : { 'enabled' : False,
  100. 'color' : None },
  101. 'line' : { 'enabled' : False,
  102. 'color' : None },
  103. 'boundaryNo' : { 'enabled' : False,
  104. 'color' : None },
  105. 'boundaryOne' : { 'enabled' : False,
  106. 'color' : None },
  107. 'boundaryTwo' : { 'enabled' : False,
  108. 'color' : None },
  109. 'centroidIn' : { 'enabled' : False,
  110. 'color' : None },
  111. 'centroidOut' : { 'enabled' : False,
  112. 'color' : None },
  113. 'centroidDup' : { 'enabled' : False,
  114. 'color' : None },
  115. 'nodeOne' : { 'enabled' : False,
  116. 'color' : None },
  117. 'nodeTwo' : { 'enabled' : False,
  118. 'color' : None },
  119. 'vertex' : { 'enabled' : False,
  120. 'color' : None },
  121. 'area' : { 'enabled' : False,
  122. 'color' : None },
  123. 'direction' : { 'enabled' : False,
  124. 'color' : None },
  125. 'lineWidth' : -1, # screen units
  126. }
  127. # topology
  128. self._resetTopology()
  129. self._drawSelected = False
  130. self._drawSegments = False
  131. self.UpdateSettings()
  132. def __del__(self):
  133. """!Close currently open vector map"""
  134. G_unset_error_routine()
  135. G_unset_percent_routine()
  136. if self.poMapInfo:
  137. self.CloseMap()
  138. Vect_destroy_line_struct(self.poPoints)
  139. Vect_destroy_cats_struct(self.poCats)
  140. def _resetTopology(self):
  141. """!Reset topology dict
  142. """
  143. self.topology = {
  144. 'highlight' : 0,
  145. 'point' : 0,
  146. 'line' : 0,
  147. 'boundaryNo' : 0,
  148. 'boundaryOne' : 0,
  149. 'boundaryTwo' : 0,
  150. 'centroidIn' : 0,
  151. 'centroidOut' : 0,
  152. 'centroidDup' : 0,
  153. 'nodeOne' : 0,
  154. 'nodeTwo' : 0,
  155. 'vertex' : 0,
  156. }
  157. def _cell2Pixel(self, east, north, elev):
  158. """!Conversion from geographic coordinates (east, north)
  159. to screen (x, y)
  160. @todo 3D stuff...
  161. @param east, north, elev geographical coordinates
  162. @return x, y screen coordinates (integer)
  163. """
  164. map_res = max(self.region['ewres'], self.region['nsres'])
  165. w = self.region['center_easting'] - (self.mapObj.width / 2) * map_res
  166. n = self.region['center_northing'] + (self.mapObj.height / 2) * map_res
  167. return int((east - w) / map_res), int((n - north) / map_res)
  168. def _drawCross(self, pdc, point, size = 5):
  169. """!Draw cross symbol of given size to device content
  170. Used for points, nodes, vertices
  171. @param[in,out] PseudoDC where to draw
  172. @param point coordinates of center
  173. @param size size of the cross symbol
  174. @return 0 on success
  175. @return -1 on failure
  176. """
  177. if not pdc or not point:
  178. return -1
  179. pdc.DrawLine(point.x - size, point.y, point.x + size, point.y)
  180. pdc.DrawLine(point.x, point.y - size, point.x, point.y + size)
  181. return 0
  182. def _drawObject(self, robj):
  183. """!Draw given object to the device
  184. The object is defined as robject() from vedit.h.
  185. @param robj object to be rendered
  186. @return 1 on success
  187. @return -1 on failure (vector feature marked as dead, etc.)
  188. """
  189. if not self.dc or not self.dcTmp:
  190. return -1
  191. Debug.msg(3, "_drawObject(): line=%d type=%d npoints=%d", robj.fid, robj.type, robj.npoints)
  192. brush = None
  193. if self._isSelected(robj.fid):
  194. pdc = self.dcTmp
  195. if robj.type == TYPE_AREA:
  196. return 1
  197. else:
  198. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(robj.fid):
  199. pen = wx.Pen(self.settings['highlightDupl']['color'], self.settings['lineWidth'], wx.SOLID)
  200. else:
  201. pen = wx.Pen(self.settings['highlight'], self.settings['lineWidth'], wx.SOLID)
  202. dcId = 1
  203. self.topology['highlight'] += 1
  204. if not self._drawSelected:
  205. return
  206. else:
  207. pdc = self.dc
  208. pen, brush = self._definePen(robj.type)
  209. dcId = 0
  210. pdc.SetPen(pen)
  211. if brush:
  212. pdc.SetBrush(brush)
  213. if robj.type & (TYPE_POINT | TYPE_CENTROIDIN | TYPE_CENTROIDOUT | TYPE_CENTROIDDUP |
  214. TYPE_NODEONE | TYPE_NODETWO | TYPE_VERTEX): # -> point
  215. if dcId > 0:
  216. if robj.type == TYPE_VERTEX:
  217. dcId = 3 # first vertex
  218. elif robj.type & (TYPE_NODEONE | TYPE_NODETWO):
  219. if self.firstNode:
  220. dcId = 1
  221. self.firstNode = False
  222. else:
  223. dcId = self.lastNodeId
  224. for i in range(robj.npoints):
  225. p = robj.point[i]
  226. if dcId > 0:
  227. pdc.SetId(dcId)
  228. dcId += 2
  229. self._drawCross(pdc, p)
  230. else:
  231. if dcId > 0 and self._drawSegments:
  232. self.fisrtNode = True
  233. self.lastNodeId = robj.npoints * 2 - 1
  234. dcId = 2 # first segment
  235. i = 0
  236. while i < robj.npoints - 1:
  237. point_beg = wx.Point(robj.point[i].x, robj.point[i].y)
  238. point_end = wx.Point(robj.point[i+1].x, robj.point[i+1].y)
  239. pdc.SetId(dcId) # set unique id & set bbox for each segment
  240. pdc.SetPen(pen)
  241. pdc.SetIdBounds(dcId - 1, wx.Rect(point_beg.x, point_beg.y, 0, 0))
  242. pdc.SetIdBounds(dcId, wx.RectPP(point_beg, point_end))
  243. pdc.DrawLine(point_beg.x, point_beg.y,
  244. point_end.x, point_end.y)
  245. i += 1
  246. dcId += 2
  247. pdc.SetIdBounds(dcId - 1, wx.Rect(robj.point[robj.npoints - 1].x,
  248. robj.point[robj.npoints - 1].y,
  249. 0, 0))
  250. else:
  251. points = list()
  252. for i in range(robj.npoints):
  253. p = robj.point[i]
  254. points.append(wx.Point(p.x, p.y))
  255. if robj.type == TYPE_AREA:
  256. pdc.DrawPolygon(points)
  257. else:
  258. pdc.DrawLines(points)
  259. def _definePen(self, rtype):
  260. """!Define pen/brush based on rendered object)
  261. Updates also self.topology dict
  262. @return pen, brush
  263. """
  264. if rtype == TYPE_POINT:
  265. key = 'point'
  266. elif rtype == TYPE_LINE:
  267. key = 'line'
  268. elif rtype == TYPE_BOUNDARYNO:
  269. key = 'boundaryNo'
  270. elif rtype == TYPE_BOUNDARYTWO:
  271. key = 'boundaryTwo'
  272. elif rtype == TYPE_BOUNDARYONE:
  273. key = 'boundaryOne'
  274. elif rtype == TYPE_CENTROIDIN:
  275. key = 'centroidIn'
  276. elif rtype == TYPE_CENTROIDOUT:
  277. key = 'centroidOut'
  278. elif rtype == TYPE_CENTROIDDUP:
  279. key = 'centroidDup'
  280. elif rtype == TYPE_NODEONE:
  281. key = 'nodeOne'
  282. elif rtype == TYPE_NODETWO:
  283. key = 'nodeTwo'
  284. elif rtype == TYPE_VERTEX:
  285. key = 'vertex'
  286. elif rtype == TYPE_AREA:
  287. key = 'area'
  288. elif rtype == TYPE_ISLE:
  289. key = 'isle'
  290. elif rtype == TYPE_DIRECTION:
  291. key = 'direction'
  292. if key not in ('direction', 'area', 'isle'):
  293. self.topology[key] += 1
  294. if key in ('area', 'isle'):
  295. pen = wx.TRANSPARENT_PEN
  296. if key == 'area':
  297. brush = wx.Brush(self.settings[key]['color'], wx.SOLID)
  298. else:
  299. brush = wx.TRANSPARENT_BRUSH
  300. else:
  301. pen = wx.Pen(self.settings[key]['color'], self.settings['lineWidth'], wx.SOLID)
  302. brush = None
  303. return pen, brush
  304. def _getDrawFlag(self):
  305. """!Get draw flag from the settings
  306. See vedit.h for list of draw flags.
  307. @return draw flag (int)
  308. """
  309. ret = 0
  310. if self.settings['point']['enabled']:
  311. ret |= DRAW_POINT
  312. if self.settings['line']['enabled']:
  313. ret |= DRAW_LINE
  314. if self.settings['boundaryNo']['enabled']:
  315. ret |= DRAW_BOUNDARYNO
  316. if self.settings['boundaryTwo']['enabled']:
  317. ret |= DRAW_BOUNDARYTWO
  318. if self.settings['boundaryOne']['enabled']:
  319. ret |= DRAW_BOUNDARYONE
  320. if self.settings['centroidIn']['enabled']:
  321. ret |= DRAW_CENTROIDIN
  322. if self.settings['centroidOut']['enabled']:
  323. ret |= DRAW_CENTROIDOUT
  324. if self.settings['centroidDup']['enabled']:
  325. ret |= DRAW_CENTROIDDUP
  326. if self.settings['nodeOne']['enabled']:
  327. ret |= DRAW_NODEONE
  328. if self.settings['nodeTwo']['enabled']:
  329. ret |= DRAW_NODETWO
  330. if self.settings['vertex']['enabled']:
  331. ret |= DRAW_VERTEX
  332. if self.settings['area']['enabled']:
  333. ret |= DRAW_AREA
  334. if self.settings['direction']['enabled']:
  335. ret |= DRAW_DIRECTION
  336. return ret
  337. def _isSelected(self, line, force = False):
  338. """!Check if vector object selected?
  339. @param line feature id
  340. @return True if vector object is selected
  341. @return False if vector object is not selected
  342. """
  343. if line in self.selected['ids']:
  344. return True
  345. return False
  346. def _isDuplicated(self, line):
  347. """!Check for already marked duplicates
  348. @param line feature id
  349. @return True line already marked as duplicated
  350. @return False not duplicated
  351. """
  352. return line in self.selected['idsDupl']
  353. def _getRegionBox(self):
  354. """!Get bound_box() from current region
  355. @return bound_box
  356. """
  357. box = bound_box()
  358. box.N = self.region['n']
  359. box.S = self.region['s']
  360. box.E = self.region['e']
  361. box.W = self.region['w']
  362. box.T = PORT_DOUBLE_MAX
  363. box.B = -PORT_DOUBLE_MAX
  364. return box
  365. def DrawMap(self, force = False):
  366. """!Draw content of the vector map to the device
  367. @param force force drawing
  368. @return number of drawn features
  369. @return -1 on error
  370. """
  371. Debug.msg(1, "DisplayDriver.DrawMap(): force=%d", force)
  372. if not self.poMapInfo or not self.dc or not self.dcTmp:
  373. return -1
  374. rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
  375. self.region['center_easting'], self.region['center_northing'],
  376. self.mapObj.width, self.mapObj.height,
  377. max(self.region['nsres'], self.region['ewres'])).contents
  378. self._resetTopology()
  379. self.dc.BeginDrawing()
  380. self.dcTmp.BeginDrawing()
  381. # draw objects
  382. for i in range(rlist.nitems):
  383. robj = rlist.item[i].contents
  384. self._drawObject(robj)
  385. self.dc.EndDrawing()
  386. self.dcTmp.EndDrawing()
  387. # reset list of selected features by cat
  388. # list of ids - see IsSelected()
  389. self.selected['field'] = -1
  390. self.selected['cats'] = list()
  391. def _getSelectType(self):
  392. """!Get type(s) to be selected
  393. Used by SelectLinesByBox() and SelectLineByPoint()
  394. """
  395. ftype = 0
  396. for feature in (('point', GV_POINT),
  397. ('line', GV_LINE),
  398. ('centroid', GV_CENTROID),
  399. ('boundary', GV_BOUNDARY)):
  400. if UserSettings.Get(group = 'vdigit', key = 'selectType',
  401. subkey = [feature[0], 'enabled']):
  402. ftype |= feature[1]
  403. return ftype
  404. def _validLine(self, line):
  405. """!Check if feature id is valid
  406. @param line feature id
  407. @return True valid feature id
  408. @return False invalid
  409. """
  410. if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
  411. return True
  412. return False
  413. def SelectLinesByBox(self, bbox, drawSeg = False, poMapInfo = None):
  414. """!Select vector objects by given bounding box
  415. If line id is already in the list of selected lines, then it will
  416. be excluded from this list.
  417. @param bbox bounding box definition
  418. @param drawSeg True to draw segments of line
  419. @param poMapInfo use external Map_info, None for self.poMapInfo
  420. @return number of selected features
  421. @return None on error
  422. """
  423. thisMapInfo = poMapInfo is None
  424. if not poMapInfo:
  425. poMapInfo = self.poMapInfo
  426. if not poMapInfo:
  427. return None
  428. if thisMapInfo:
  429. self._drawSegments = drawSeg
  430. self._drawSelected = True
  431. # select by ids
  432. self.selected['cats'] = list()
  433. poList = Vect_new_list()
  434. x1, y1 = bbox[0]
  435. x2, y2 = bbox[1]
  436. poBbox = Vect_new_line_struct()
  437. Vect_append_point(poBbox, x1, y1, 0.0)
  438. Vect_append_point(poBbox, x2, y1, 0.0)
  439. Vect_append_point(poBbox, x2, y2, 0.0)
  440. Vect_append_point(poBbox, x1, y2, 0.0)
  441. Vect_append_point(poBbox, x1, y1, 0.0)
  442. Vect_select_lines_by_polygon(poMapInfo, poBbox,
  443. 0, None, # isles
  444. self._getSelectType(), poList)
  445. flist = poList.contents
  446. nlines = flist.n_values
  447. Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
  448. for i in range(nlines):
  449. line = flist.value[i]
  450. if UserSettings.Get(group = 'vdigit', key = 'selectInside',
  451. subkey = 'enabled'):
  452. inside = True
  453. if not self._validLine(line):
  454. return None
  455. Vect_read_line(poMapInfo, self.poPoints, None, line)
  456. points = self.poPoints.contents
  457. for p in range(points.n_points):
  458. if not Vect_point_in_poly(points.x[p], points.y[p],
  459. poBbox):
  460. inside = False
  461. break
  462. if not inside:
  463. continue # skip lines just overlapping bbox
  464. if not self._isSelected(line):
  465. self.selected['ids'].append(line)
  466. else:
  467. self.selected['ids'].remove(line)
  468. Vect_destroy_line_struct(poBbox)
  469. Vect_destroy_list(poList)
  470. return nlines
  471. def SelectLineByPoint(self, point, poMapInfo = None):
  472. """!Select vector feature by given point in given
  473. threshold
  474. Only one vector object can be selected. Bounding boxes of
  475. all segments are stores.
  476. @param point points coordinates (x, y)
  477. @param poMapInfo use external Map_info, None for self.poMapInfo
  478. @return dict {'line' : feature id, 'point' : point on line}
  479. """
  480. thisMapInfo = poMapInfo is None
  481. if not poMapInfo:
  482. poMapInfo = self.poMapInfo
  483. if not poMapInfo:
  484. return { 'line' : -1, 'point': None }
  485. if thisMapInfo:
  486. self._drawSelected = True
  487. # select by ids
  488. self.selected['cats'] = list()
  489. poFound = Vect_new_list()
  490. lineNearest = Vect_find_line_list(poMapInfo, point[0], point[1], 0,
  491. self._getSelectType(), self.GetThreshold(), self.is3D,
  492. None, poFound)
  493. Debug.msg(1, "DisplayDriver.SelectLineByPoint() found = %d", lineNearest)
  494. if lineNearest > 0:
  495. if not self._isSelected(lineNearest):
  496. self.selected['ids'].append(lineNearest)
  497. else:
  498. self.selected['ids'].remove(lineNearest)
  499. px = c_double()
  500. py = c_double()
  501. pz = c_double()
  502. if not self._validLine(lineNearest):
  503. return { 'line' : -1, 'point': None }
  504. ftype = Vect_read_line(poMapInfo, self.poPoints, self.poCats, lineNearest)
  505. Vect_line_distance (self.poPoints, point[0], point[1], 0.0, self.is3D,
  506. byref(px), byref(py), byref(pz),
  507. None, None, None)
  508. # check for duplicates
  509. if self.settings['highlightDupl']['enabled']:
  510. found = poFound.contents
  511. for i in range(found.n_values):
  512. line = found.value[i]
  513. if line != lineNearest:
  514. self.selected['ids'].append(line)
  515. self.GetDuplicates()
  516. for i in range(found.n_values):
  517. line = found.value[i]
  518. if line != lineNearest and not self._isDuplicated(line):
  519. self.selected['ids'].remove(line)
  520. Vect_destroy_list(poFound)
  521. if thisMapInfo:
  522. # drawing segments can be very expensive
  523. # only one features selected
  524. self._drawSegments = True
  525. return { 'line' : lineNearest,
  526. 'point' : (px.value, py.value, pz.value) }
  527. def _listToIList(self, plist):
  528. """!Generate from list struct_ilist
  529. """
  530. ilist = Vect_new_list()
  531. for val in plist:
  532. Vect_list_append(ilist, val)
  533. return ilist
  534. def GetSelectedIList(self, ilist = None):
  535. """!Get list of selected objects as struct_ilist
  536. Returned IList must be freed by Vect_destroy_list().
  537. @return struct_ilist
  538. """
  539. if ilist:
  540. return self._listToIList(ilist)
  541. return self._listToIList(self.selected['ids'])
  542. def GetSelected(self, grassId = True):
  543. """!Get ids of selected objects
  544. @param grassId True for feature id, False for PseudoDC id
  545. @return list of ids of selected vector objects
  546. """
  547. if grassId:
  548. return self.selected['ids']
  549. dc_ids = list()
  550. if not self._drawSegments:
  551. dc_ids.append(1)
  552. elif len(self.selected['ids']) > 0:
  553. # only first selected feature
  554. Vect_read_line(self.poMapInfo, self.poPoints, None,
  555. self.selected['ids'][0])
  556. points = self.poPoints.contents
  557. # node - segment - vertex - segment - node
  558. for i in range(1, 2 * points.n_points):
  559. dc_ids.append(i)
  560. return dc_ids
  561. def SetSelected(self, ids, layer = -1):
  562. """!Set selected vector objects
  563. @param list of ids (None to unselect features)
  564. @param layer layer number for features selected based on category number
  565. """
  566. if ids:
  567. self._drawSelected = True
  568. else:
  569. self._drawSelected = False
  570. self.selected['field'] = layer
  571. if layer > 0:
  572. self.selected['cats'] = ids
  573. self.selected['ids'] = list()
  574. ### cidx is not up-to-date
  575. # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist)
  576. nlines = Vect_get_num_lines(self.poMapInfo)
  577. for line in range(1, nlines + 1):
  578. if not Vect_line_alive(self.poMapInfo, line):
  579. continue
  580. ltype = Vect_read_line (self.poMapInfo, None, self.poCats, line)
  581. if not (ltype & (GV_POINTS | GV_LINES)):
  582. continue
  583. found = False
  584. cats = self.poCats.contents
  585. for i in range(0, cats.n_cats):
  586. for cat in self.selected['cats']:
  587. if cats.cat[i] == cat:
  588. found = True
  589. break
  590. if found:
  591. self.selected['ids'].append(line)
  592. else:
  593. self.selected['ids'] = ids
  594. self.selected['cats'] = []
  595. def GetSelectedVertex(self, pos):
  596. """!Get PseudoDC vertex id of selected line
  597. Set bounding box for vertices of line.
  598. @param pos position
  599. @return id of center, left and right vertex
  600. @return 0 no line found
  601. @return -1 on error
  602. """
  603. returnId = list()
  604. # only one object can be selected
  605. if len(self.selected['ids']) != 1 or not self._drawSegments:
  606. return returnId
  607. startId = 1
  608. line = self.selected['ids'][0]
  609. if not self._validLine(line):
  610. return -1
  611. ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
  612. minDist = 0.0
  613. Gid = -1
  614. # find the closest vertex (x, y)
  615. DCid = 1
  616. points = self.poPoints.contents
  617. for idx in range(points.n_points):
  618. dist = Vect_points_distance(pos[0], pos[1], 0.0,
  619. points.x[idx], points.y[idx], points.z[idx], 0)
  620. if idx == 0:
  621. minDist = dist
  622. Gid = idx
  623. else:
  624. if minDist > dist:
  625. minDist = dist
  626. Gid = idx
  627. vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
  628. rect = wx.Rect(vx, vy, 0, 0)
  629. self.dc.SetIdBounds(DCid, rect)
  630. DCid += 2
  631. if minDist > self.GetThreshold():
  632. return returnId
  633. # translate id
  634. DCid = Gid * 2 + 1
  635. # add selected vertex
  636. returnId.append(DCid)
  637. # left vertex
  638. if DCid == startId:
  639. returnId.append(-1)
  640. else:
  641. returnId.append(DCid - 2)
  642. # right vertex
  643. if DCid == (points.n_points - 1) * 2 + startId:
  644. returnId.append(-1)
  645. else:
  646. returnId.append(DCid + 2)
  647. return returnId
  648. def GetRegionSelected(self):
  649. """!Get minimal region extent of selected features
  650. @return n,s,w,e
  651. """
  652. regionBox = bound_box()
  653. lineBox = bound_box()
  654. setRegion = True
  655. nareas = Vect_get_num_areas(self.poMapInfo)
  656. for line in self.selected['ids']:
  657. area = Vect_get_centroid_area(self.poMapInfo, line)
  658. if area > 0 and area <= nareas:
  659. if not Vect_get_area_box(self.poMapInfo, area, byref(lineBox)):
  660. continue
  661. else:
  662. if not Vect_get_line_box(self.poMapInfo, line, byref(lineBox)):
  663. continue
  664. if setRegion:
  665. Vect_box_copy(byref(regionBox), byref(lineBox))
  666. setRegion = False
  667. else:
  668. Vect_box_extend(byref(regionBox), byref(lineBox))
  669. return regionBox.N, regionBox.S, regionBox.W, regionBox.E
  670. def DrawSelected(self, flag):
  671. """!Draw selected features
  672. @param flag True to draw selected features
  673. """
  674. self._drawSelected = bool(flag)
  675. def CloseMap(self):
  676. """!Close vector map
  677. @return 0 on success
  678. @return non-zero on error
  679. """
  680. ret = 0
  681. if self.poMapInfo:
  682. # rebuild topology
  683. Vect_build_partial(self.poMapInfo, GV_BUILD_NONE)
  684. Vect_build(self.poMapInfo)
  685. # close map and store topo/cidx
  686. ret = Vect_close(self.poMapInfo)
  687. del self.mapInfo
  688. self.poMapInfo = self.mapInfo = None
  689. return ret
  690. def OpenMap(self, name, mapset, update = True):
  691. """!Open vector map by the driver
  692. @param name name of vector map to be open
  693. @param mapset name of mapset where the vector map lives
  694. @return map_info
  695. @return None on error
  696. """
  697. Debug.msg("DisplayDriver.OpenMap(): name=%s mapset=%s updated=%d",
  698. name, mapset, update)
  699. if not self.mapInfo:
  700. self.mapInfo = Map_info()
  701. self.poMapInfo = pointer(self.mapInfo)
  702. # open existing map
  703. if update:
  704. ret = Vect_open_update(self.poMapInfo, name, mapset)
  705. else:
  706. ret = Vect_open_old(self.poMapInfo, name, mapset)
  707. self.is3D = Vect_is_3d(self.poMapInfo)
  708. if ret == -1: # error
  709. del self.mapInfo
  710. self.poMapInfo = self.mapInfo = None
  711. elif ret < 2:
  712. dlg = wx.MessageDialog(parent = self.window,
  713. message = _("Topology for vector map <%s> is not available. "
  714. "Topology is required by digitizer. Do you want to "
  715. "rebuild topology (takes some time) and open the vector map "
  716. "for editing?") % name,
  717. caption=_("Topology missing"),
  718. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  719. ret = dlg.ShowModal()
  720. if ret != wx.ID_YES:
  721. del self.mapInfo
  722. self.poMapInfo = self.mapInfo = None
  723. else:
  724. Vect_build(self.poMapInfo)
  725. return self.poMapInfo
  726. def GetMapBoundingBox(self):
  727. """!Get bounding box of (opened) vector map layer
  728. @return (w,s,b,e,n,t)
  729. """
  730. if not self.poMapInfo:
  731. return None
  732. bbox = bound_box()
  733. Vect_get_map_box(self.poMapInfo, byref(bbox))
  734. return bbox.W, bbox.S, bbox.B, \
  735. bbox.E, bbox.N, bbox.T
  736. def UpdateSettings(self, alpha = 255):
  737. """!Update display driver settings
  738. @todo map units
  739. @alpha color value for aplha channel
  740. """
  741. color = dict()
  742. for key in self.settings.keys():
  743. if key == 'lineWidth':
  744. self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
  745. subkey = 'value'))
  746. continue
  747. color = wx.Color(UserSettings.Get(group = 'vdigit', key = 'symbol',
  748. subkey = [key, 'color'])[0],
  749. UserSettings.Get(group = 'vdigit', key = 'symbol',
  750. subkey = [key, 'color'])[1],
  751. UserSettings.Get(group = 'vdigit', key = 'symbol',
  752. subkey = [key, 'color'])[2],
  753. alpha)
  754. if key == 'highlight':
  755. self.settings[key] = color
  756. continue
  757. if key == 'highlightDupl':
  758. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  759. subkey = 'enabled'))
  760. else:
  761. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
  762. subkey = [key, 'enabled']))
  763. self.settings[key]['color'] = color
  764. def UpdateRegion(self):
  765. """!Update geographical region used by display driver
  766. """
  767. self.region = self.mapObj.GetCurrentRegion()
  768. def GetThreshold(self, type = 'snapping', value = None, units = None):
  769. """!Return threshold value in map units
  770. @param type snapping mode (node, vertex)
  771. @param value threshold to be set up
  772. @param units units (map, screen)
  773. @return threshold value
  774. """
  775. if value is None:
  776. value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
  777. if units is None:
  778. units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
  779. if value < 0:
  780. value = (self.region['nsres'] + self.region['ewres']) / 2.0
  781. if units == "screen pixels":
  782. # pixel -> cell
  783. res = max(self.region['nsres'], self.region['ewres'])
  784. return value * res
  785. return value
  786. def GetDuplicates(self):
  787. """!Return ids of (selected) duplicated vector features
  788. """
  789. if not self.poMapInfo:
  790. return
  791. ids = dict()
  792. APoints = Vect_new_line_struct()
  793. BPoints = Vect_new_line_struct()
  794. self.selected['idsDupl'] = list()
  795. for i in range(len(self.selected['ids'])):
  796. line1 = self.selected['ids'][i]
  797. if self._isDuplicated(line1):
  798. continue
  799. Vect_read_line(self.poMapInfo, APoints, None, line1)
  800. for line2 in self.selected['ids']:
  801. if line1 == line2 or self._isDuplicated(line2):
  802. continue
  803. Vect_read_line(self.poMapInfo, BPoints, None, line2)
  804. if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
  805. if i not in ids:
  806. ids[i] = list()
  807. ids[i].append((line1, self._getCatString(line1)))
  808. self.selected['idsDupl'].append(line1)
  809. ids[i].append((line2, self._getCatString(line2)))
  810. self.selected['idsDupl'].append(line2)
  811. Vect_destroy_line_struct(APoints)
  812. Vect_destroy_line_struct(BPoints)
  813. return ids
  814. def _getCatString(self, line):
  815. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  816. cats = self.poCats.contents
  817. catsDict = dict()
  818. for i in range(cats.n_cats):
  819. layer = cats.field[i]
  820. if layer not in catsDict:
  821. catsDict[layer] = list()
  822. catsDict[layer].append(cats.cat[i])
  823. catsStr = ''
  824. for l, c in catsDict.iteritems():
  825. catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
  826. return catsStr
  827. def UnSelect(self, lines):
  828. """!Unselect vector features
  829. @param lines list of feature id(s)
  830. """
  831. checkForDupl = False
  832. for line in lines:
  833. if self._isSelected(line):
  834. self.selected['ids'].remove(line)
  835. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
  836. checkForDupl = True
  837. if checkForDupl:
  838. self.GetDuplicates()
  839. return len(self.selected['ids'])