mapdisp_window.py 111 KB

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