mapdisp_window.py 102 KB

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