wxdisplay.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 self.settings['highlightDupl']['enabled'] and self._isDuplicated(robj.fid):
  196. pen = wx.Pen(self.settings['highlightDupl']['color'], self.settings['lineWidth'], wx.SOLID)
  197. else:
  198. pen = wx.Pen(self.settings['highlight'], self.settings['lineWidth'], wx.SOLID)
  199. dcId = 1
  200. self.topology['highlight'] += 1
  201. if not self._drawSelected:
  202. return
  203. else:
  204. pdc = self.dc
  205. pen, brush = self._definePen(robj.type)
  206. dcId = 0
  207. pdc.SetPen(pen)
  208. if brush:
  209. pdc.SetBrush(brush)
  210. if robj.type & (TYPE_POINT | TYPE_CENTROIDIN | TYPE_CENTROIDOUT | TYPE_CENTROIDDUP |
  211. TYPE_NODEONE | TYPE_NODETWO | TYPE_VERTEX): # -> point
  212. if dcId > 0:
  213. if robj.type == TYPE_VERTEX:
  214. dcId = 3 # first vertex
  215. elif robj.type & (TYPE_NODEONE | TYPE_NODETWO):
  216. if self.firstNode:
  217. dcId = 1
  218. self.firstNode = False
  219. else:
  220. dcId = self.lastNodeId
  221. for i in range(robj.npoints):
  222. p = robj.point[i]
  223. if dcId > 0:
  224. pdc.SetId(dcId)
  225. dcId += 2
  226. self._drawCross(pdc, p)
  227. else:
  228. if dcId > 0 and self._drawSegments:
  229. self.fisrtNode = True
  230. self.lastNodeId = robj.npoints * 2 - 1
  231. dcId = 2 # first segment
  232. i = 0
  233. while i < robj.npoints - 1:
  234. point_beg = wx.Point(robj.point[i].x, robj.point[i].y)
  235. point_end = wx.Point(robj.point[i+1].x, robj.point[i+1].y)
  236. pdc.SetId(dcId) # set unique id & set bbox for each segment
  237. pdc.SetPen(pen)
  238. pdc.SetIdBounds(dcId - 1, wx.Rect(point_beg.x, point_beg.y, 0, 0))
  239. pdc.SetIdBounds(dcId, wx.RectPP(point_beg, point_end))
  240. pdc.DrawLine(point_beg.x, point_beg.y,
  241. point_end.x, point_end.y)
  242. i += 1
  243. dcId += 2
  244. pdc.SetIdBounds(dcId - 1, wx.Rect(robj.point[robj.npoints - 1].x,
  245. robj.point[robj.npoints - 1].y,
  246. 0, 0))
  247. else:
  248. points = list()
  249. for i in range(robj.npoints):
  250. p = robj.point[i]
  251. points.append(wx.Point(p.x, p.y))
  252. if robj.type == TYPE_AREA:
  253. pdc.DrawPolygon(points)
  254. else:
  255. pdc.DrawLines(points)
  256. def _definePen(self, rtype):
  257. """!Define pen/brush based on rendered object)
  258. Updates also self.topology dict
  259. @return pen, brush
  260. """
  261. if rtype == TYPE_POINT:
  262. key = 'point'
  263. elif rtype == TYPE_LINE:
  264. key = 'line'
  265. elif rtype == TYPE_BOUNDARYNO:
  266. key = 'boundaryNo'
  267. elif rtype == TYPE_BOUNDARYTWO:
  268. key = 'boundaryTwo'
  269. elif rtype == TYPE_BOUNDARYONE:
  270. key = 'boundaryOne'
  271. elif rtype == TYPE_CENTROIDIN:
  272. key = 'centroidIn'
  273. elif rtype == TYPE_CENTROIDOUT:
  274. key = 'centroidOut'
  275. elif rtype == TYPE_CENTROIDDUP:
  276. key = 'centroidDup'
  277. elif rtype == TYPE_NODEONE:
  278. key = 'nodeOne'
  279. elif rtype == TYPE_NODETWO:
  280. key = 'nodeTwo'
  281. elif rtype == TYPE_VERTEX:
  282. key = 'vertex'
  283. elif rtype == TYPE_AREA:
  284. key = 'area'
  285. elif rtype == TYPE_ISLE:
  286. key = 'isle'
  287. elif rtype == TYPE_DIRECTION:
  288. key = 'direction'
  289. if key not in ('direction', 'area', 'isle'):
  290. self.topology[key] += 1
  291. if key in ('area', 'isle'):
  292. pen = wx.TRANSPARENT_PEN
  293. if key == 'area':
  294. brush = wx.Brush(self.settings[key]['color'], wx.SOLID)
  295. else:
  296. brush = wx.TRANSPARENT_BRUSH
  297. else:
  298. pen = wx.Pen(self.settings[key]['color'], self.settings['lineWidth'], wx.SOLID)
  299. brush = None
  300. return pen, brush
  301. def _getDrawFlag(self):
  302. """!Get draw flag from the settings
  303. See vedit.h for list of draw flags.
  304. @return draw flag (int)
  305. """
  306. ret = 0
  307. if self.settings['point']['enabled']:
  308. ret |= DRAW_POINT
  309. if self.settings['line']['enabled']:
  310. ret |= DRAW_LINE
  311. if self.settings['boundaryNo']['enabled']:
  312. ret |= DRAW_BOUNDARYNO
  313. if self.settings['boundaryTwo']['enabled']:
  314. ret |= DRAW_BOUNDARYTWO
  315. if self.settings['boundaryOne']['enabled']:
  316. ret |= DRAW_BOUNDARYONE
  317. if self.settings['centroidIn']['enabled']:
  318. ret |= DRAW_CENTROIDIN
  319. if self.settings['centroidOut']['enabled']:
  320. ret |= DRAW_CENTROIDOUT
  321. if self.settings['centroidDup']['enabled']:
  322. ret |= DRAW_CENTROIDDUP
  323. if self.settings['nodeOne']['enabled']:
  324. ret |= DRAW_NODEONE
  325. if self.settings['nodeTwo']['enabled']:
  326. ret |= DRAW_NODETWO
  327. if self.settings['vertex']['enabled']:
  328. ret |= DRAW_VERTEX
  329. if self.settings['area']['enabled']:
  330. ret |= DRAW_AREA
  331. if self.settings['direction']['enabled']:
  332. ret |= DRAW_DIRECTION
  333. return ret
  334. def _isSelected(self, line, force = False):
  335. """!Check if vector object selected?
  336. @param line feature id
  337. @return True if vector object is selected
  338. @return False if vector object is not selected
  339. """
  340. if line in self.selected['ids']:
  341. return True
  342. return False
  343. def _isDuplicated(self, line):
  344. """!Check for already marked duplicates
  345. @param line feature id
  346. @return True line already marked as duplicated
  347. @return False not duplicated
  348. """
  349. return line in self.selected['idsDupl']
  350. def _getRegionBox(self):
  351. """!Get bound_box() from current region
  352. @return bound_box
  353. """
  354. box = bound_box()
  355. box.N = self.region['n']
  356. box.S = self.region['s']
  357. box.E = self.region['e']
  358. box.W = self.region['w']
  359. box.T = PORT_DOUBLE_MAX
  360. box.B = -PORT_DOUBLE_MAX
  361. return box
  362. def DrawMap(self, force = False):
  363. """!Draw content of the vector map to the device
  364. @param force force drawing
  365. @return number of drawn features
  366. @return -1 on error
  367. """
  368. Debug.msg(1, "DisplayDriver.DrawMap(): force=%d", force)
  369. if not self.poMapInfo or not self.dc or not self.dcTmp:
  370. return -1
  371. rlist = Vedit_render_map(self.poMapInfo, byref(self._getRegionBox()), self._getDrawFlag(),
  372. self.region['center_easting'], self.region['center_northing'],
  373. self.mapObj.width, self.mapObj.height,
  374. max(self.region['nsres'], self.region['ewres'])).contents
  375. self._resetTopology()
  376. self.dc.BeginDrawing()
  377. self.dcTmp.BeginDrawing()
  378. # draw objects
  379. for i in range(rlist.nitems):
  380. robj = rlist.item[i].contents
  381. self._drawObject(robj)
  382. self.dc.EndDrawing()
  383. self.dcTmp.EndDrawing()
  384. # reset list of selected features by cat
  385. # list of ids - see IsSelected()
  386. self.selected['field'] = -1
  387. self.selected['cats'] = list()
  388. def _getSelectType(self):
  389. """!Get type(s) to be selected
  390. Used by SelectLinesByBox() and SelectLineByPoint()
  391. """
  392. ftype = 0
  393. for feature in (('point', GV_POINT),
  394. ('line', GV_LINE),
  395. ('centroid', GV_CENTROID),
  396. ('boundary', GV_BOUNDARY)):
  397. if UserSettings.Get(group = 'vdigit', key = 'selectType',
  398. subkey = [feature[0], 'enabled']):
  399. ftype |= feature[1]
  400. return ftype
  401. def _validLine(self, line):
  402. """!Check if feature id is valid
  403. @param line feature id
  404. @return True valid feature id
  405. @return False invalid
  406. """
  407. if line > 0 and line <= Vect_get_num_lines(self.poMapInfo):
  408. return True
  409. return False
  410. def SelectLinesByBox(self, bbox, drawSeg = False, poMapInfo = None):
  411. """!Select vector objects by given bounding box
  412. If line id is already in the list of selected lines, then it will
  413. be excluded from this list.
  414. @param bbox bounding box definition
  415. @param drawSeg True to draw segments of line
  416. @param poMapInfo use external Map_info, None for self.poMapInfo
  417. @return number of selected features
  418. @return None on error
  419. """
  420. thisMapInfo = poMapInfo is None
  421. if not poMapInfo:
  422. poMapInfo = self.poMapInfo
  423. if not poMapInfo:
  424. return None
  425. if thisMapInfo:
  426. self._drawSegments = drawSeg
  427. self._drawSelected = True
  428. # select by ids
  429. self.selected['cats'] = list()
  430. poList = Vect_new_list()
  431. x1, y1 = bbox[0]
  432. x2, y2 = bbox[1]
  433. poBbox = Vect_new_line_struct()
  434. Vect_append_point(poBbox, x1, y1, 0.0)
  435. Vect_append_point(poBbox, x2, y1, 0.0)
  436. Vect_append_point(poBbox, x2, y2, 0.0)
  437. Vect_append_point(poBbox, x1, y2, 0.0)
  438. Vect_append_point(poBbox, x1, y1, 0.0)
  439. Vect_select_lines_by_polygon(poMapInfo, poBbox,
  440. 0, None, # isles
  441. self._getSelectType(), poList)
  442. flist = poList.contents
  443. nlines = flist.n_values
  444. Debug.msg(1, "DisplayDriver.SelectLinesByBox() num = %d", nlines)
  445. for i in range(nlines):
  446. line = flist.value[i]
  447. if UserSettings.Get(group = 'vdigit', key = 'selectInside',
  448. subkey = 'enabled'):
  449. inside = True
  450. if not self._validLine(line):
  451. return None
  452. Vect_read_line(poMapInfo, self.poPoints, None, line)
  453. points = self.poPoints.contents
  454. for p in range(points.n_points):
  455. if not Vect_point_in_poly(points.x[p], points.y[p],
  456. poBbox):
  457. inside = False
  458. break
  459. if not inside:
  460. continue # skip lines just overlapping bbox
  461. if not self._isSelected(line):
  462. self.selected['ids'].append(line)
  463. else:
  464. self.selected['ids'].remove(line)
  465. Vect_destroy_line_struct(poBbox)
  466. Vect_destroy_list(poList)
  467. return nlines
  468. def SelectLineByPoint(self, point, poMapInfo = None):
  469. """!Select vector feature by given point in given
  470. threshold
  471. Only one vector object can be selected. Bounding boxes of
  472. all segments are stores.
  473. @param point points coordinates (x, y)
  474. @param poMapInfo use external Map_info, None for self.poMapInfo
  475. @return dict {'line' : feature id, 'point' : point on line}
  476. """
  477. thisMapInfo = poMapInfo is None
  478. if not poMapInfo:
  479. poMapInfo = self.poMapInfo
  480. if not poMapInfo:
  481. return { 'line' : -1, 'point': None }
  482. if thisMapInfo:
  483. self._drawSelected = True
  484. # select by ids
  485. self.selected['cats'] = list()
  486. poFound = Vect_new_list()
  487. lineNearest = Vect_find_line_list(poMapInfo, point[0], point[1], 0,
  488. self._getSelectType(), self.GetThreshold(), self.is3D,
  489. None, poFound)
  490. Debug.msg(1, "DisplayDriver.SelectLineByPoint() found = %d", lineNearest)
  491. if lineNearest > 0:
  492. if not self._isSelected(lineNearest):
  493. self.selected['ids'].append(lineNearest)
  494. else:
  495. self.selected['ids'].remove(lineNearest)
  496. px = c_double()
  497. py = c_double()
  498. pz = c_double()
  499. if not self._validLine(lineNearest):
  500. return { 'line' : -1, 'point': None }
  501. ftype = Vect_read_line(poMapInfo, self.poPoints, self.poCats, lineNearest)
  502. Vect_line_distance (self.poPoints, point[0], point[1], 0.0, self.is3D,
  503. byref(px), byref(py), byref(pz),
  504. None, None, None)
  505. # check for duplicates
  506. if self.settings['highlightDupl']['enabled']:
  507. found = poFound.contents
  508. for i in range(found.n_values):
  509. line = found.value[i]
  510. if line != lineNearest:
  511. self.selected['ids'].append(line)
  512. self.GetDuplicates()
  513. for i in range(found.n_values):
  514. line = found.value[i]
  515. if line != lineNearest and not self._isDuplicated(line):
  516. self.selected['ids'].remove(line)
  517. Vect_destroy_list(poFound)
  518. if thisMapInfo:
  519. # drawing segments can be very expensive
  520. # only one features selected
  521. self._drawSegments = True
  522. return { 'line' : lineNearest,
  523. 'point' : (px.value, py.value, pz.value) }
  524. def _listToIList(self, plist):
  525. """!Generate from list struct_ilist
  526. """
  527. ilist = Vect_new_list()
  528. for val in plist:
  529. Vect_list_append(ilist, val)
  530. return ilist
  531. def GetSelectedIList(self, ilist = None):
  532. """!Get list of selected objects as struct_ilist
  533. Returned IList must be freed by Vect_destroy_list().
  534. @return struct_ilist
  535. """
  536. if ilist:
  537. return self._listToIList(ilist)
  538. return self._listToIList(self.selected['ids'])
  539. def GetSelected(self, grassId = True):
  540. """!Get ids of selected objects
  541. @param grassId True for feature id, False for PseudoDC id
  542. @return list of ids of selected vector objects
  543. """
  544. if grassId:
  545. return self.selected['ids']
  546. dc_ids = list()
  547. if not self._drawSegments:
  548. dc_ids.append(1)
  549. elif len(self.selected['ids']) > 0:
  550. # only first selected feature
  551. Vect_read_line(self.poMapInfo, self.poPoints, None,
  552. self.selected['ids'][0])
  553. points = self.poPoints.contents
  554. # node - segment - vertex - segment - node
  555. for i in range(1, 2 * points.n_points):
  556. dc_ids.append(i)
  557. return dc_ids
  558. def SetSelected(self, ids, layer = -1):
  559. """!Set selected vector objects
  560. @param list of ids (None to unselect features)
  561. @param layer layer number for features selected based on category number
  562. """
  563. if ids:
  564. self._drawSelected = True
  565. else:
  566. self._drawSelected = False
  567. self.selected['field'] = layer
  568. if layer > 0:
  569. self.selected['cats'] = ids
  570. self.selected['ids'] = list()
  571. ### cidx is not up-to-date
  572. # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist)
  573. nlines = Vect_get_num_lines(self.poMapInfo)
  574. for line in range(1, nlines + 1):
  575. if not Vect_line_alive(self.poMapInfo, line):
  576. continue
  577. ltype = Vect_read_line (self.poMapInfo, None, self.poCats, line)
  578. if not (ltype & (GV_POINTS | GV_LINES)):
  579. continue
  580. found = False
  581. cats = self.poCats.contents
  582. for i in range(0, cats.n_cats):
  583. for cat in self.selected['cats']:
  584. if cats.cat[i] == cat:
  585. found = True
  586. break
  587. if found:
  588. self.selected['ids'].append(line)
  589. else:
  590. self.selected['ids'] = ids
  591. self.selected['cats'] = []
  592. def GetSelectedVertex(self, pos):
  593. """!Get PseudoDC vertex id of selected line
  594. Set bounding box for vertices of line.
  595. @param pos position
  596. @return id of center, left and right vertex
  597. @return 0 no line found
  598. @return -1 on error
  599. """
  600. returnId = list()
  601. # only one object can be selected
  602. if len(self.selected['ids']) != 1 or not self._drawSegments:
  603. return returnId
  604. startId = 1
  605. line = self.selected['ids'][0]
  606. if not self._validLine(line):
  607. return -1
  608. ftype = Vect_read_line(self.poMapInfo, self.poPoints, self.poCats, line)
  609. minDist = 0.0
  610. Gid = -1
  611. # find the closest vertex (x, y)
  612. DCid = 1
  613. points = self.poPoints.contents
  614. for idx in range(points.n_points):
  615. dist = Vect_points_distance(pos[0], pos[1], 0.0,
  616. points.x[idx], points.y[idx], points.z[idx], 0)
  617. if idx == 0:
  618. minDist = dist
  619. Gid = idx
  620. else:
  621. if minDist > dist:
  622. minDist = dist
  623. Gid = idx
  624. vx, vy = self._cell2Pixel(points.x[idx], points.y[idx], points.z[idx])
  625. rect = wx.Rect(vx, vy, 0, 0)
  626. self.dc.SetIdBounds(DCid, rect)
  627. DCid += 2
  628. if minDist > self.GetThreshold():
  629. return returnId
  630. # translate id
  631. DCid = Gid * 2 + 1
  632. # add selected vertex
  633. returnId.append(DCid)
  634. # left vertex
  635. if DCid == startId:
  636. returnId.append(-1)
  637. else:
  638. returnId.append(DCid - 2)
  639. # right vertex
  640. if DCid == (points.n_points - 1) * 2 + startId:
  641. returnId.append(-1)
  642. else:
  643. returnId.append(DCid + 2)
  644. return returnId
  645. def GetRegionSelected(self):
  646. """!Get minimal region extent of selected features
  647. @return n,s,w,e
  648. """
  649. regionBox = bound_box()
  650. lineBox = bound_box()
  651. setRegion = True
  652. nareas = Vect_get_num_areas(self.poMapInfo)
  653. for line in self.selected['ids']:
  654. area = Vect_get_centroid_area(self.poMapInfo, line)
  655. if area > 0 and area <= nareas:
  656. if not Vect_get_area_box(self.poMapInfo, area, byref(lineBox)):
  657. continue
  658. else:
  659. if not Vect_get_line_box(self.poMapInfo, line, byref(lineBox)):
  660. continue
  661. if setRegion:
  662. Vect_box_copy(byref(regionBox), byref(lineBox))
  663. setRegion = False
  664. else:
  665. Vect_box_extend(byref(regionBox), byref(lineBox))
  666. return regionBox.N, regionBox.S, regionBox.W, regionBox.E
  667. def DrawSelected(self, flag):
  668. """!Draw selected features
  669. @param flag True to draw selected features
  670. """
  671. self._drawSelected = bool(flag)
  672. def CloseMap(self):
  673. """!Close vector map
  674. @return 0 on success
  675. @return non-zero on error
  676. """
  677. ret = 0
  678. if self.poMapInfo:
  679. # rebuild topology
  680. Vect_build_partial(self.poMapInfo, GV_BUILD_NONE)
  681. Vect_build(self.poMapInfo)
  682. # close map and store topo/cidx
  683. ret = Vect_close(self.poMapInfo)
  684. del self.mapInfo
  685. self.poMapInfo = self.mapInfo = None
  686. return ret
  687. def OpenMap(self, name, mapset, update = True):
  688. """!Open vector map by the driver
  689. @param name name of vector map to be open
  690. @param mapset name of mapset where the vector map lives
  691. @return map_info
  692. @return None on error
  693. """
  694. Debug.msg("DisplayDriver.OpenMap(): name=%s mapset=%s updated=%d",
  695. name, mapset, update)
  696. if not self.mapInfo:
  697. self.mapInfo = Map_info()
  698. self.poMapInfo = pointer(self.mapInfo)
  699. # open existing map
  700. if update:
  701. ret = Vect_open_update(self.poMapInfo, name, mapset)
  702. else:
  703. ret = Vect_open_old(self.poMapInfo, name, mapset)
  704. self.is3D = Vect_is_3d(self.poMapInfo)
  705. if ret == -1: # error
  706. del self.mapInfo
  707. self.poMapInfo = self.mapInfo = None
  708. elif ret < 2:
  709. dlg = wx.MessageDialog(parent = self.window,
  710. message = _("Topology for vector map <%s> is not available. "
  711. "Topology is required by digitizer. Do you want to "
  712. "rebuild topology (takes some time) and open the vector map "
  713. "for editing?") % name,
  714. caption=_("Topology missing"),
  715. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  716. ret = dlg.ShowModal()
  717. if ret != wx.ID_YES:
  718. del self.mapInfo
  719. self.poMapInfo = self.mapInfo = None
  720. else:
  721. Vect_build(self.poMapInfo)
  722. return self.poMapInfo
  723. def GetMapBoundingBox(self):
  724. """!Get bounding box of (opened) vector map layer
  725. @return (w,s,b,e,n,t)
  726. """
  727. if not self.poMapInfo:
  728. return None
  729. bbox = bound_box()
  730. Vect_get_map_box(self.poMapInfo, byref(bbox))
  731. return bbox.W, bbox.S, bbox.B, \
  732. bbox.E, bbox.N, bbox.T
  733. def UpdateSettings(self, alpha = 255):
  734. """!Update display driver settings
  735. @todo map units
  736. @alpha color value for aplha channel
  737. """
  738. color = dict()
  739. for key in self.settings.keys():
  740. if key == 'lineWidth':
  741. self.settings[key] = int(UserSettings.Get(group = 'vdigit', key = 'lineWidth',
  742. subkey = 'value'))
  743. continue
  744. color = wx.Color(UserSettings.Get(group = 'vdigit', key = 'symbol',
  745. subkey = [key, 'color'])[0],
  746. UserSettings.Get(group = 'vdigit', key = 'symbol',
  747. subkey = [key, 'color'])[1],
  748. UserSettings.Get(group = 'vdigit', key = 'symbol',
  749. subkey = [key, 'color'])[2],
  750. alpha)
  751. if key == 'highlight':
  752. self.settings[key] = color
  753. continue
  754. if key == 'highlightDupl':
  755. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'checkForDupl',
  756. subkey = 'enabled'))
  757. else:
  758. self.settings[key]['enabled'] = bool(UserSettings.Get(group = 'vdigit', key = 'symbol',
  759. subkey = [key, 'enabled']))
  760. self.settings[key]['color'] = color
  761. def UpdateRegion(self):
  762. """!Update geographical region used by display driver
  763. """
  764. self.region = self.mapObj.GetCurrentRegion()
  765. def GetThreshold(self, type = 'snapping', value = None, units = None):
  766. """!Return threshold value in map units
  767. @param type snapping mode (node, vertex)
  768. @param value threshold to be set up
  769. @param units units (map, screen)
  770. @return threshold value
  771. """
  772. if value is None:
  773. value = UserSettings.Get(group = 'vdigit', key = type, subkey = 'value')
  774. if units is None:
  775. units = UserSettings.Get(group = 'vdigit', key = type, subkey = 'units')
  776. if value < 0:
  777. value = (self.region['nsres'] + self.region['ewres']) / 2.0
  778. if units == "screen pixels":
  779. # pixel -> cell
  780. res = max(self.region['nsres'], self.region['ewres'])
  781. return value * res
  782. return value
  783. def GetDuplicates(self):
  784. """!Return ids of (selected) duplicated vector features
  785. """
  786. if not self.poMapInfo:
  787. return
  788. ids = dict()
  789. APoints = Vect_new_line_struct()
  790. BPoints = Vect_new_line_struct()
  791. self.selected['idsDupl'] = list()
  792. for i in range(len(self.selected['ids'])):
  793. line1 = self.selected['ids'][i]
  794. if self._isDuplicated(line1):
  795. continue
  796. Vect_read_line(self.poMapInfo, APoints, None, line1)
  797. for line2 in self.selected['ids']:
  798. if line1 == line2 or self._isDuplicated(line2):
  799. continue
  800. Vect_read_line(self.poMapInfo, BPoints, None, line2)
  801. if Vect_line_check_duplicate(APoints, BPoints, WITHOUT_Z):
  802. if i not in ids:
  803. ids[i] = list()
  804. ids[i].append((line1, self._getCatString(line1)))
  805. self.selected['idsDupl'].append(line1)
  806. ids[i].append((line2, self._getCatString(line2)))
  807. self.selected['idsDupl'].append(line2)
  808. Vect_destroy_line_struct(APoints)
  809. Vect_destroy_line_struct(BPoints)
  810. return ids
  811. def _getCatString(self, line):
  812. Vect_read_line(self.poMapInfo, None, self.poCats, line)
  813. cats = self.poCats.contents
  814. catsDict = dict()
  815. for i in range(cats.n_cats):
  816. layer = cats.field[i]
  817. if layer not in catsDict:
  818. catsDict[layer] = list()
  819. catsDict[layer].append(cats.cat[i])
  820. catsStr = ''
  821. for l, c in catsDict.iteritems():
  822. catsStr = '%d: (%s)' % (l, ','.join(map(str, c)))
  823. return catsStr
  824. def UnSelect(self, lines):
  825. """!Unselect vector features
  826. @param lines list of feature id(s)
  827. """
  828. checkForDupl = False
  829. for line in lines:
  830. if self._isSelected(line):
  831. self.selected['ids'].remove(line)
  832. if self.settings['highlightDupl']['enabled'] and self._isDuplicated(line):
  833. checkForDupl = True
  834. if checkForDupl:
  835. self.GetDuplicates()
  836. return len(self.selected['ids'])