mapdisp_window.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621
  1. """
  2. @package mapdisp_window.py
  3. @brief GIS map display canvas, buffered window.
  4. Classes:
  5. - MapWindow
  6. - BufferedWindow
  7. (C) 2006-2009 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 Michael Barton
  12. @author Jachym Cepicky
  13. @author Martin Landa <landa.martin gmail.com>
  14. """
  15. import os
  16. import time
  17. import math
  18. import sys
  19. import wx
  20. import dbm
  21. import dbm_dialogs
  22. import gdialogs
  23. import gcmd
  24. import utils
  25. import globalvar
  26. from debug import Debug
  27. from preferences import globalSettings as UserSettings
  28. from vdigit import GV_LINES as VDigit_Lines_Type
  29. from vdigit import VDigitCategoryDialog
  30. from vdigit import VDigitZBulkDialog
  31. from vdigit import VDigitDuplicatesDialog
  32. from vdigit import PseudoDC
  33. class MapWindow(object):
  34. """
  35. Abstract map window class
  36. Parent for BufferedWindow class (2D display mode) and
  37. GLWindow (3D display mode)
  38. """
  39. def __init__(self, parent, id=wx.ID_ANY,
  40. pos=wx.DefaultPosition,
  41. size=wx.DefaultSize,
  42. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  43. Map=None, tree=None, lmgr=None):
  44. self.parent = parent # MapFrame
  45. #
  46. # mouse attributes -- position on the screen, begin and end of
  47. # dragging, and type of drawing
  48. #
  49. self.mouse = {
  50. 'begin': [0, 0], # screen coordinates
  51. 'end' : [0, 0],
  52. 'use' : "pointer",
  53. 'box' : "point"
  54. }
  55. def EraseMap(self):
  56. """
  57. Erase the canvas (virtual method)
  58. """
  59. pass
  60. def UpdateMap(self):
  61. """
  62. Updates the canvas anytime there is a change to the
  63. underlaying images or to the geometry of the canvas.
  64. """
  65. pass
  66. def OnLeftDown(self, event):
  67. pass
  68. def OnLeftUp(self, event):
  69. pass
  70. def OnMouseMotion(self, event):
  71. pass
  72. def OnZoomToMap(self, event):
  73. pass
  74. def OnZoomToRaster(self, event):
  75. pass
  76. def GetSelectedLayer(self, type = 'layer', multi = False):
  77. """
  78. Get selected layer from layer tree
  79. @param type 'item' / 'layer' / 'nviz'
  80. @param multi return first selected layer or all
  81. @return layer / map layer properties / nviz properties
  82. @return None / [] on failure
  83. """
  84. ret = []
  85. if not self.tree or \
  86. not self.tree.GetSelection():
  87. if multi:
  88. return []
  89. else:
  90. return None
  91. if multi and \
  92. type == 'item':
  93. return self.tree.GetSelections()
  94. for item in self.tree.GetSelections():
  95. if not item.IsChecked():
  96. if multi:
  97. continue
  98. else:
  99. return None
  100. if type == 'item': # -> multi = False
  101. return item
  102. try:
  103. if type == 'nviz':
  104. layer = self.tree.GetPyData(item)[0]['nviz']
  105. else:
  106. layer = self.tree.GetPyData(item)[0]['maplayer']
  107. except:
  108. layer = None
  109. if multi:
  110. ret.append(layer)
  111. else:
  112. return layer
  113. return ret
  114. class BufferedWindow(MapWindow, wx.Window):
  115. """
  116. A Buffered window class.
  117. When the drawing needs to change, you app needs to call the
  118. UpdateMap() method. Since the drawing is stored in a bitmap, you
  119. can also save the drawing to file by calling the
  120. SaveToFile(self,file_name,file_type) method.
  121. """
  122. def __init__(self, parent, id,
  123. pos = wx.DefaultPosition,
  124. size = wx.DefaultSize,
  125. style=wx.NO_FULL_REPAINT_ON_RESIZE,
  126. Map=None, tree=None, lmgr=None):
  127. MapWindow.__init__(self, parent, id, pos, size, style,
  128. Map, tree, lmgr)
  129. wx.Window.__init__(self, parent, id, pos, size, style)
  130. self.Map = Map
  131. self.tree = tree
  132. #
  133. # Flags
  134. #
  135. self.resize = False # indicates whether or not a resize event has taken place
  136. self.dragimg = None # initialize variable for map panning
  137. #
  138. # Variable for drawing on DC
  139. #
  140. self.pen = None # pen for drawing zoom boxes, etc.
  141. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  142. # List of wx.Point tuples defining a polyline (geographical coordinates)
  143. self.polycoords = []
  144. # ID of rubber band line
  145. self.lineid = None
  146. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  147. self.plineid = None
  148. #
  149. # Event bindings
  150. #
  151. self.Bind(wx.EVT_PAINT, self.OnPaint)
  152. self.Bind(wx.EVT_SIZE, self.OnSize)
  153. self.Bind(wx.EVT_IDLE, self.OnIdle)
  154. self.Bind(wx.EVT_MOTION, self.MouseActions)
  155. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  156. self.processMouse = True
  157. #
  158. # Render output objects
  159. #
  160. self.mapfile = None # image file to be rendered
  161. self.img = "" # wx.Image object (self.mapfile)
  162. # used in digitization tool (do not redraw vector map)
  163. self.imgVectorMap = None
  164. # decoration overlays
  165. self.overlays = {}
  166. # images and their PseudoDC ID's for painting and dragging
  167. self.imagedict = {}
  168. self.select = {} # selecting/unselecting decorations for dragging
  169. self.textdict = {} # text, font, and color indexed by id
  170. self.currtxtid = None # PseudoDC id for currently selected text
  171. #
  172. # Zoom objects
  173. #
  174. self.zoomhistory = [] # list of past zoom extents
  175. self.currzoom = 0 # current set of extents in zoom history being used
  176. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  177. self.hitradius = 10 # distance for selecting map decorations
  178. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  179. # OnSize called to make sure the buffer is initialized.
  180. # This might result in OnSize getting called twice on some
  181. # platforms at initialization, but little harm done.
  182. ### self.OnSize(None)
  183. # create PseudoDC used for background map, map decorations like scales and legends
  184. self.pdc = PseudoDC()
  185. # used for digitization tool
  186. self.pdcVector = None
  187. # decorations (region box, etc.)
  188. self.pdcDec = PseudoDC()
  189. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  190. self.pdcTmp = PseudoDC()
  191. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  192. self.redrawAll = True
  193. # will store an off screen empty bitmap for saving to file
  194. self._buffer = ''
  195. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  196. # vars for handling mouse clicks
  197. self.dragid = -1
  198. self.lastpos = (0, 0)
  199. def Draw(self, pdc, img=None, drawid=None, pdctype='image', coords=[0, 0, 0, 0]):
  200. """
  201. Draws map and overlay decorations
  202. """
  203. if drawid == None:
  204. if pdctype == 'image' and img:
  205. drawid = self.imagedict[img]
  206. elif pdctype == 'clear':
  207. drawid == None
  208. else:
  209. drawid = wx.NewId()
  210. if img and pdctype == 'image':
  211. # self.imagedict[img]['coords'] = coords
  212. self.select[self.imagedict[img]['id']] = False # ?
  213. pdc.BeginDrawing()
  214. if drawid != 99:
  215. bg = wx.TRANSPARENT_BRUSH
  216. else:
  217. bg = wx.Brush(self.GetBackgroundColour())
  218. pdc.SetBackground(bg)
  219. ### pdc.Clear()
  220. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % \
  221. (drawid, pdctype, coords))
  222. # set PseudoDC id
  223. if drawid is not None:
  224. pdc.SetId(drawid)
  225. if pdctype == 'clear': # erase the display
  226. bg = wx.WHITE_BRUSH
  227. # bg = wx.Brush(self.GetBackgroundColour())
  228. pdc.SetBackground(bg)
  229. pdc.RemoveAll()
  230. pdc.Clear()
  231. pdc.EndDrawing()
  232. self.Refresh()
  233. return
  234. if pdctype == 'image': # draw selected image
  235. bitmap = wx.BitmapFromImage(img)
  236. w,h = bitmap.GetSize()
  237. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  238. pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
  239. elif pdctype == 'box': # draw a box on top of the map
  240. if self.pen:
  241. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  242. pdc.SetPen(self.pen)
  243. x2 = max(coords[0],coords[2])
  244. x1 = min(coords[0],coords[2])
  245. y2 = max(coords[1],coords[3])
  246. y1 = min(coords[1],coords[3])
  247. rwidth = x2-x1
  248. rheight = y2-y1
  249. rect = wx.Rect(x1, y1, rwidth, rheight)
  250. pdc.DrawRectangleRect(rect)
  251. pdc.SetIdBounds(drawid, rect)
  252. elif pdctype == 'line': # draw a line on top of the map
  253. if self.pen:
  254. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  255. pdc.SetPen(self.pen)
  256. pdc.DrawLine(wx.Point(coords[0], coords[1]),
  257. wx.Point(coords[2], coords[3]))
  258. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
  259. # self.ovlcoords[drawid] = coords
  260. elif pdctype == 'polyline': # draw a polyline on top of the map
  261. if self.polypen:
  262. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  263. pdc.SetPen(self.polypen)
  264. ### pdc.DrawLines(coords)
  265. if (len(coords) < 2):
  266. return
  267. i = 1
  268. while i < len(coords):
  269. pdc.DrawLine(wx.Point(coords[i-1][0], coords[i-1][1]),
  270. wx.Point(coords[i][0], coords[i][1]))
  271. i += 1
  272. # get bounding rectangle for polyline
  273. xlist = []
  274. ylist = []
  275. if len(coords) > 0:
  276. for point in coords:
  277. x,y = point
  278. xlist.append(x)
  279. ylist.append(y)
  280. x1=min(xlist)
  281. x2=max(xlist)
  282. y1=min(ylist)
  283. y2=max(ylist)
  284. pdc.SetIdBounds(drawid, wx.Rect(x1,y1,x2,y2))
  285. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  286. elif pdctype == 'point': # draw point
  287. if self.pen:
  288. pdc.SetPen(self.pen)
  289. pdc.DrawPoint(coords[0], coords[1])
  290. coordsBound = (coords[0] - 5,
  291. coords[1] - 5,
  292. coords[0] + 5,
  293. coords[1] + 5)
  294. pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
  295. # self.ovlcoords[drawid] = coords
  296. elif pdctype == 'text': # draw text on top of map
  297. if not img['active']:
  298. return #only draw active text
  299. if img.has_key('rotation'):
  300. rotation = float(img['rotation'])
  301. else:
  302. rotation = 0.0
  303. w, h = self.GetFullTextExtent(img['text'])[0:2]
  304. pdc.SetFont(img['font'])
  305. pdc.SetTextForeground(img['color'])
  306. coords, w, h = self.TextBounds(img)
  307. if rotation == 0:
  308. pdc.DrawText(img['text'], coords[0], coords[1])
  309. else:
  310. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  311. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], w, h))
  312. pdc.EndDrawing()
  313. self.Refresh()
  314. return drawid
  315. def TextBounds(self, textinfo):
  316. """
  317. Return text boundary data
  318. @param textinfo text metadata (text, font, color, rotation)
  319. @param coords reference point
  320. """
  321. if textinfo.has_key('rotation'):
  322. rotation = float(textinfo['rotation'])
  323. else:
  324. rotation = 0.0
  325. coords = textinfo['coords']
  326. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  327. (textinfo['text'], rotation))
  328. self.Update()
  329. ### self.Refresh()
  330. self.SetFont(textinfo['font'])
  331. w, h = self.GetTextExtent(textinfo['text'])
  332. if rotation == 0:
  333. coords[2], coords[3] = coords[0] + w, coords[1] + h
  334. return coords, w, h
  335. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  336. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  337. coords[2] = coords[0] + boxw
  338. coords[3] = coords[1] + boxh
  339. return coords, boxw, boxh
  340. def OnPaint(self, event):
  341. """
  342. Draw PseudoDC's to buffered paint DC
  343. self.pdc for background and decorations
  344. self.pdcVector for vector map which is edited
  345. self.pdcTmp for temporaly drawn objects (self.polycoords)
  346. If self.redrawAll is False on self.pdcTmp content is re-drawn
  347. """
  348. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  349. dc = wx.BufferedPaintDC(self, self.buffer)
  350. ### dc.SetBackground(wx.Brush("White"))
  351. dc.Clear()
  352. # use PrepareDC to set position correctly
  353. self.PrepareDC(dc)
  354. # create a clipping rect from our position and size
  355. # and update region
  356. rgn = self.GetUpdateRegion().GetBox()
  357. dc.SetClippingRect(rgn)
  358. switchDraw = False
  359. if self.redrawAll is None:
  360. self.redrawAll = True
  361. switchDraw = True
  362. if self.redrawAll: # redraw pdc and pdcVector
  363. # draw to the dc using the calculated clipping rect
  364. self.pdc.DrawToDCClipped(dc, rgn)
  365. # draw vector map layer
  366. if self.pdcVector:
  367. # decorate with GDDC (transparency)
  368. try:
  369. gcdc = wx.GCDC(dc)
  370. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  371. except NotImplementedError, e:
  372. print >> sys.stderr, e
  373. self.pdcVector.DrawToDCClipped(dc, rgn)
  374. self.bufferLast = None
  375. else: # do not redraw pdc and pdcVector
  376. if self.bufferLast is None:
  377. # draw to the dc
  378. self.pdc.DrawToDC(dc)
  379. if self.pdcVector:
  380. # decorate with GDDC (transparency)
  381. try:
  382. gcdc = wx.GCDC(dc)
  383. self.pdcVector.DrawToDC(gcdc)
  384. except NotImplementedError, e:
  385. print >> sys.stderr, e
  386. self.pdcVector.DrawToDC(dc)
  387. # store buffered image
  388. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  389. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  390. pdcLast = PseudoDC()
  391. pdcLast.DrawBitmap(self.bufferLast, 0, 0, False)
  392. pdcLast.DrawToDC(dc)
  393. # draw decorations (e.g. region box)
  394. try:
  395. gcdc = wx.GCDC(dc)
  396. self.pdcDec.DrawToDC(gcdc)
  397. except NotImplementedError, e:
  398. print >> sys.stderr, e
  399. self.pdcDec.DrawToDC(dc)
  400. # draw temporary object on the foreground
  401. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  402. self.pdcTmp.DrawToDC(dc)
  403. if switchDraw:
  404. self.redrawAll = False
  405. def OnSize(self, event):
  406. """
  407. Scale map image so that it is
  408. the same size as the Window
  409. """
  410. Debug.msg(3, "BufferedWindow.OnSize():")
  411. # set size of the input image
  412. self.Map.ChangeMapSize(self.GetClientSize())
  413. # align extent based on center point and display resolution
  414. # this causes that image is not resized when display windows is resized
  415. # self.Map.AlignExtentFromDisplay()
  416. # Make new off screen bitmap: this bitmap will always have the
  417. # current drawing in it, so it can be used to save the image to
  418. # a file, or whatever.
  419. self.buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  420. # get the image to be rendered
  421. self.img = self.GetImage()
  422. # update map display
  423. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  424. self.img = self.img.Scale(self.Map.width, self.Map.height)
  425. if len(self.Map.GetListOfLayers()) > 0:
  426. self.UpdateMap()
  427. # re-render image on idle
  428. self.resize = True
  429. # reposition checkbox in statusbar
  430. self.parent.StatusbarReposition()
  431. # update statusbar
  432. self.parent.StatusbarUpdate()
  433. def OnIdle(self, event):
  434. """
  435. Only re-render a composite map image from GRASS during
  436. idle time instead of multiple times during resizing.
  437. """
  438. if self.resize:
  439. self.UpdateMap(render=True)
  440. event.Skip()
  441. def SaveToFile(self, FileName, FileType):
  442. """
  443. This draws the psuedo DC to a buffer that
  444. can be saved to a file.
  445. """
  446. dc = wx.BufferedPaintDC(self, self.buffer)
  447. self.pdc.DrawToDC(dc)
  448. if self.pdcVector:
  449. self.pdcVector.DrawToDC(dc)
  450. self.buffer.SaveFile(FileName, FileType)
  451. def GetOverlay(self):
  452. """
  453. Converts rendered overlay files to wx.Image
  454. Updates self.imagedict
  455. @return list of images
  456. """
  457. imgs = []
  458. for overlay in self.Map.GetListOfLayers(l_type="overlay", l_active=True):
  459. if os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  460. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  461. self.imagedict[img] = { 'id' : overlay.id,
  462. 'layer' : overlay }
  463. imgs.append(img)
  464. return imgs
  465. def GetImage(self):
  466. """
  467. Converts redered map files to wx.Image
  468. Updates self.imagedict (id=99)
  469. @return wx.Image instance (map composition)
  470. """
  471. imgId = 99
  472. if self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  473. os.path.getsize(self.Map.mapfile):
  474. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  475. else:
  476. img = None
  477. self.imagedict[img] = { 'id': imgId }
  478. return img
  479. def UpdateMap(self, render=True, renderVector=True):
  480. """
  481. Updates the canvas anytime there is a change to the
  482. underlaying images or to the geometry of the canvas.
  483. @param render re-render map composition
  484. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  485. """
  486. start = time.clock()
  487. self.resize = False
  488. # if len(self.Map.GetListOfLayers()) == 0:
  489. # return False
  490. if self.img is None:
  491. render = True
  492. #
  493. # initialize process bar (only on 'render')
  494. #
  495. if render is True or renderVector is True:
  496. self.parent.onRenderGauge.Show()
  497. if self.parent.onRenderGauge.GetRange() > 0:
  498. self.parent.onRenderGauge.SetValue(1)
  499. #
  500. # render background image if needed
  501. #
  502. # update layer dictionary if there has been a change in layers
  503. if self.tree and self.tree.reorder == True:
  504. self.tree.ReorderLayers()
  505. # reset flag for auto-rendering
  506. if self.tree:
  507. self.tree.rerender = False
  508. if render:
  509. # update display size
  510. self.Map.ChangeMapSize(self.GetClientSize())
  511. if self.parent.compResolution.IsChecked():
  512. # use computation region resolution for rendering
  513. windres = True
  514. else:
  515. windres = False
  516. self.mapfile = self.Map.Render(force=True, mapWindow=self.parent,
  517. windres=windres)
  518. else:
  519. self.mapfile = self.Map.Render(force=False, mapWindow=self.parent)
  520. self.img = self.GetImage() # id=99
  521. #
  522. # clear pseudoDcs
  523. #
  524. for pdc in (self.pdc,
  525. self.pdcDec,
  526. self.pdcTmp):
  527. pdc.Clear()
  528. pdc.RemoveAll()
  529. #
  530. # draw background map image to PseudoDC
  531. #
  532. if not self.img:
  533. self.Draw(self.pdc, pdctype='clear')
  534. else:
  535. try:
  536. id = self.imagedict[self.img]['id']
  537. except:
  538. return False
  539. self.Draw(self.pdc, self.img, drawid=id)
  540. #
  541. # render vector map layer
  542. #
  543. digitToolbar = self.parent.toolbars['vdigit']
  544. if renderVector and digitToolbar and \
  545. digitToolbar.GetLayer():
  546. # set region
  547. self.parent.digit.driver.UpdateRegion()
  548. # re-calculate threshold for digitization tool
  549. self.parent.digit.driver.GetThreshold()
  550. # draw map
  551. self.pdcVector.Clear()
  552. self.pdcVector.RemoveAll()
  553. try:
  554. item = self.tree.FindItemByData('maplayer', digitToolbar.GetLayer())
  555. except TypeError:
  556. item = None
  557. if item and self.tree.IsItemChecked(item):
  558. self.parent.digit.driver.DrawMap()
  559. # translate tmp objects (pointer position)
  560. if digitToolbar.GetAction() == 'moveLine':
  561. if hasattr(self, "vdigitMove") and \
  562. self.vdigitMove.has_key('beginDiff'):
  563. # move line
  564. for id in self.vdigitMove['id']:
  565. self.pdcTmp.TranslateId(id,
  566. self.vdigitMove['beginDiff'][0],
  567. self.vdigitMove['beginDiff'][1])
  568. del self.vdigitMove['beginDiff']
  569. #
  570. # render overlays
  571. #
  572. for img in self.GetOverlay():
  573. # draw any active and defined overlays
  574. if self.imagedict[img]['layer'].IsActive():
  575. id = self.imagedict[img]['id']
  576. self.Draw(self.pdc, img=img, drawid=id,
  577. pdctype=self.overlays[id]['pdcType'], coords=self.overlays[id]['coords'])
  578. for id in self.textdict.keys():
  579. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  580. pdctype='text', coords=[10, 10, 10, 10])
  581. # optionally draw computational extent box
  582. self.DrawCompRegionExtent()
  583. #
  584. # redraw pdcTmp if needed
  585. #
  586. if len(self.polycoords) > 0:
  587. self.DrawLines(self.pdcTmp)
  588. if not self.parent.IsStandalone() and \
  589. self.parent.GetLayerManager().georectifying:
  590. # -> georectifier (redraw GCPs)
  591. if self.parent.toolbars['georect']:
  592. coordtype = 'gcpcoord'
  593. else:
  594. coordtype = 'mapcoord'
  595. self.parent.GetLayerManager().georectifying.DrawGCP(coordtype)
  596. #
  597. # clear measurement
  598. #
  599. if self.mouse["use"] == "measure":
  600. self.ClearLines(pdc=self.pdcTmp)
  601. self.polycoords = []
  602. self.mouse['use'] = 'pointer'
  603. self.mouse['box'] = 'point'
  604. self.mouse['end'] = [0, 0]
  605. self.SetCursor(self.parent.cursors["default"])
  606. stop = time.clock()
  607. #
  608. # hide process bar
  609. #
  610. self.parent.onRenderGauge.Hide()
  611. #
  612. # update statusbar
  613. #
  614. ### self.Map.SetRegion()
  615. self.parent.StatusbarUpdate()
  616. Debug.msg (2, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  617. (render, renderVector, (stop-start)))
  618. return True
  619. def DrawCompRegionExtent(self):
  620. """
  621. Draw computational region extent in the display
  622. Display region is drawn as a blue box inside the computational region,
  623. computational region inside a display region as a red box).
  624. """
  625. if hasattr(self, "regionCoords"):
  626. compReg = self.Map.GetRegion()
  627. dispReg = self.Map.GetCurrentRegion()
  628. reg = None
  629. if self.IsInRegion(dispReg, compReg):
  630. self.polypen = wx.Pen(colour=wx.Colour(0, 0, 255, 128), width=3, style=wx.SOLID)
  631. reg = dispReg
  632. else:
  633. self.polypen = wx.Pen(colour=wx.Colour(255, 0, 0, 128),
  634. width=3, style=wx.SOLID)
  635. reg = compReg
  636. self.regionCoords = []
  637. self.regionCoords.append((reg['w'], reg['n']))
  638. self.regionCoords.append((reg['e'], reg['n']))
  639. self.regionCoords.append((reg['e'], reg['s']))
  640. self.regionCoords.append((reg['w'], reg['s']))
  641. self.regionCoords.append((reg['w'], reg['n']))
  642. # draw region extent
  643. self.DrawLines(pdc=self.pdcDec, polycoords=self.regionCoords)
  644. def IsInRegion(self, region, refRegion):
  645. """
  646. Test if 'region' is inside of 'refRegion'
  647. @param region input region
  648. @param refRegion reference region (e.g. computational region)
  649. @return True if region is inside of refRegion
  650. @return False
  651. """
  652. if region['s'] >= refRegion['s'] and \
  653. region['n'] <= refRegion['n'] and \
  654. region['w'] >= refRegion['w'] and \
  655. region['e'] <= refRegion['e']:
  656. return True
  657. return False
  658. def EraseMap(self):
  659. """
  660. Erase the canvas
  661. """
  662. self.Draw(self.pdc, pdctype='clear')
  663. if self.pdcVector:
  664. self.Draw(self.pdcVector, pdctype='clear')
  665. self.Draw(self.pdcDec, pdctype='clear')
  666. self.Draw(self.pdcTmp, pdctype='clear')
  667. def DragMap(self, moveto):
  668. """
  669. Drag the entire map image for panning.
  670. """
  671. dc = wx.BufferedDC(wx.ClientDC(self))
  672. dc.SetBackground(wx.Brush("White"))
  673. dc.Clear()
  674. self.dragimg = wx.DragImage(self.buffer)
  675. self.dragimg.BeginDrag((0, 0), self)
  676. self.dragimg.GetImageRect(moveto)
  677. self.dragimg.Move(moveto)
  678. self.dragimg.DoDrawImage(dc, moveto)
  679. self.dragimg.EndDrag()
  680. return True
  681. def DragItem(self, id, event):
  682. """
  683. Drag an overlay decoration item
  684. """
  685. if id == 99 or id == '' or id == None: return
  686. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  687. x, y = self.lastpos
  688. dx = event.GetX() - x
  689. dy = event.GetY() - y
  690. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  691. r = self.pdc.GetIdBounds(id)
  692. ### FIXME in vdigit/pseudodc.i
  693. if type(r) is list:
  694. r = wx.Rect(r[0], r[1], r[2], r[3])
  695. if id > 100: # text dragging
  696. rtop = (r[0],r[1]-r[3],r[2],r[3])
  697. r = r.Union(rtop)
  698. rleft = (r[0]-r[2],r[1],r[2],r[3])
  699. r = r.Union(rleft)
  700. self.pdc.TranslateId(id, dx, dy)
  701. r2 = self.pdc.GetIdBounds(id)
  702. if type(r2) is list:
  703. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  704. if id > 100: # text
  705. self.textdict[id]['coords'] = r2
  706. r = r.Union(r2)
  707. r.Inflate(4,4)
  708. self.RefreshRect(r, False)
  709. self.lastpos = (event.GetX(), event.GetY())
  710. def MouseDraw(self, pdc=None, begin=None, end=None):
  711. """
  712. Mouse box or line from 'begin' to 'end'
  713. If not given from self.mouse['begin'] to self.mouse['end'].
  714. """
  715. self.redrawAll = False
  716. if not pdc:
  717. return
  718. if begin is None:
  719. begin = self.mouse['begin']
  720. if end is None:
  721. end = self.mouse['end']
  722. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  723. (self.mouse['use'], self.mouse['box'],
  724. begin[0], begin[1], end[0], end[1]))
  725. if self.mouse['box'] == "box":
  726. boxid = wx.ID_NEW
  727. mousecoords = [begin[0], begin[1],
  728. end[0], end[1]]
  729. r = pdc.GetIdBounds(boxid)
  730. if type(r) is list:
  731. r = wx.Rect(r[0], r[1], r[2], r[3])
  732. r.Inflate(4, 4)
  733. pdc.ClearId(boxid)
  734. self.RefreshRect(r, False)
  735. pdc.SetId(boxid)
  736. self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
  737. elif self.mouse['box'] == "line":
  738. self.lineid = wx.ID_NEW
  739. mousecoords = [begin[0], begin[1], \
  740. end[0], end[1]]
  741. x1=min(begin[0],end[0])
  742. x2=max(begin[0],end[0])
  743. y1=min(begin[1],end[1])
  744. y2=max(begin[1],end[1])
  745. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  746. r.Inflate(4,4)
  747. try:
  748. pdc.ClearId(self.lineid)
  749. except:
  750. pass
  751. self.RefreshRect(r, False)
  752. pdc.SetId(self.lineid)
  753. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=mousecoords)
  754. def DrawLines(self, pdc=None, polycoords=None):
  755. """
  756. Draw polyline in PseudoDC
  757. Set self.pline to wx.NEW_ID + 1
  758. polycoords - list of polyline vertices, geographical coordinates
  759. (if not given, self.polycoords is used)
  760. """
  761. if not pdc:
  762. pdc = self.pdcTmp
  763. if not polycoords:
  764. polycoords = self.polycoords
  765. if len(polycoords) > 0:
  766. self.plineid = wx.ID_NEW + 1
  767. # convert from EN to XY
  768. coords = []
  769. for p in polycoords:
  770. coords.append(self.Cell2Pixel(p))
  771. self.Draw(pdc, drawid=self.plineid, pdctype='polyline', coords=coords)
  772. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  773. (coords, self.plineid))
  774. return self.plineid
  775. return -1
  776. def DrawCross(self, pdc, coords, size, rotation=0,
  777. text=None, textAlign='lr', textOffset=(5, 5)):
  778. """Draw cross in PseudoDC
  779. @todo implement rotation
  780. @param pdc PseudoDC
  781. @param coord center coordinates
  782. @param rotation rotate symbol
  783. @param text draw also text (text, font, color, rotation)
  784. @param textAlign alignment (default 'lower-right')
  785. @textOffset offset for text (from center point)
  786. """
  787. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  788. (pdc, coords, size))
  789. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  790. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  791. self.lineid = wx.NewId()
  792. for lineCoords in coordsCross:
  793. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=lineCoords)
  794. if not text:
  795. return self.lineid
  796. if textAlign == 'ul':
  797. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  798. elif textAlign == 'ur':
  799. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  800. elif textAlign == 'lr':
  801. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  802. else:
  803. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  804. self.Draw(pdc, img=text,
  805. pdctype='text', coords=coord)
  806. return self.lineid
  807. def MouseActions(self, event):
  808. """
  809. Mouse motion and button click notifier
  810. """
  811. if not self.processMouse:
  812. return
  813. ### if self.redrawAll is False:
  814. ### self.redrawAll = True
  815. # zoom with mouse wheel
  816. if event.GetWheelRotation() != 0:
  817. self.OnMouseWheel(event)
  818. # left mouse button pressed
  819. elif event.LeftDown():
  820. self.OnLeftDown(event)
  821. # left mouse button released
  822. elif event.LeftUp():
  823. self.OnLeftUp(event)
  824. # dragging
  825. elif event.Dragging():
  826. self.OnDragging(event)
  827. # double click
  828. elif event.ButtonDClick():
  829. self.OnButtonDClick(event)
  830. # middle mouse button pressed
  831. elif event.MiddleDown():
  832. self.OnMiddleDown(event)
  833. # right mouse button pressed
  834. elif event.RightDown():
  835. self.OnRightDown(event)
  836. # right mouse button released
  837. elif event.RightUp():
  838. self.OnRightUp(event)
  839. elif event.Moving():
  840. self.OnMouseMoving(event)
  841. # event.Skip()
  842. def OnMouseWheel(self, event):
  843. """
  844. Mouse wheel moved
  845. """
  846. self.processMouse = False
  847. current = event.GetPositionTuple()[:]
  848. wheel = event.GetWheelRotation()
  849. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  850. # zoom 1/2 of the screen, centered to current mouse position (TODO: settings)
  851. begin = (current[0] - self.Map.width / 4,
  852. current[1] - self.Map.height / 4)
  853. end = (current[0] + self.Map.width / 4,
  854. current[1] + self.Map.height / 4)
  855. if wheel > 0:
  856. zoomtype = 1
  857. else:
  858. zoomtype = -1
  859. # zoom
  860. self.Zoom(begin, end, zoomtype)
  861. # redraw map
  862. self.UpdateMap()
  863. ### self.OnPaint(None)
  864. # update statusbar
  865. self.parent.StatusbarUpdate()
  866. self.Refresh()
  867. self.processMouse = True
  868. # event.Skip()
  869. def OnDragging(self, event):
  870. """
  871. Mouse dragging with left button down
  872. """
  873. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  874. current = event.GetPositionTuple()[:]
  875. previous = self.mouse['begin']
  876. move = (current[0] - previous[0],
  877. current[1] - previous[1])
  878. digitToolbar = self.parent.toolbars['vdigit']
  879. # dragging or drawing box with left button
  880. if self.mouse['use'] == 'pan':
  881. self.DragMap(move)
  882. # dragging decoration overlay item
  883. elif (self.mouse['use'] == 'pointer' and
  884. not digitToolbar and
  885. self.dragid != None):
  886. self.DragItem(self.dragid, event)
  887. # dragging anything else - rubber band box or line
  888. else:
  889. if (self.mouse['use'] == 'pointer' and
  890. not digitToolbar): return
  891. self.mouse['end'] = event.GetPositionTuple()[:]
  892. digitClass = self.parent.digit
  893. if (event.LeftIsDown() and
  894. not (digitToolbar and
  895. digitToolbar.GetAction() in ("moveLine",) and
  896. digitClass.driver.GetSelected() > 0)):
  897. # draw box only when left mouse button is pressed
  898. self.MouseDraw(pdc=self.pdcTmp)
  899. # event.Skip()
  900. def OnLeftDownVDigitAddLine(self, event):
  901. """
  902. Left mouse button down - vector digitizer add new line
  903. action
  904. """
  905. digitToolbar = self.parent.toolbars['vdigit']
  906. digitClass = self.parent.digit
  907. try:
  908. mapLayer = digitToolbar.GetLayer().GetName()
  909. except:
  910. return
  911. if digitToolbar.GetAction('type') in ["point", "centroid"]:
  912. # add new point
  913. if digitToolbar.GetAction('type') == 'point':
  914. point = True
  915. else:
  916. point = False
  917. east, north = self.Pixel2Cell(self.mouse['begin'])
  918. fid = digitClass.AddPoint(mapLayer, point, east, north)
  919. if fid < 0:
  920. return
  921. self.UpdateMap(render=False) # redraw map
  922. # add new record into atribute table
  923. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') is True:
  924. # select attributes based on layer and category
  925. cats = { fid : {
  926. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  927. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  928. }}
  929. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  930. self.mouse['end'][1] + self.dialogOffset))
  931. addRecordDlg = dbm_dialogs.DisplayAttributesDialog(parent=self, map=mapLayer,
  932. cats=cats,
  933. pos=posWindow,
  934. action="add")
  935. if addRecordDlg.mapDBInfo and \
  936. addRecordDlg.ShowModal() == wx.ID_OK:
  937. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  938. for sql in addRecordDlg.GetSQLString():
  939. sqlfile.file.write(sql + ";\n")
  940. sqlfile.file.flush()
  941. gcmd.RunCommand('db.execute',
  942. parent = self,
  943. quiet = True,
  944. input = sqlfile.name)
  945. elif digitToolbar.GetAction('type') in ["line", "boundary"]:
  946. # add new point to the line
  947. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  948. self.DrawLines(pdc=self.pdcTmp)
  949. def OnLeftDownVDigitEditLine(self, event):
  950. """
  951. Left mouse button down - vector digitizer edit linear feature
  952. - add new vertex.
  953. """
  954. digitToolbar = self.parent.toolbars['vdigit']
  955. digitClass = self.parent.digit
  956. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  957. self.vdigitMove['id'].append(wx.NewId())
  958. self.DrawLines(pdc=self.pdcTmp)
  959. def OnLeftDownVDigitMoveLine(self, event):
  960. """
  961. Left mouse button down - vector digitizer move feature/vertex,
  962. edit linear feature
  963. """
  964. digitToolbar = self.parent.toolbars['vdigit']
  965. digitClass = self.parent.digit
  966. self.vdigitMove = {}
  967. # geographic coordinates of initial position (left-down)
  968. self.vdigitMove['begin'] = None
  969. # list of ids to modify
  970. self.vdigitMove['id'] = []
  971. # ids geographic coordinates
  972. self.vdigitMove['coord'] = {}
  973. if digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  974. # set pen
  975. pcolor = UserSettings.Get(group='vdigit', key="symbol",
  976. subkey=["highlight", "color"])
  977. self.pen = self.polypen = wx.Pen(colour=pcolor,
  978. width=2, style=wx.SHORT_DASH)
  979. self.pdcTmp.SetPen(self.polypen)
  980. def OnLeftDownVDigitDisplayCA(self, event):
  981. """
  982. Left mouse button down - vector digitizer display categories
  983. or attributes action
  984. """
  985. digitToolbar = self.parent.toolbars['vdigit']
  986. digitClass = self.parent.digit
  987. try:
  988. mapLayer = digitToolbar.GetLayer().GetName()
  989. except:
  990. return
  991. coords = self.Pixel2Cell(self.mouse['begin'])
  992. # unselect
  993. digitClass.driver.SetSelected([])
  994. # select feature by point
  995. cats = {}
  996. if digitClass.driver.SelectLineByPoint(coords,
  997. digitClass.GetSelectType()) is None:
  998. return
  999. if UserSettings.Get(group='vdigit', key='checkForDupl',
  1000. subkey='enabled'):
  1001. lines = digitClass.driver.GetSelected()
  1002. else:
  1003. lines = (digitClass.driver.GetSelected()[0],) # only first found
  1004. for line in lines:
  1005. cats[line] = digitClass.GetLineCats(line)
  1006. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1007. self.mouse['end'][1] + self.dialogOffset))
  1008. if digitToolbar.GetAction() == "displayAttrs":
  1009. # select attributes based on coordinates (all layers)
  1010. if self.parent.dialogs['attributes'] is None:
  1011. self.parent.dialogs['attributes'] = \
  1012. dbm_dialogs.DisplayAttributesDialog(parent=self, map=mapLayer,
  1013. cats=cats,
  1014. action="update")
  1015. else:
  1016. # upgrade dialog
  1017. self.parent.dialogs['attributes'].UpdateDialog(cats=cats)
  1018. if self.parent.dialogs['attributes']:
  1019. if len(cats.keys()) > 0:
  1020. # highlight feature & re-draw map
  1021. if not self.parent.dialogs['attributes'].IsShown():
  1022. self.parent.dialogs['attributes'].Show()
  1023. else:
  1024. if self.parent.dialogs['attributes'] and \
  1025. self.parent.dialogs['attributes'].IsShown():
  1026. self.parent.dialogs['attributes'].Hide()
  1027. else: # displayCats
  1028. if self.parent.dialogs['category'] is None:
  1029. # open new dialog
  1030. dlg = VDigitCategoryDialog(parent=self,
  1031. map=mapLayer,
  1032. cats=cats,
  1033. pos=posWindow,
  1034. title=_("Update categories"))
  1035. self.parent.dialogs['category'] = dlg
  1036. else:
  1037. # update currently open dialog
  1038. self.parent.dialogs['category'].UpdateDialog(cats=cats)
  1039. if self.parent.dialogs['category']:
  1040. if len(cats.keys()) > 0:
  1041. # highlight feature & re-draw map
  1042. if not self.parent.dialogs['category'].IsShown():
  1043. self.parent.dialogs['category'].Show()
  1044. else:
  1045. if self.parent.dialogs['category'].IsShown():
  1046. self.parent.dialogs['category'].Hide()
  1047. self.UpdateMap(render=False)
  1048. def OnLeftDownVDigitCopyCA(self, event):
  1049. """
  1050. Left mouse button down - vector digitizer copy categories
  1051. or attributes action
  1052. """
  1053. digitToolbar = self.parent.toolbars['vdigit']
  1054. digitClass = self.parent.digit
  1055. if not hasattr(self, "copyCatsList"):
  1056. self.copyCatsList = []
  1057. else:
  1058. self.copyCatsIds = []
  1059. self.mouse['box'] = 'box'
  1060. def OnLeftDownVDigitCopyLine(self, event):
  1061. """
  1062. Left mouse button down - vector digitizer copy lines action
  1063. """
  1064. digitToolbar = self.parent.toolbars['vdigit']
  1065. digitClass = self.parent.digit
  1066. if not hasattr(self, "copyIds"):
  1067. self.copyIds = []
  1068. self.layerTmp = None
  1069. def OnLeftDownVDigitBulkLine(self, event):
  1070. """
  1071. Left mouse button down - vector digitizer label 3d vector
  1072. lines
  1073. """
  1074. digitToolbar = self.parent.toolbars['vdigit']
  1075. digitClass = self.parent.digit
  1076. if len(self.polycoords) > 1: # start new line
  1077. self.polycoords = []
  1078. self.ClearLines(pdc=self.pdcTmp)
  1079. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1080. if len(self.polycoords) == 1:
  1081. begin = self.Pixel2Cell(self.polycoords[-1])
  1082. end = self.Pixel2Cell(self.mouse['end'])
  1083. else:
  1084. end = self.Pixel2Cell(self.polycoords[-1])
  1085. begin = self.Pixel2Cell(self.mouse['begin'])
  1086. self.DrawLines(self.pdcTmp, begin, end)
  1087. def OnLeftDown(self, event):
  1088. """
  1089. Left mouse button pressed
  1090. """
  1091. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  1092. self.mouse["use"])
  1093. self.mouse['begin'] = event.GetPositionTuple()[:]
  1094. if self.mouse["use"] in ["measure", "profile"]:
  1095. # measure or profile
  1096. if len(self.polycoords) == 0:
  1097. self.mouse['end'] = self.mouse['begin']
  1098. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  1099. self.ClearLines(pdc=self.pdcTmp)
  1100. else:
  1101. self.mouse['begin'] = self.mouse['end']
  1102. elif self.mouse['use'] == 'zoom':
  1103. pass
  1104. #
  1105. # vector digizer
  1106. #
  1107. elif self.mouse["use"] == "pointer" and \
  1108. self.parent.toolbars['vdigit']:
  1109. digitToolbar = self.parent.toolbars['vdigit']
  1110. digitClass = self.parent.digit
  1111. try:
  1112. mapLayer = digitToolbar.GetLayer().GetName()
  1113. except:
  1114. wx.MessageBox(parent=self,
  1115. message=_("No vector map selected for editing."),
  1116. caption=_("Vector digitizer"),
  1117. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1118. event.Skip()
  1119. return
  1120. if digitToolbar.GetAction() not in ("moveVertex",
  1121. "addVertex",
  1122. "removeVertex",
  1123. "editLine"):
  1124. # set pen
  1125. self.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  1126. self.polypen = wx.Pen(colour='dark green', width=2, style=wx.SOLID)
  1127. if digitToolbar.GetAction() in ("addVertex",
  1128. "removeVertex",
  1129. "splitLines"):
  1130. # unselect
  1131. digitClass.driver.SetSelected([])
  1132. if digitToolbar.GetAction() == "addLine":
  1133. self.OnLeftDownVDigitAddLine(event)
  1134. elif digitToolbar.GetAction() == "editLine" and \
  1135. hasattr(self, "vdigitMove"):
  1136. self.OnLeftDownVDigitEditLine(event)
  1137. elif digitToolbar.GetAction() in ("moveLine",
  1138. "moveVertex",
  1139. "editLine") and \
  1140. not hasattr(self, "vdigitMove"):
  1141. self.OnLeftDownVDigitMoveLine(event)
  1142. elif digitToolbar.GetAction() in ("displayAttrs"
  1143. "displayCats"):
  1144. self.OnLeftDownVDigitDisplayCA(event)
  1145. elif digitToolbar.GetAction() in ("copyCats",
  1146. "copyAttrs"):
  1147. self.OnLeftDownVDigitCopyCA(event)
  1148. elif digitToolbar.GetAction() == "copyLine":
  1149. self.OnLeftDownVDigitCopyLine(event)
  1150. elif digitToolbar.GetAction() == "zbulkLine":
  1151. self.OnLeftDownVDigitBulkLine(event)
  1152. elif self.mouse['use'] == 'pointer':
  1153. # get decoration or text id
  1154. self.idlist = []
  1155. self.dragid = ''
  1156. self.lastpos = self.mouse['begin']
  1157. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  1158. self.hitradius)
  1159. if 99 in idlist:
  1160. idlist.remove(99)
  1161. if idlist != []:
  1162. self.dragid = idlist[0] #drag whatever is on top
  1163. else:
  1164. pass
  1165. event.Skip()
  1166. def OnLeftUpVDigitVarious(self, event):
  1167. """
  1168. Left mouse button up - vector digitizer various actions
  1169. """
  1170. digitToolbar = self.parent.toolbars['vdigit']
  1171. digitClass = self.parent.digit
  1172. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1173. pos2 = self.Pixel2Cell(self.mouse['end'])
  1174. nselected = 0
  1175. # -> delete line || move line || move vertex
  1176. if digitToolbar.GetAction() in ("moveVertex",
  1177. "editLine"):
  1178. if len(digitClass.driver.GetSelected()) == 0:
  1179. nselected = digitClass.driver.SelectLineByPoint(pos1, type=VDigit_Lines_Type)
  1180. if digitToolbar.GetAction() == "editLine":
  1181. try:
  1182. selVertex = digitClass.driver.GetSelectedVertex(pos1)[0]
  1183. except IndexError:
  1184. selVertex = None
  1185. if selVertex:
  1186. # self.UpdateMap(render=False)
  1187. ids = digitClass.driver.GetSelected(grassId=False)
  1188. # move this line to tmp layer
  1189. self.polycoords = []
  1190. for id in ids:
  1191. if id % 2: # register only vertices
  1192. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  1193. self.polycoords.append((e, n))
  1194. digitClass.driver.DrawSelected(False)
  1195. if selVertex < ids[-1] / 2:
  1196. # choose first or last node of line
  1197. self.vdigitMove['id'].reverse()
  1198. self.polycoords.reverse()
  1199. else:
  1200. # unselect
  1201. digitClass.driver.SetSelected([])
  1202. del self.vdigitMove
  1203. self.UpdateMap(render=False)
  1204. elif digitToolbar.GetAction() in ("copyCats",
  1205. "copyAttrs"):
  1206. if not hasattr(self, "copyCatsIds"):
  1207. # 'from' -> select by point
  1208. nselected = digitClass.driver.SelectLineByPoint(pos1, digitClass.GetSelectType())
  1209. if nselected:
  1210. self.copyCatsList = digitClass.driver.GetSelected()
  1211. else:
  1212. # -> 'to' -> select by bbox
  1213. digitClass.driver.SetSelected([])
  1214. # return number of selected features (by box/point)
  1215. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1216. digitClass.GetSelectType())
  1217. if nselected == 0:
  1218. if digitClass.driver.SelectLineByPoint(pos1,
  1219. digitClass.GetSelectType()) is not None:
  1220. nselected = 1
  1221. if nselected > 0:
  1222. self.copyCatsIds = digitClass.driver.GetSelected()
  1223. elif digitToolbar.GetAction() == "queryLine":
  1224. selected = digitClass.SelectLinesByQuery(pos1, pos2)
  1225. nselected = len(selected)
  1226. if nselected > 0:
  1227. digitClass.driver.SetSelected(selected)
  1228. else:
  1229. # -> moveLine || deleteLine, etc. (select by point/box)
  1230. if digitToolbar.GetAction() == 'moveLine' and \
  1231. len(digitClass.driver.GetSelected()) > 0:
  1232. nselected = 0
  1233. else:
  1234. if digitToolbar.GetAction() == 'moveLine':
  1235. drawSeg = True
  1236. else:
  1237. drawSeg = False
  1238. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1239. digitClass.GetSelectType(),
  1240. drawSeg)
  1241. if nselected == 0:
  1242. if digitClass.driver.SelectLineByPoint(pos1,
  1243. digitClass.GetSelectType()) is not None:
  1244. nselected = 1
  1245. if nselected > 0:
  1246. if digitToolbar.GetAction() in ("moveLine",
  1247. "moveVertex"):
  1248. # get pseudoDC id of objects which should be redrawn
  1249. if digitToolbar.GetAction() == "moveLine":
  1250. # -> move line
  1251. self.vdigitMove['id'] = digitClass.driver.GetSelected(grassId=False)
  1252. self.vdigitMove['coord'] = digitClass.driver.GetSelectedCoord()
  1253. else: # moveVertex
  1254. self.vdigitMove['id'] = digitClass.driver.GetSelectedVertex(pos1)
  1255. if len(self.vdigitMove['id']) == 0: # no vertex found
  1256. digitClass.driver.SetSelected([])
  1257. #
  1258. # check for duplicates
  1259. #
  1260. if UserSettings.Get(group='vdigit', key='checkForDupl', subkey='enabled') is True:
  1261. dupl = digitClass.driver.GetDuplicates()
  1262. self.UpdateMap(render=False)
  1263. if dupl:
  1264. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1265. self.mouse['end'][1] + self.dialogOffset))
  1266. dlg = VDigitDuplicatesDialog(parent=self, data=dupl, pos=posWindow)
  1267. if dlg.ShowModal() == wx.ID_OK:
  1268. digitClass.driver.UnSelect(dlg.GetUnSelected())
  1269. # update selected
  1270. self.UpdateMap(render=False)
  1271. if digitToolbar.GetAction() != "editLine":
  1272. # -> move line || move vertex
  1273. self.UpdateMap(render=False)
  1274. else: # no vector object found
  1275. if not (digitToolbar.GetAction() in ("moveLine",
  1276. "moveVertex") and \
  1277. len(self.vdigitMove['id']) > 0):
  1278. # avoid left-click when features are already selected
  1279. self.UpdateMap(render=False, renderVector=False)
  1280. def OnLeftUpVDigitModifyLine(self, event):
  1281. """
  1282. Left mouse button up - vector digitizer split line, add/remove
  1283. vertex action
  1284. """
  1285. digitToolbar = self.parent.toolbars['vdigit']
  1286. digitClass = self.parent.digit
  1287. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1288. pointOnLine = digitClass.driver.SelectLineByPoint(pos1,
  1289. type=VDigit_Lines_Type)
  1290. if not pointOnLine:
  1291. return
  1292. if digitToolbar.GetAction() in ["splitLine", "addVertex"]:
  1293. self.UpdateMap(render=False) # highlight object
  1294. self.DrawCross(pdc=self.pdcTmp, coords=self.Cell2Pixel(pointOnLine),
  1295. size=5)
  1296. else: # removeVertex
  1297. # get only id of vertex
  1298. try:
  1299. id = digitClass.driver.GetSelectedVertex(pos1)[0]
  1300. except IndexError:
  1301. id = None
  1302. if id:
  1303. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  1304. self.pdcVector.RemoveId(id)
  1305. self.UpdateMap(render=False) # highlight object
  1306. self.DrawCross(pdc=self.pdcTmp, coords=(x, y),
  1307. size=5)
  1308. else:
  1309. # unselect
  1310. digitClass.driver.SetSelected([])
  1311. self.UpdateMap(render=False)
  1312. def OnLeftUpVDigitCopyLine(self, event):
  1313. """
  1314. Left mouse button up - vector digitizer copy feature action
  1315. """
  1316. digitToolbar = self.parent.toolbars['vdigit']
  1317. digitClass = self.parent.digit
  1318. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1319. pos2 = self.Pixel2Cell(self.mouse['end'])
  1320. if UserSettings.Get(group='vdigit', key='bgmap',
  1321. subkey='value', internal=True) == '':
  1322. # no background map -> copy from current vector map layer
  1323. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1324. digitClass.GetSelectType())
  1325. if nselected > 0:
  1326. # highlight selected features
  1327. self.UpdateMap(render=False)
  1328. else:
  1329. self.UpdateMap(render=False, renderVector=False)
  1330. else:
  1331. # copy features from background map
  1332. self.copyIds += digitClass.SelectLinesFromBackgroundMap(pos1, pos2)
  1333. if len(self.copyIds) > 0:
  1334. color = UserSettings.Get(group='vdigit', key='symbol',
  1335. subkey=['highlight', 'color'])
  1336. colorStr = str(color[0]) + ":" + \
  1337. str(color[1]) + ":" + \
  1338. str(color[2])
  1339. dVectTmp = ['d.vect',
  1340. 'map=%s' % UserSettings.Get(group='vdigit', key='bgmap',
  1341. subkey='value', internal=True),
  1342. 'cats=%s' % utils.ListOfCatsToRange(self.copyIds),
  1343. '-i',
  1344. 'color=%s' % colorStr,
  1345. 'fcolor=%s' % colorStr,
  1346. 'type=point,line,boundary,centroid',
  1347. 'width=2']
  1348. if not self.layerTmp:
  1349. self.layerTmp = self.Map.AddLayer(type='vector',
  1350. name=globalvar.QUERYLAYER,
  1351. command=dVectTmp)
  1352. else:
  1353. self.layerTmp.SetCmd(dVectTmp)
  1354. self.UpdateMap(render=True, renderVector=False)
  1355. else:
  1356. self.UpdateMap(render=False, renderVector=False)
  1357. self.redrawAll = None
  1358. def OnLeftUpVDigitBulkLine(self, event):
  1359. """
  1360. Left mouse button up - vector digitizer z-bulk line action
  1361. """
  1362. digitToolbar = self.parent.toolbars['vdigit']
  1363. digitClass = self.parent.digit
  1364. # select lines to be labeled
  1365. pos1 = self.polycoords[0]
  1366. pos2 = self.polycoords[1]
  1367. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1368. digitClass.GetSelectType())
  1369. if nselected > 0:
  1370. # highlight selected features
  1371. self.UpdateMap(render=False)
  1372. self.DrawLines(pdc=self.pdcTmp) # redraw temp line
  1373. else:
  1374. self.UpdateMap(render=False, renderVector=False)
  1375. def OnLeftUpVDigitConnectLine(self, event):
  1376. """
  1377. Left mouse button up - vector digitizer connect line action
  1378. """
  1379. digitToolbar = self.parent.toolbars['vdigit']
  1380. digitClass = self.parent.digit
  1381. if len(digitClass.driver.GetSelected()) > 0:
  1382. self.UpdateMap(render=False)
  1383. def OnLeftUp(self, event):
  1384. """
  1385. Left mouse button released
  1386. """
  1387. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  1388. self.mouse["use"])
  1389. self.mouse['end'] = event.GetPositionTuple()[:]
  1390. if self.mouse['use'] in ["zoom", "pan"]:
  1391. # set region in zoom or pan
  1392. begin = self.mouse['begin']
  1393. end = self.mouse['end']
  1394. if self.mouse['use'] == 'zoom':
  1395. # set region for click (zero-width box)
  1396. if begin[0] - end[0] == 0 or \
  1397. begin[1] - end[1] == 0:
  1398. # zoom 1/2 of the screen (TODO: settings)
  1399. begin = (end[0] - self.Map.width / 4,
  1400. end[1] - self.Map.height / 4)
  1401. end = (end[0] + self.Map.width / 4,
  1402. end[1] + self.Map.height / 4)
  1403. self.Zoom(begin, end, self.zoomtype)
  1404. # redraw map
  1405. self.UpdateMap(render=True)
  1406. # update statusbar
  1407. self.parent.StatusbarUpdate()
  1408. elif self.mouse["use"] == "query":
  1409. # querying
  1410. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  1411. elif self.mouse["use"] == "queryVector":
  1412. # editable mode for vector map layers
  1413. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  1414. # clear temp canvas
  1415. self.UpdateMap(render=False, renderVector=False)
  1416. elif self.mouse["use"] in ["measure", "profile"]:
  1417. # measure or profile
  1418. if self.mouse["use"] == "measure":
  1419. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  1420. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1421. self.ClearLines(pdc=self.pdcTmp)
  1422. self.DrawLines(pdc=self.pdcTmp)
  1423. elif self.mouse["use"] == "pointer" and \
  1424. self.parent.GetLayerManager().georectifying:
  1425. # -> georectifying
  1426. coord = self.Pixel2Cell(self.mouse['end'])
  1427. if self.parent.toolbars['georect']:
  1428. coordtype = 'gcpcoord'
  1429. else:
  1430. coordtype = 'mapcoord'
  1431. self.parent.GetLayerManager().georectifying.SetGCPData(coordtype, coord, self)
  1432. self.UpdateMap(render=False, renderVector=False)
  1433. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  1434. # digitization tool active
  1435. digitToolbar = self.parent.toolbars['vdigit']
  1436. digitClass = self.parent.digit
  1437. if hasattr(self, "vdigitMove"):
  1438. if len(digitClass.driver.GetSelected()) == 0:
  1439. self.vdigitMove['begin'] = self.Pixel2Cell(self.mouse['begin']) # left down
  1440. # eliminate initial mouse moving efect
  1441. self.mouse['begin'] = self.mouse['end']
  1442. if digitToolbar.GetAction() in ("deleteLine",
  1443. "moveLine",
  1444. "moveVertex",
  1445. "copyCats",
  1446. "copyAttrs",
  1447. "editLine",
  1448. "flipLine",
  1449. "mergeLine",
  1450. "snapLine",
  1451. "queryLine",
  1452. "breakLine",
  1453. "typeConv",
  1454. "connectLine"):
  1455. self.OnLeftUpVDigitVarious(event)
  1456. elif digitToolbar.GetAction() in ("splitLine",
  1457. "addVertex",
  1458. "removeVertex"):
  1459. self.OnLeftUpVDigitModifyLine(event)
  1460. elif digitToolbar.GetAction() == "copyLine":
  1461. self.OnLeftUpVDigitCopyLine(event)
  1462. elif digitToolbar.GetAction() == "zbulkLine" and \
  1463. len(self.polycoords) == 2:
  1464. self.OnLeftUpVDigitBulkLine(event)
  1465. elif digitToolbar.GetAction() == "connectLine":
  1466. self.OnLeftUpConnectLine(event)
  1467. if len(digitClass.driver.GetSelected()) > 0:
  1468. self.redrawAll = None
  1469. elif (self.mouse['use'] == 'pointer' and
  1470. self.dragid >= 0):
  1471. # end drag of overlay decoration
  1472. if self.dragid < 99 and self.overlays.has_key(self.dragid):
  1473. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1474. elif self.dragid > 100 and self.textdict.has_key(self.dragid):
  1475. self.textdict[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1476. else:
  1477. pass
  1478. self.dragid = None
  1479. self.currtxtid = None
  1480. def OnButtonDClick(self, event):
  1481. """
  1482. Mouse button double click
  1483. """
  1484. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1485. self.mouse["use"])
  1486. if self.mouse["use"] == "measure":
  1487. # measure
  1488. self.ClearLines(pdc=self.pdcTmp)
  1489. self.polycoords = []
  1490. self.mouse['use'] = 'pointer'
  1491. self.mouse['box'] = 'point'
  1492. self.mouse['end'] = [0, 0]
  1493. self.Refresh()
  1494. self.SetCursor(self.parent.cursors["default"])
  1495. elif self.mouse["use"] == "profile":
  1496. pass
  1497. elif self.mouse['use'] == 'pointer' and \
  1498. self.parent.toolbars['vdigit']:
  1499. # vector digitizer
  1500. pass
  1501. else:
  1502. # select overlay decoration options dialog
  1503. clickposition = event.GetPositionTuple()[:]
  1504. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1505. if idlist == []:
  1506. return
  1507. self.dragid = idlist[0]
  1508. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1509. if self.dragid > 100:
  1510. self.currtxtid = self.dragid
  1511. self.parent.OnAddText(None)
  1512. elif self.dragid == 0:
  1513. self.parent.OnAddBarscale(None)
  1514. elif self.dragid == 1:
  1515. self.parent.OnAddLegend(None)
  1516. def OnRightDown(self, event):
  1517. """
  1518. Right mouse button pressed
  1519. """
  1520. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1521. self.mouse["use"])
  1522. digitToolbar = self.parent.toolbars['vdigit']
  1523. if digitToolbar:
  1524. digitClass = self.parent.digit
  1525. # digitization tool (confirm action)
  1526. if digitToolbar.GetAction() in ("moveLine",
  1527. "moveVertex") and \
  1528. hasattr(self, "vdigitMove"):
  1529. pFrom = self.vdigitMove['begin']
  1530. pTo = self.Pixel2Cell(event.GetPositionTuple())
  1531. move = (pTo[0] - pFrom[0],
  1532. pTo[1] - pFrom[1])
  1533. if digitToolbar.GetAction() == "moveLine":
  1534. # move line
  1535. if digitClass.MoveSelectedLines(move) < 0:
  1536. return
  1537. elif digitToolbar.GetAction() == "moveVertex":
  1538. # move vertex
  1539. if digitClass.MoveSelectedVertex(pFrom, move) < 0:
  1540. return
  1541. del self.vdigitMove
  1542. event.Skip()
  1543. def OnRightUp(self, event):
  1544. """
  1545. Right mouse button released
  1546. """
  1547. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1548. self.mouse["use"])
  1549. digitToolbar = self.parent.toolbars['vdigit']
  1550. if digitToolbar:
  1551. digitClass = self.parent.digit
  1552. # digitization tool (confirm action)
  1553. if digitToolbar.GetAction() == "addLine" and \
  1554. digitToolbar.GetAction('type') in ["line", "boundary"]:
  1555. # -> add new line / boundary
  1556. try:
  1557. map = digitToolbar.GetLayer().GetName()
  1558. except:
  1559. map = None
  1560. wx.MessageBox(parent=self,
  1561. message=_("No vector map selected for editing."),
  1562. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1563. if map:
  1564. # mapcoords = []
  1565. # xy -> EN
  1566. # for coord in self.polycoords:
  1567. # mapcoords.append(self.Pixel2Cell(coord))
  1568. if digitToolbar.GetAction('type') == 'line':
  1569. line = True
  1570. else:
  1571. line = False
  1572. if len(self.polycoords) < 2: # ignore 'one-point' lines
  1573. return
  1574. fid = digitClass.AddLine(map, line, self.polycoords)
  1575. if fid < 0:
  1576. return
  1577. position = self.Cell2Pixel(self.polycoords[-1])
  1578. self.polycoords = []
  1579. self.UpdateMap(render=False)
  1580. self.redrawAll = True
  1581. # add new record into atribute table
  1582. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') and \
  1583. (line is True or \
  1584. (not line and fid > 0)):
  1585. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  1586. position[1] + self.dialogOffset))
  1587. # select attributes based on layer and category
  1588. cats = { fid : {
  1589. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  1590. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  1591. }}
  1592. addRecordDlg = dbm_dialogs.DisplayAttributesDialog(parent=self, map=map,
  1593. cats=cats,
  1594. pos=posWindow,
  1595. action="add")
  1596. if addRecordDlg.mapDBInfo and \
  1597. addRecordDlg.ShowModal() == wx.ID_OK:
  1598. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1599. for sql in addRecordDlg.GetSQLString():
  1600. sqlfile.file.write(sql + ";\n")
  1601. sqlfile.file.flush()
  1602. gcmd.RunCommand('db.execute',
  1603. parent = True,
  1604. quiet = True,
  1605. input = sqlfile.name)
  1606. elif digitToolbar.GetAction() == "deleteLine":
  1607. # -> delete selected vector features
  1608. if digitClass.DeleteSelectedLines() < 0:
  1609. return
  1610. elif digitToolbar.GetAction() == "splitLine":
  1611. # split line
  1612. if digitClass.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1613. return
  1614. elif digitToolbar.GetAction() == "addVertex":
  1615. # add vertex
  1616. if digitClass.AddVertex(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1617. return
  1618. elif digitToolbar.GetAction() == "removeVertex":
  1619. # remove vertex
  1620. if digitClass.RemoveVertex(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1621. return
  1622. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1623. try:
  1624. if digitToolbar.GetAction() == 'copyCats':
  1625. if digitClass.CopyCats(self.copyCatsList,
  1626. self.copyCatsIds, copyAttrb=False) < 0:
  1627. return
  1628. else:
  1629. if digitClass.CopyCats(self.copyCatsList,
  1630. self.copyCatsIds, copyAttrb=True) < 0:
  1631. return
  1632. del self.copyCatsList
  1633. del self.copyCatsIds
  1634. except AttributeError:
  1635. pass
  1636. elif digitToolbar.GetAction() == "editLine" and \
  1637. hasattr(self, "vdigitMove"):
  1638. line = digitClass.driver.GetSelected()
  1639. if digitClass.EditLine(line, self.polycoords) < 0:
  1640. return
  1641. del self.vdigitMove
  1642. elif digitToolbar.GetAction() == "flipLine":
  1643. if digitClass.FlipLine() < 0:
  1644. return
  1645. elif digitToolbar.GetAction() == "mergeLine":
  1646. if digitClass.MergeLine() < 0:
  1647. return
  1648. elif digitToolbar.GetAction() == "breakLine":
  1649. if digitClass.BreakLine() < 0:
  1650. return
  1651. elif digitToolbar.GetAction() == "snapLine":
  1652. if digitClass.SnapLine() < 0:
  1653. return
  1654. elif digitToolbar.GetAction() == "connectLine":
  1655. if len(digitClass.driver.GetSelected()) > 1:
  1656. if digitClass.ConnectLine() < 0:
  1657. return
  1658. elif digitToolbar.GetAction() == "copyLine":
  1659. if digitClass.CopyLine(self.copyIds) < 0:
  1660. return
  1661. del self.copyIds
  1662. if self.layerTmp:
  1663. self.Map.DeleteLayer(self.layerTmp)
  1664. self.UpdateMap(render=True, renderVector=False)
  1665. del self.layerTmp
  1666. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1667. pos1 = self.polycoords[0]
  1668. pos2 = self.polycoords[1]
  1669. selected = digitClass.driver.GetSelected()
  1670. dlg = VDigitZBulkDialog(parent=self, title=_("Z bulk-labeling dialog"),
  1671. nselected=len(selected))
  1672. if dlg.ShowModal() == wx.ID_OK:
  1673. if digitClass.ZBulkLine(pos1, pos2, dlg.value.GetValue(),
  1674. dlg.step.GetValue()) < 0:
  1675. return
  1676. self.UpdateMap(render=False, renderVector=True)
  1677. elif digitToolbar.GetAction() == "typeConv":
  1678. # -> feature type conversion
  1679. # - point <-> centroid
  1680. # - line <-> boundary
  1681. if digitClass.TypeConvForSelectedLines() < 0:
  1682. return
  1683. if digitToolbar.GetAction() != "addLine":
  1684. # unselect and re-render
  1685. digitClass.driver.SetSelected([])
  1686. self.polycoords = []
  1687. self.UpdateMap(render=False)
  1688. self.redrawAll = True
  1689. event.Skip()
  1690. def OnMiddleDown(self, event):
  1691. """
  1692. Middle mouse button pressed
  1693. """
  1694. digitToolbar = self.parent.toolbars['vdigit']
  1695. # digitization tool
  1696. if self.mouse["use"] == "pointer" and digitToolbar:
  1697. digitClass = self.parent.digit
  1698. if (digitToolbar.GetAction() == "addLine" and \
  1699. digitToolbar.GetAction('type') in ["line", "boundary"]) or \
  1700. digitToolbar.GetAction() == "editLine":
  1701. # add line or boundary -> remove last point from the line
  1702. try:
  1703. removed = self.polycoords.pop()
  1704. Debug.msg(4, "BufferedWindow.OnMiddleDown(): polycoords_poped=%s" % \
  1705. [removed,])
  1706. self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
  1707. except:
  1708. pass
  1709. if digitToolbar.GetAction() == "editLine":
  1710. # remove last vertex & line
  1711. if len(self.vdigitMove['id']) > 1:
  1712. self.vdigitMove['id'].pop()
  1713. self.UpdateMap(render=False, renderVector=False)
  1714. elif digitToolbar.GetAction() in ["deleteLine", "moveLine", "splitLine",
  1715. "addVertex", "removeVertex", "moveVertex",
  1716. "copyCats", "flipLine", "mergeLine",
  1717. "snapLine", "connectLine", "copyLine",
  1718. "queryLine", "breakLine", "typeConv"]:
  1719. # varios tools -> unselected selected features
  1720. digitClass.driver.SetSelected([])
  1721. if digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  1722. hasattr(self, "vdigitMove"):
  1723. del self.vdigitMove
  1724. elif digitToolbar.GetAction() == "copyCats":
  1725. try:
  1726. del self.copyCatsList
  1727. del self.copyCatsIds
  1728. except AttributeError:
  1729. pass
  1730. elif digitToolbar.GetAction() == "copyLine":
  1731. del self.copyIds
  1732. if self.layerTmp:
  1733. self.Map.DeleteLayer(self.layerTmp)
  1734. self.UpdateMap(render=True, renderVector=False)
  1735. del self.layerTmp
  1736. self.polycoords = []
  1737. self.UpdateMap(render=False) # render vector
  1738. elif digitToolbar.GetAction() == "zbulkLine":
  1739. # reset polyline
  1740. self.polycoords = []
  1741. digitClass.driver.SetSelected([])
  1742. self.UpdateMap(render=False)
  1743. self.redrawAll = True
  1744. def OnMouseMoving(self, event):
  1745. """
  1746. Motion event and no mouse buttons were pressed
  1747. """
  1748. digitToolbar = self.parent.toolbars['vdigit']
  1749. if self.mouse["use"] == "pointer" and digitToolbar:
  1750. digitClass = self.parent.digit
  1751. self.mouse['end'] = event.GetPositionTuple()[:]
  1752. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  1753. (self.mouse['end'][0], self.mouse['end'][1]))
  1754. if digitToolbar.GetAction() == "addLine" and digitToolbar.GetAction('type') in ["line", "boundary"]:
  1755. if len(self.polycoords) > 0:
  1756. self.MouseDraw(pdc=self.pdcTmp, begin=self.Cell2Pixel(self.polycoords[-1]))
  1757. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] \
  1758. and hasattr(self, "vdigitMove"):
  1759. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  1760. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  1761. if len(self.vdigitMove['id']) > 0:
  1762. # draw lines on new position
  1763. if digitToolbar.GetAction() == "moveLine":
  1764. # move line
  1765. for id in self.vdigitMove['id']:
  1766. self.pdcTmp.TranslateId(id, dx, dy)
  1767. elif digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1768. # move vertex ->
  1769. # (vertex, left vertex, left line,
  1770. # right vertex, right line)
  1771. # do not draw static lines
  1772. if digitToolbar.GetAction() == "moveVertex":
  1773. self.polycoords = []
  1774. ### self.pdcTmp.TranslateId(self.vdigitMove['id'][0], dx, dy)
  1775. self.pdcTmp.RemoveId(self.vdigitMove['id'][0])
  1776. if self.vdigitMove['id'][1] > 0: # previous vertex
  1777. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][1])[0:2])
  1778. self.pdcTmp.RemoveId(self.vdigitMove['id'][1]+1)
  1779. self.polycoords.append((x, y))
  1780. ### x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][0])[0:2])
  1781. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1782. if self.vdigitMove['id'][2] > 0: # next vertex
  1783. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][2])[0:2])
  1784. self.pdcTmp.RemoveId(self.vdigitMove['id'][2]-1)
  1785. self.polycoords.append((x, y))
  1786. self.ClearLines(pdc=self.pdcTmp)
  1787. self.DrawLines(pdc=self.pdcTmp)
  1788. else: # edit line
  1789. try:
  1790. if self.vdigitMove['id'][-1] > 0: # previous vertex
  1791. self.MouseDraw(pdc=self.pdcTmp,
  1792. begin=self.Cell2Pixel(self.polycoords[-1]))
  1793. except: # no line
  1794. self.vdigitMove['id'] = []
  1795. self.polycoords = []
  1796. self.Refresh() # TODO: use RefreshRect()
  1797. self.mouse['begin'] = self.mouse['end']
  1798. elif digitToolbar.GetAction() == "zbulkLine":
  1799. if len(self.polycoords) == 1:
  1800. # draw mouse moving
  1801. self.MouseDraw(self.pdcTmp)
  1802. event.Skip()
  1803. def ClearLines(self, pdc=None):
  1804. """
  1805. Clears temporary drawn lines from PseudoDC
  1806. """
  1807. if not pdc:
  1808. pdc=self.pdcTmp
  1809. try:
  1810. pdc.ClearId(self.lineid)
  1811. pdc.RemoveId(self.lineid)
  1812. except:
  1813. pass
  1814. try:
  1815. pdc.ClearId(self.plineid)
  1816. pdc.RemoveId(self.plineid)
  1817. except:
  1818. pass
  1819. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1820. (self.lineid, self.plineid))
  1821. ### self.Refresh()
  1822. return True
  1823. def Pixel2Cell(self, (x, y)):
  1824. """
  1825. Convert image coordinates to real word coordinates
  1826. Input : int x, int y
  1827. Output: float x, float y
  1828. """
  1829. try:
  1830. x = int(x)
  1831. y = int(y)
  1832. except:
  1833. return None
  1834. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1835. res = self.Map.region["ewres"]
  1836. else:
  1837. res = self.Map.region["nsres"]
  1838. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1839. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1840. east = w + x * res
  1841. north = n - y * res
  1842. # extent does not correspond with whole map canvas area...
  1843. # east = self.Map.region['w'] + x * self.Map.region["ewres"]
  1844. # north = self.Map.region['n'] - y * self.Map.region["nsres"]
  1845. return (east, north)
  1846. def Cell2Pixel(self, (east, north)):
  1847. """
  1848. Convert real word coordinates to image coordinates
  1849. """
  1850. try:
  1851. east = float(east)
  1852. north = float(north)
  1853. except:
  1854. return None
  1855. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1856. res = self.Map.region["ewres"]
  1857. else:
  1858. res = self.Map.region["nsres"]
  1859. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1860. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1861. # x = int((east - w) / res)
  1862. # y = int((n - north) / res)
  1863. x = (east - w) / res
  1864. y = (n - north) / res
  1865. return (x, y)
  1866. def Zoom(self, begin, end, zoomtype):
  1867. """
  1868. Calculates new region while (un)zoom/pan-ing
  1869. """
  1870. x1, y1 = begin
  1871. x2, y2 = end
  1872. newreg = {}
  1873. # threshold - too small squares do not make sense
  1874. # can only zoom to windows of > 5x5 screen pixels
  1875. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1876. if x1 > x2:
  1877. x1, x2 = x2, x1
  1878. if y1 > y2:
  1879. y1, y2 = y2, y1
  1880. # zoom in
  1881. if zoomtype > 0:
  1882. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1883. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1884. # zoom out
  1885. elif zoomtype < 0:
  1886. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1887. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1888. (self.Map.width - x2),
  1889. self.Map.height + 2 * \
  1890. (self.Map.height - y2)))
  1891. # pan
  1892. elif zoomtype == 0:
  1893. dx = x1 - x2
  1894. dy = y1 - y2
  1895. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1896. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1897. self.Map.height + dy))
  1898. # if new region has been calculated, set the values
  1899. if newreg != {}:
  1900. # LL locations
  1901. if self.parent.Map.projinfo['proj'] == 'll':
  1902. if newreg['n'] > 90.0:
  1903. newreg['n'] = 90.0
  1904. if newreg['s'] < -90.0:
  1905. newreg['s'] = -90.0
  1906. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1907. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1908. if hasattr(self, "vdigitMove"):
  1909. # xo = self.Cell2Pixel((self.Map.region['center_easting'], self.Map.region['center_northing']))
  1910. # xn = self.Cell2Pixel(ce, cn))
  1911. tmp = self.Pixel2Cell(self.mouse['end'])
  1912. # calculate new center point and display resolution
  1913. self.Map.region['center_easting'] = ce
  1914. self.Map.region['center_northing'] = cn
  1915. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  1916. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  1917. self.Map.AlignExtentFromDisplay()
  1918. if hasattr(self, "vdigitMove"):
  1919. tmp1 = self.mouse['end']
  1920. tmp2 = self.Cell2Pixel(self.vdigitMove['begin'])
  1921. dx = tmp1[0] - tmp2[0]
  1922. dy = tmp1[1] - tmp2[1]
  1923. self.vdigitMove['beginDiff'] = (dx, dy)
  1924. for id in self.vdigitMove['id']:
  1925. self.pdcTmp.RemoveId(id)
  1926. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1927. self.Map.region['e'], self.Map.region['w'])
  1928. if self.redrawAll is False:
  1929. self.redrawAll = True
  1930. def ZoomBack(self):
  1931. """
  1932. Zoom to previous extents in zoomhistory list
  1933. """
  1934. zoom = []
  1935. if len(self.zoomhistory) > 1:
  1936. self.zoomhistory.pop()
  1937. zoom = self.zoomhistory[len(self.zoomhistory)-1]
  1938. # (n, s, e, w)
  1939. if zoom:
  1940. # zoom to selected region
  1941. self.Map.region['center_easting'] = zoom[3] + \
  1942. (zoom[2] - zoom[3]) / 2
  1943. self.Map.region['center_northing'] = zoom[1] + \
  1944. (zoom[0] - zoom[1]) / 2
  1945. self.Map.region["ewres"] = (zoom[2] - zoom[3]) / self.Map.width
  1946. self.Map.region["nsres"] = (zoom[0] - zoom[1]) / self.Map.height
  1947. self.Map.AlignExtentFromDisplay()
  1948. # update map
  1949. self.UpdateMap()
  1950. # update statusbar
  1951. self.parent.StatusbarUpdate()
  1952. def ZoomHistory(self, n, s, e, w):
  1953. """
  1954. Manages a list of last 10 zoom extents
  1955. Return removed history item if exists
  1956. """
  1957. removed = None
  1958. self.zoomhistory.append((n,s,e,w))
  1959. if len(self.zoomhistory) > 10:
  1960. removed = self.zoomhistory.pop(0)
  1961. if removed:
  1962. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1963. (self.zoomhistory, removed))
  1964. else:
  1965. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1966. (self.zoomhistory))
  1967. return removed
  1968. def OnZoomToMap(self, event):
  1969. """
  1970. Set display extents to match selected raster (including NULLs)
  1971. or vector map.
  1972. """
  1973. self.ZoomToMap()
  1974. def OnZoomToRaster(self, event):
  1975. """
  1976. Set display extents to match selected raster map (ignore NULLs)
  1977. """
  1978. self.ZoomToMap(zoom=True)
  1979. def ZoomToMap(self, layer = None, zoom = False):
  1980. """
  1981. Set display extents to match selected raster
  1982. or vector map.
  1983. """
  1984. zoomreg = {}
  1985. if not layer:
  1986. layer = self.GetSelectedLayer(multi = True)
  1987. if not layer:
  1988. return
  1989. rast = []
  1990. vect = []
  1991. updated = False
  1992. for l in layer:
  1993. # only raster/vector layers are currently supported
  1994. if l.type == 'raster':
  1995. rast.append(l.name)
  1996. elif l.type == 'vector':
  1997. if self.parent.digit and l.name == self.parent.digit.map and \
  1998. self.parent.digit.type == 'vdigit':
  1999. w, s, b, e, n, t = self.parent.digit.driver.GetMapBoundingBox()
  2000. self.Map.GetRegion(n=n, s=s, w=w, e=e,
  2001. update=True)
  2002. updated = True
  2003. else:
  2004. vect.append(l.name)
  2005. if not updated:
  2006. self.Map.GetRegion(rast = rast,
  2007. vect = vect,
  2008. update = True)
  2009. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2010. self.Map.region['e'], self.Map.region['w'])
  2011. self.UpdateMap()
  2012. self.parent.StatusbarUpdate()
  2013. def ZoomToWind(self, event):
  2014. """
  2015. Set display geometry to match computational
  2016. region settings (set with g.region)
  2017. """
  2018. self.Map.region = self.Map.GetRegion()
  2019. ### self.Map.SetRegion(windres=True)
  2020. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2021. self.Map.region['e'], self.Map.region['w'])
  2022. self.UpdateMap()
  2023. self.parent.StatusbarUpdate()
  2024. def ZoomToDefault(self, event):
  2025. """
  2026. Set display geometry to match default region settings
  2027. """
  2028. self.Map.region = self.Map.GetRegion(default=True)
  2029. self.Map.AdjustRegion() # aling region extent to the display
  2030. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2031. self.Map.region['e'], self.Map.region['w'])
  2032. self.UpdateMap()
  2033. self.parent.StatusbarUpdate()
  2034. def DisplayToWind(self, event):
  2035. """
  2036. Set computational region (WIND file) to
  2037. match display extents
  2038. """
  2039. tmpreg = os.getenv("GRASS_REGION")
  2040. if tmpreg:
  2041. del os.environ["GRASS_REGION"]
  2042. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  2043. # for user to set explicitly with g.region
  2044. new = self.Map.AlignResolution()
  2045. gcmd.RunCommand('g.region',
  2046. parent = self,
  2047. overwrite = True,
  2048. n = new['n'],
  2049. s = new['s'],
  2050. e = new['e'],
  2051. w = new['w'],
  2052. rows = int(new['rows']),
  2053. cols = int(new['cols']))
  2054. if tmpreg:
  2055. os.environ["GRASS_REGION"] = tmpreg
  2056. def ZoomToSaved(self, event):
  2057. """
  2058. Set display geometry to match extents in
  2059. saved region file
  2060. """
  2061. zoomreg = {}
  2062. dlg = gdialogs.SavedRegion(self, wx.ID_ANY, _("Zoom to saved region extents"),
  2063. pos=wx.DefaultPosition, size=wx.DefaultSize,
  2064. style=wx.DEFAULT_DIALOG_STYLE,
  2065. loadsave='load')
  2066. if dlg.ShowModal() == wx.ID_CANCEL:
  2067. dlg.Destroy()
  2068. return
  2069. wind = dlg.wind
  2070. region = gcmd.RunCommand('g.region',
  2071. parent = self,
  2072. read = True,
  2073. flags = 'ugp',
  2074. region = wind)
  2075. if not region:
  2076. dlg.Destroy()
  2077. return
  2078. for line in region.splitlines():
  2079. key, val = line.split('=')
  2080. zoomreg[key.strip()] = float(val.strip())
  2081. self.Map.region['n'] = zoomreg['n']
  2082. self.Map.region['s'] = zoomreg['s']
  2083. self.Map.region['e'] = zoomreg['e']
  2084. self.Map.region['w'] = zoomreg['w']
  2085. self.ZoomHistory(self.Map.region['n'],
  2086. self.Map.region['s'],
  2087. self.Map.region['e'],
  2088. self.Map.region['w'])
  2089. self.UpdateMap()
  2090. dlg.Destroy()
  2091. def SaveDisplayRegion(self, event):
  2092. """
  2093. Save display extents to named region file.
  2094. """
  2095. dlg = gdialogs.SavedRegion(self, wx.ID_ANY, "Save display extents to region file",
  2096. pos=wx.DefaultPosition, size=wx.DefaultSize,
  2097. style=wx.DEFAULT_DIALOG_STYLE,
  2098. loadsave='save')
  2099. if dlg.ShowModal() == wx.ID_CANCEL:
  2100. dlg.Destroy()
  2101. return
  2102. wind = dlg.wind
  2103. # test to see if it already exists and ask permission to overwrite
  2104. windpath = os.path.join(self.Map.env["GISDBASE"], self.Map.env["LOCATION_NAME"],
  2105. self.Map.env["MAPSET"],"windows",wind)
  2106. if windpath and not os.path.exists(windpath):
  2107. self.SaveRegion(wind)
  2108. elif windpath and os.path.exists(windpath):
  2109. overwrite = wx.MessageBox(_("Region file <%s> already exists. "
  2110. "Do you want to overwrite it?") % (wind),
  2111. _("Warning"), wx.YES_NO)
  2112. if (overwrite == wx.YES):
  2113. self.SaveRegion(wind)
  2114. else:
  2115. pass
  2116. dlg.Destroy()
  2117. def SaveRegion(self, wind):
  2118. """
  2119. Save region settings
  2120. """
  2121. new = self.Map.AlignResolution()
  2122. cmdRegion = ["g.region",
  2123. "-u",
  2124. "n=%f" % new['n'],
  2125. "s=%f" % new['s'],
  2126. "e=%f" % new['e'],
  2127. "w=%f" % new['w'],
  2128. "rows=%d" % new['rows'],
  2129. "cols=%d" % new['cols'],
  2130. "save=%s" % wind,
  2131. "--o"]
  2132. tmpreg = os.getenv("GRASS_REGION")
  2133. if tmpreg:
  2134. del os.environ["GRASS_REGION"]
  2135. gcmd.RunCommand('g.region',
  2136. overwrite = True,
  2137. parent = self,
  2138. flags = 'u',
  2139. n = new['n'],
  2140. s = new['s'],
  2141. e = new['e'],
  2142. w = new['w'],
  2143. rows = int(new['rows']),
  2144. cols = int(new['cols']),
  2145. save = wind)
  2146. if tmpreg:
  2147. os.environ["GRASS_REGION"] = tmpreg
  2148. def Distance(self, beginpt, endpt, screen=True):
  2149. """Calculete distance
  2150. LL-locations not supported
  2151. @todo Use m.distance
  2152. @param beginpt first point
  2153. @param endpt second point
  2154. @param screen True for screen coordinates otherwise EN
  2155. """
  2156. x1, y1 = beginpt
  2157. x2, y2 = endpt
  2158. if screen:
  2159. dEast = (x2 - x1) * self.Map.region["ewres"]
  2160. dNorth = (y2 - y1) * self.Map.region["nsres"]
  2161. else:
  2162. dEast = (x2 - x1)
  2163. dNorth = (y2 - y1)
  2164. return (math.sqrt(math.pow((dEast),2) + math.pow((dNorth),2)), (dEast, dNorth))