mapdisp_window.py 110 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-2009 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. @author Michael Barton
  12. @author Jachym Cepicky
  13. @author Martin Landa <landa.martin gmail.com>
  14. """
  15. import os
  16. import time
  17. import math
  18. import sys
  19. import tempfile
  20. import traceback
  21. import wx
  22. import grass.script as grass
  23. import dbm
  24. import dbm_dialogs
  25. import gdialogs
  26. import gcmd
  27. import utils
  28. import globalvar
  29. import gselect
  30. from debug import Debug
  31. from preferences import globalSettings as UserSettings
  32. from units import ConvertValue as UnitsConvertValue
  33. from vdigit import GV_LINES as VDigit_Lines_Type
  34. from vdigit import VDigitCategoryDialog
  35. from vdigit import VDigitZBulkDialog
  36. from vdigit import VDigitDuplicatesDialog
  37. from vdigit import PseudoDC as VDigitPseudoDC
  38. class MapWindow(object):
  39. """!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. """!
  290. Draws map and overlay decorations
  291. """
  292. if drawid == None:
  293. if pdctype == 'image' and img:
  294. drawid = self.imagedict[img]
  295. elif pdctype == 'clear':
  296. drawid == None
  297. else:
  298. drawid = wx.NewId()
  299. if img and pdctype == 'image':
  300. # self.imagedict[img]['coords'] = coords
  301. self.select[self.imagedict[img]['id']] = False # ?
  302. pdc.BeginDrawing()
  303. if drawid != 99:
  304. bg = wx.TRANSPARENT_BRUSH
  305. else:
  306. bg = wx.Brush(self.GetBackgroundColour())
  307. pdc.SetBackground(bg)
  308. ### pdc.Clear()
  309. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype=%s, coord=%s" % \
  310. (drawid, pdctype, coords))
  311. # set PseudoDC id
  312. if drawid is not None:
  313. pdc.SetId(drawid)
  314. if pdctype == 'clear': # erase the display
  315. bg = wx.WHITE_BRUSH
  316. # bg = wx.Brush(self.GetBackgroundColour())
  317. pdc.SetBackground(bg)
  318. pdc.RemoveAll()
  319. pdc.Clear()
  320. pdc.EndDrawing()
  321. self.Refresh()
  322. return
  323. if pdctype == 'image': # draw selected image
  324. bitmap = wx.BitmapFromImage(img)
  325. w,h = bitmap.GetSize()
  326. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  327. pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
  328. elif pdctype == 'box': # draw a box on top of the map
  329. if self.pen:
  330. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  331. pdc.SetPen(self.pen)
  332. x2 = max(coords[0],coords[2])
  333. x1 = min(coords[0],coords[2])
  334. y2 = max(coords[1],coords[3])
  335. y1 = min(coords[1],coords[3])
  336. rwidth = x2-x1
  337. rheight = y2-y1
  338. rect = wx.Rect(x1, y1, rwidth, rheight)
  339. pdc.DrawRectangleRect(rect)
  340. pdc.SetIdBounds(drawid, rect)
  341. elif pdctype == 'line': # draw a line on top of the map
  342. if self.pen:
  343. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  344. pdc.SetPen(self.pen)
  345. pdc.DrawLinePoint(wx.Point(coords[0], coords[1]),wx.Point(coords[2], coords[3]))
  346. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
  347. # self.ovlcoords[drawid] = coords
  348. elif pdctype == 'polyline': # draw a polyline on top of the map
  349. if self.polypen:
  350. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  351. pdc.SetPen(self.polypen)
  352. ### pdc.DrawLines(coords)
  353. if (len(coords) < 2):
  354. return
  355. i = 1
  356. while i < len(coords):
  357. pdc.DrawLinePoint(wx.Point(coords[i-1][0], coords[i-1][1]),
  358. wx.Point(coords[i][0], coords[i][1]))
  359. i += 1
  360. # get bounding rectangle for polyline
  361. xlist = []
  362. ylist = []
  363. if len(coords) > 0:
  364. for point in coords:
  365. x,y = point
  366. xlist.append(x)
  367. ylist.append(y)
  368. x1=min(xlist)
  369. x2=max(xlist)
  370. y1=min(ylist)
  371. y2=max(ylist)
  372. pdc.SetIdBounds(drawid, wx.Rect(x1,y1,x2,y2))
  373. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  374. elif pdctype == 'point': # draw point
  375. if self.pen:
  376. pdc.SetPen(self.pen)
  377. pdc.DrawPoint(coords[0], coords[1])
  378. coordsBound = (coords[0] - 5,
  379. coords[1] - 5,
  380. coords[0] + 5,
  381. coords[1] + 5)
  382. pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
  383. # self.ovlcoords[drawid] = coords
  384. elif pdctype == 'text': # draw text on top of map
  385. if not img['active']:
  386. return #only draw active text
  387. if img.has_key('rotation'):
  388. rotation = float(img['rotation'])
  389. else:
  390. rotation = 0.0
  391. w, h = self.GetFullTextExtent(img['text'])[0:2]
  392. pdc.SetFont(img['font'])
  393. pdc.SetTextForeground(img['color'])
  394. coords, w, h = self.TextBounds(img)
  395. if rotation == 0:
  396. pdc.DrawText(img['text'], coords[0], coords[1])
  397. else:
  398. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  399. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], w, h))
  400. pdc.EndDrawing()
  401. self.Refresh()
  402. return drawid
  403. def TextBounds(self, textinfo):
  404. """!
  405. Return text boundary data
  406. @param textinfo text metadata (text, font, color, rotation)
  407. @param coords reference point
  408. """
  409. if textinfo.has_key('rotation'):
  410. rotation = float(textinfo['rotation'])
  411. else:
  412. rotation = 0.0
  413. coords = textinfo['coords']
  414. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  415. (textinfo['text'], rotation))
  416. self.Update()
  417. ### self.Refresh()
  418. self.SetFont(textinfo['font'])
  419. w, h = self.GetTextExtent(textinfo['text'])
  420. if rotation == 0:
  421. coords[2], coords[3] = coords[0] + w, coords[1] + h
  422. return coords, w, h
  423. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  424. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  425. coords[2] = coords[0] + boxw
  426. coords[3] = coords[1] + boxh
  427. return coords, boxw, boxh
  428. def OnKeyDown(self, event):
  429. """!Key pressed"""
  430. shift = event.ShiftDown()
  431. kc = event.GetKeyCode()
  432. vdigitToolbar = self.parent.toolbars['vdigit']
  433. ### vdigit
  434. if vdigitToolbar:
  435. event = None
  436. if not shift:
  437. if kc == ord('P'):
  438. event = wx.CommandEvent(winid = vdigitToolbar.addPoint)
  439. tool = vdigitToolbar.OnAddPoint
  440. elif kc == ord('L'):
  441. event = wx.CommandEvent(winid = vdigitToolbar.addLine)
  442. tool = vdigitToolbar.OnAddLine
  443. if event:
  444. vdigitToolbar.OnTool(event)
  445. tool(event)
  446. def OnPaint(self, event):
  447. """!
  448. Draw PseudoDC's to buffered paint DC
  449. self.pdc for background and decorations
  450. self.pdcVector for vector map which is edited
  451. self.pdcTmp for temporaly drawn objects (self.polycoords)
  452. If self.redrawAll is False on self.pdcTmp content is re-drawn
  453. """
  454. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  455. dc = wx.BufferedPaintDC(self, self.buffer)
  456. ### dc.SetBackground(wx.Brush("White"))
  457. dc.Clear()
  458. # use PrepareDC to set position correctly
  459. self.PrepareDC(dc)
  460. # create a clipping rect from our position and size
  461. # and update region
  462. rgn = self.GetUpdateRegion().GetBox()
  463. dc.SetClippingRect(rgn)
  464. switchDraw = False
  465. if self.redrawAll is None:
  466. self.redrawAll = True
  467. switchDraw = True
  468. if self.redrawAll: # redraw pdc and pdcVector
  469. # draw to the dc using the calculated clipping rect
  470. self.pdc.DrawToDCClipped(dc, rgn)
  471. # draw vector map layer
  472. if self.pdcVector:
  473. # decorate with GDDC (transparency)
  474. try:
  475. gcdc = wx.GCDC(dc)
  476. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  477. except NotImplementedError, e:
  478. print >> sys.stderr, e
  479. self.pdcVector.DrawToDCClipped(dc, rgn)
  480. self.bufferLast = None
  481. else: # do not redraw pdc and pdcVector
  482. if self.bufferLast is None:
  483. # draw to the dc
  484. self.pdc.DrawToDC(dc)
  485. if self.pdcVector:
  486. # decorate with GDDC (transparency)
  487. try:
  488. gcdc = wx.GCDC(dc)
  489. self.pdcVector.DrawToDC(gcdc)
  490. except NotImplementedError, e:
  491. print >> sys.stderr, e
  492. self.pdcVector.DrawToDC(dc)
  493. # store buffered image
  494. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  495. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  496. pdcLast = self.PseudoDC(vdigit = False)
  497. pdcLast.DrawBitmap(self.bufferLast, 0, 0, False)
  498. pdcLast.DrawToDC(dc)
  499. # draw decorations (e.g. region box)
  500. try:
  501. gcdc = wx.GCDC(dc)
  502. self.pdcDec.DrawToDC(gcdc)
  503. except NotImplementedError, e:
  504. print >> sys.stderr, e
  505. self.pdcDec.DrawToDC(dc)
  506. # draw temporary object on the foreground
  507. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  508. self.pdcTmp.DrawToDC(dc)
  509. if switchDraw:
  510. self.redrawAll = False
  511. def OnSize(self, event):
  512. """!Scale map image so that it is the same size as the Window
  513. """
  514. Debug.msg(3, "BufferedWindow.OnSize():")
  515. # set size of the input image
  516. self.Map.ChangeMapSize(self.GetClientSize())
  517. # align extent based on center point and display resolution
  518. # this causes that image is not resized when display windows is resized
  519. ### self.Map.AlignExtentFromDisplay()
  520. # Make new off screen bitmap: this bitmap will always have the
  521. # current drawing in it, so it can be used to save the image to
  522. # a file, or whatever.
  523. self.buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  524. # get the image to be rendered
  525. self.img = self.GetImage()
  526. # update map display
  527. if self.img and self.Map.width + self.Map.height > 0: # scale image during resize
  528. self.img = self.img.Scale(self.Map.width, self.Map.height)
  529. if len(self.Map.GetListOfLayers()) > 0:
  530. self.UpdateMap()
  531. # re-render image on idle
  532. self.resize = True
  533. # reposition checkbox in statusbar
  534. self.parent.StatusbarReposition()
  535. # update statusbar
  536. self.parent.StatusbarUpdate()
  537. def OnIdle(self, event):
  538. """!Only re-render a composite map image from GRASS during
  539. idle time instead of multiple times during resizing.
  540. """
  541. if self.resize:
  542. self.UpdateMap(render=True)
  543. event.Skip()
  544. def SaveToFile(self, FileName, FileType, width, height):
  545. """!This draws the pseudo DC to a buffer that can be saved to
  546. a file.
  547. @param FileName file name
  548. @param FileType type of bitmap
  549. @param width image width
  550. @param height image height
  551. """
  552. busy = wx.BusyInfo(message=_("Please wait, exporting image..."),
  553. parent=self)
  554. wx.Yield()
  555. self.Map.ChangeMapSize((width, height))
  556. ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
  557. self.Map.Render(force=True, windres = True)
  558. img = self.GetImage()
  559. self.Draw(self.pdc, img, drawid = 99)
  560. dc = wx.BufferedPaintDC(self, ibuffer)
  561. dc.Clear()
  562. self.PrepareDC(dc)
  563. self.pdc.DrawToDC(dc)
  564. if self.pdcVector:
  565. self.pdcVector.DrawToDC(dc)
  566. ibuffer.SaveFile(FileName, FileType)
  567. busy.Destroy()
  568. self.UpdateMap(render = True)
  569. self.Refresh()
  570. def GetOverlay(self):
  571. """!
  572. Converts rendered overlay files to wx.Image
  573. Updates self.imagedict
  574. @return list of images
  575. """
  576. imgs = []
  577. for overlay in self.Map.GetListOfLayers(l_type="overlay", l_active=True):
  578. if os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  579. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  580. self.imagedict[img] = { 'id' : overlay.id,
  581. 'layer' : overlay }
  582. imgs.append(img)
  583. return imgs
  584. def GetImage(self):
  585. """!Converts redered map files to wx.Image
  586. Updates self.imagedict (id=99)
  587. @return wx.Image instance (map composition)
  588. """
  589. imgId = 99
  590. if self.mapfile and self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  591. os.path.getsize(self.Map.mapfile):
  592. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  593. else:
  594. img = None
  595. self.imagedict[img] = { 'id': imgId }
  596. return img
  597. def UpdateMap(self, render=True, renderVector=True):
  598. """!
  599. Updates the canvas anytime there is a change to the
  600. underlaying images or to the geometry of the canvas.
  601. @param render re-render map composition
  602. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  603. """
  604. start = time.clock()
  605. self.resize = False
  606. # if len(self.Map.GetListOfLayers()) == 0:
  607. # return False
  608. if self.img is None:
  609. render = True
  610. #
  611. # initialize process bar (only on 'render')
  612. #
  613. if render is True or renderVector is True:
  614. self.parent.statusbarWin['progress'].Show()
  615. if self.parent.statusbarWin['progress'].GetRange() > 0:
  616. self.parent.statusbarWin['progress'].SetValue(1)
  617. #
  618. # render background image if needed
  619. #
  620. # update layer dictionary if there has been a change in layers
  621. if self.tree and self.tree.reorder == True:
  622. self.tree.ReorderLayers()
  623. # reset flag for auto-rendering
  624. if self.tree:
  625. self.tree.rerender = False
  626. if render:
  627. # update display size
  628. self.Map.ChangeMapSize(self.GetClientSize())
  629. if self.parent.statusbarWin['resolution'].IsChecked():
  630. # use computation region resolution for rendering
  631. windres = True
  632. else:
  633. windres = False
  634. self.mapfile = self.Map.Render(force=True, mapWindow=self.parent,
  635. windres=windres)
  636. else:
  637. self.mapfile = self.Map.Render(force=False, mapWindow=self.parent)
  638. self.img = self.GetImage() # id=99
  639. #
  640. # clear pseudoDcs
  641. #
  642. for pdc in (self.pdc,
  643. self.pdcDec,
  644. self.pdcTmp):
  645. pdc.Clear()
  646. pdc.RemoveAll()
  647. #
  648. # draw background map image to PseudoDC
  649. #
  650. if not self.img:
  651. self.Draw(self.pdc, pdctype='clear')
  652. else:
  653. try:
  654. id = self.imagedict[self.img]['id']
  655. except:
  656. return False
  657. self.Draw(self.pdc, self.img, drawid=id)
  658. #
  659. # render vector map layer
  660. #
  661. digitToolbar = self.parent.toolbars['vdigit']
  662. if renderVector and digitToolbar and \
  663. digitToolbar.GetLayer():
  664. # set region
  665. self.parent.digit.driver.UpdateRegion()
  666. # re-calculate threshold for digitization tool
  667. self.parent.digit.driver.GetThreshold()
  668. # draw map
  669. if self.pdcVector:
  670. self.pdcVector.Clear()
  671. self.pdcVector.RemoveAll()
  672. try:
  673. item = self.tree.FindItemByData('maplayer', digitToolbar.GetLayer())
  674. except TypeError:
  675. item = None
  676. if item and self.tree.IsItemChecked(item):
  677. self.parent.digit.driver.DrawMap()
  678. # translate tmp objects (pointer position)
  679. if digitToolbar.GetAction() == 'moveLine':
  680. if hasattr(self, "vdigitMove") and \
  681. self.vdigitMove.has_key('beginDiff'):
  682. # move line
  683. for id in self.vdigitMove['id']:
  684. self.pdcTmp.TranslateId(id,
  685. self.vdigitMove['beginDiff'][0],
  686. self.vdigitMove['beginDiff'][1])
  687. del self.vdigitMove['beginDiff']
  688. #
  689. # render overlays
  690. #
  691. for img in self.GetOverlay():
  692. # draw any active and defined overlays
  693. if self.imagedict[img]['layer'].IsActive():
  694. id = self.imagedict[img]['id']
  695. self.Draw(self.pdc, img=img, drawid=id,
  696. pdctype=self.overlays[id]['pdcType'], coords=self.overlays[id]['coords'])
  697. for id in self.textdict.keys():
  698. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  699. pdctype='text', coords=[10, 10, 10, 10])
  700. # optionally draw computational extent box
  701. self.DrawCompRegionExtent()
  702. #
  703. # redraw pdcTmp if needed
  704. #
  705. if len(self.polycoords) > 0:
  706. self.DrawLines(self.pdcTmp)
  707. if not self.parent.IsStandalone() and \
  708. self.parent.GetLayerManager().georectifying:
  709. # -> georectifier (redraw GCPs)
  710. if self.parent.toolbars['georect']:
  711. coordtype = 'gcpcoord'
  712. else:
  713. coordtype = 'mapcoord'
  714. self.parent.GetLayerManager().georectifying.DrawGCP(coordtype)
  715. if not self.parent.IsStandalone() and \
  716. self.parent.GetLayerManager().gcpmanagement:
  717. # -> georectifier (redraw GCPs)
  718. if self.parent.toolbars['gcpdisp']:
  719. if self == self.parent.TgtMapWindow:
  720. coordtype = 'target'
  721. else:
  722. coordtype = 'source'
  723. self.parent.DrawGCP(coordtype)
  724. #
  725. # clear measurement
  726. #
  727. if self.mouse["use"] == "measure":
  728. self.ClearLines(pdc=self.pdcTmp)
  729. self.polycoords = []
  730. self.mouse['use'] = 'pointer'
  731. self.mouse['box'] = 'point'
  732. self.mouse['end'] = [0, 0]
  733. self.SetCursor(self.parent.cursors["default"])
  734. stop = time.clock()
  735. #
  736. # hide process bar
  737. #
  738. self.parent.statusbarWin['progress'].Hide()
  739. #
  740. # update statusbar
  741. #
  742. ### self.Map.SetRegion()
  743. self.parent.StatusbarUpdate()
  744. if grass.find_file(name = 'MASK', element = 'cell')['name']:
  745. # mask found
  746. self.parent.statusbarWin['mask'].SetLabel(_('MASK'))
  747. else:
  748. self.parent.statusbarWin['mask'].SetLabel('')
  749. Debug.msg (2, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  750. (render, renderVector, (stop-start)))
  751. return True
  752. def DrawCompRegionExtent(self):
  753. """!
  754. Draw computational region extent in the display
  755. Display region is drawn as a blue box inside the computational region,
  756. computational region inside a display region as a red box).
  757. """
  758. if hasattr(self, "regionCoords"):
  759. compReg = self.Map.GetRegion()
  760. dispReg = self.Map.GetCurrentRegion()
  761. reg = None
  762. if self.IsInRegion(dispReg, compReg):
  763. self.polypen = wx.Pen(colour=wx.Colour(0, 0, 255, 128), width=3, style=wx.SOLID)
  764. reg = dispReg
  765. else:
  766. self.polypen = wx.Pen(colour=wx.Colour(255, 0, 0, 128),
  767. width=3, style=wx.SOLID)
  768. reg = compReg
  769. self.regionCoords = []
  770. self.regionCoords.append((reg['w'], reg['n']))
  771. self.regionCoords.append((reg['e'], reg['n']))
  772. self.regionCoords.append((reg['e'], reg['s']))
  773. self.regionCoords.append((reg['w'], reg['s']))
  774. self.regionCoords.append((reg['w'], reg['n']))
  775. # draw region extent
  776. self.DrawLines(pdc=self.pdcDec, polycoords=self.regionCoords)
  777. def IsInRegion(self, region, refRegion):
  778. """!
  779. Test if 'region' is inside of 'refRegion'
  780. @param region input region
  781. @param refRegion reference region (e.g. computational region)
  782. @return True if region is inside of refRegion
  783. @return False
  784. """
  785. if region['s'] >= refRegion['s'] and \
  786. region['n'] <= refRegion['n'] and \
  787. region['w'] >= refRegion['w'] and \
  788. region['e'] <= refRegion['e']:
  789. return True
  790. return False
  791. def EraseMap(self):
  792. """!
  793. Erase the canvas
  794. """
  795. self.Draw(self.pdc, pdctype='clear')
  796. if self.pdcVector:
  797. self.Draw(self.pdcVector, pdctype='clear')
  798. self.Draw(self.pdcDec, pdctype='clear')
  799. self.Draw(self.pdcTmp, pdctype='clear')
  800. def DragMap(self, moveto):
  801. """!
  802. Drag the entire map image for panning.
  803. @param moveto dx,dy
  804. """
  805. dc = wx.BufferedDC(wx.ClientDC(self))
  806. dc.SetBackground(wx.Brush("White"))
  807. dc.Clear()
  808. self.dragimg = wx.DragImage(self.buffer)
  809. self.dragimg.BeginDrag((0, 0), self)
  810. self.dragimg.GetImageRect(moveto)
  811. self.dragimg.Move(moveto)
  812. self.dragimg.DoDrawImage(dc, moveto)
  813. self.dragimg.EndDrag()
  814. def DragItem(self, id, event):
  815. """!
  816. Drag an overlay decoration item
  817. """
  818. if id == 99 or id == '' or id == None: return
  819. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  820. x, y = self.lastpos
  821. dx = event.GetX() - x
  822. dy = event.GetY() - y
  823. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  824. r = self.pdc.GetIdBounds(id)
  825. ### FIXME in vdigit/pseudodc.i
  826. if type(r) is list:
  827. r = wx.Rect(r[0], r[1], r[2], r[3])
  828. if id > 100: # text dragging
  829. rtop = (r[0],r[1]-r[3],r[2],r[3])
  830. r = r.Union(rtop)
  831. rleft = (r[0]-r[2],r[1],r[2],r[3])
  832. r = r.Union(rleft)
  833. self.pdc.TranslateId(id, dx, dy)
  834. r2 = self.pdc.GetIdBounds(id)
  835. if type(r2) is list:
  836. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  837. if id > 100: # text
  838. self.textdict[id]['coords'] = r2
  839. r = r.Union(r2)
  840. r.Inflate(4,4)
  841. self.RefreshRect(r, False)
  842. self.lastpos = (event.GetX(), event.GetY())
  843. def MouseDraw(self, pdc=None, begin=None, end=None):
  844. """!
  845. Mouse box or line from 'begin' to 'end'
  846. If not given from self.mouse['begin'] to self.mouse['end'].
  847. """
  848. # self.redrawAll = False
  849. if not pdc:
  850. return
  851. if begin is None:
  852. begin = self.mouse['begin']
  853. if end is None:
  854. end = self.mouse['end']
  855. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  856. (self.mouse['use'], self.mouse['box'],
  857. begin[0], begin[1], end[0], end[1]))
  858. if self.mouse['box'] == "box":
  859. boxid = wx.ID_NEW
  860. mousecoords = [begin[0], begin[1],
  861. end[0], end[1]]
  862. r = pdc.GetIdBounds(boxid)
  863. if type(r) is list:
  864. r = wx.Rect(r[0], r[1], r[2], r[3])
  865. r.Inflate(4, 4)
  866. try:
  867. pdc.ClearId(boxid)
  868. except:
  869. pass
  870. self.RefreshRect(r, False)
  871. pdc.SetId(boxid)
  872. self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
  873. elif self.mouse['box'] == "line" or self.mouse['box'] == 'point':
  874. self.lineid = wx.ID_NEW
  875. mousecoords = [begin[0], begin[1], \
  876. end[0], end[1]]
  877. x1=min(begin[0],end[0])
  878. x2=max(begin[0],end[0])
  879. y1=min(begin[1],end[1])
  880. y2=max(begin[1],end[1])
  881. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  882. r.Inflate(4,4)
  883. try:
  884. pdc.ClearId(self.lineid)
  885. except:
  886. pass
  887. self.RefreshRect(r, False)
  888. pdc.SetId(self.lineid)
  889. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=mousecoords)
  890. def DrawLines(self, pdc=None, polycoords=None):
  891. """!
  892. Draw polyline in PseudoDC
  893. Set self.pline to wx.NEW_ID + 1
  894. polycoords - list of polyline vertices, geographical coordinates
  895. (if not given, self.polycoords is used)
  896. """
  897. if not pdc:
  898. pdc = self.pdcTmp
  899. if not polycoords:
  900. polycoords = self.polycoords
  901. if len(polycoords) > 0:
  902. self.plineid = wx.ID_NEW + 1
  903. # convert from EN to XY
  904. coords = []
  905. for p in polycoords:
  906. coords.append(self.Cell2Pixel(p))
  907. self.Draw(pdc, drawid=self.plineid, pdctype='polyline', coords=coords)
  908. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  909. (coords, self.plineid))
  910. return self.plineid
  911. return -1
  912. def DrawCross(self, pdc, coords, size, rotation=0,
  913. text=None, textAlign='lr', textOffset=(5, 5)):
  914. """!Draw cross in PseudoDC
  915. @todo implement rotation
  916. @param pdc PseudoDC
  917. @param coord center coordinates
  918. @param rotation rotate symbol
  919. @param text draw also text (text, font, color, rotation)
  920. @param textAlign alignment (default 'lower-right')
  921. @textOffset offset for text (from center point)
  922. """
  923. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  924. (pdc, coords, size))
  925. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  926. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  927. self.lineid = wx.NewId()
  928. for lineCoords in coordsCross:
  929. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=lineCoords)
  930. if not text:
  931. return self.lineid
  932. if textAlign == 'ul':
  933. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  934. elif textAlign == 'ur':
  935. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  936. elif textAlign == 'lr':
  937. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  938. else:
  939. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  940. self.Draw(pdc, img=text,
  941. pdctype='text', coords=coord)
  942. return self.lineid
  943. def MouseActions(self, event):
  944. """!
  945. Mouse motion and button click notifier
  946. """
  947. if not self.processMouse:
  948. return
  949. ### if self.redrawAll is False:
  950. ### self.redrawAll = True
  951. # zoom with mouse wheel
  952. if event.GetWheelRotation() != 0:
  953. self.OnMouseWheel(event)
  954. # left mouse button pressed
  955. elif event.LeftDown():
  956. self.OnLeftDown(event)
  957. # left mouse button released
  958. elif event.LeftUp():
  959. self.OnLeftUp(event)
  960. # dragging
  961. elif event.Dragging():
  962. self.OnDragging(event)
  963. # double click
  964. elif event.ButtonDClick():
  965. self.OnButtonDClick(event)
  966. # middle mouse button pressed
  967. elif event.MiddleDown():
  968. self.OnMiddleDown(event)
  969. # middle mouse button relesed
  970. elif event.MiddleUp():
  971. self.OnMiddleUp(event)
  972. # right mouse button pressed
  973. elif event.RightDown():
  974. self.OnRightDown(event)
  975. # right mouse button released
  976. elif event.RightUp():
  977. self.OnRightUp(event)
  978. elif event.Entering():
  979. self.OnMouseEnter(event)
  980. elif event.Moving():
  981. self.OnMouseMoving(event)
  982. # event.Skip()
  983. def OnMouseWheel(self, event):
  984. """!
  985. Mouse wheel moved
  986. """
  987. self.processMouse = False
  988. current = event.GetPositionTuple()[:]
  989. wheel = event.GetWheelRotation()
  990. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  991. # zoom 1/2 of the screen, centered to current mouse position (TODO: settings)
  992. begin = (current[0] - self.Map.width / 4,
  993. current[1] - self.Map.height / 4)
  994. end = (current[0] + self.Map.width / 4,
  995. current[1] + self.Map.height / 4)
  996. if wheel > 0:
  997. zoomtype = 1
  998. else:
  999. zoomtype = -1
  1000. # zoom
  1001. self.Zoom(begin, end, zoomtype)
  1002. # redraw map
  1003. self.UpdateMap()
  1004. ### self.OnPaint(None)
  1005. # update statusbar
  1006. self.parent.StatusbarUpdate()
  1007. self.Refresh()
  1008. self.processMouse = True
  1009. # event.Skip()
  1010. def OnDragging(self, event):
  1011. """!
  1012. Mouse dragging with left button down
  1013. """
  1014. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  1015. current = event.GetPositionTuple()[:]
  1016. previous = self.mouse['begin']
  1017. move = (current[0] - previous[0],
  1018. current[1] - previous[1])
  1019. digitToolbar = self.parent.toolbars['vdigit']
  1020. # dragging or drawing box with left button
  1021. if self.mouse['use'] == 'pan' or \
  1022. event.MiddleIsDown():
  1023. self.DragMap(move)
  1024. # dragging decoration overlay item
  1025. elif (self.mouse['use'] == 'pointer' and
  1026. not digitToolbar and
  1027. self.dragid != None):
  1028. self.DragItem(self.dragid, event)
  1029. # dragging anything else - rubber band box or line
  1030. else:
  1031. if (self.mouse['use'] == 'pointer' and
  1032. not digitToolbar): return
  1033. self.mouse['end'] = event.GetPositionTuple()[:]
  1034. digitClass = self.parent.digit
  1035. if (event.LeftIsDown() and
  1036. not (digitToolbar and
  1037. digitToolbar.GetAction() in ("moveLine",) and
  1038. digitClass.driver.GetSelected() > 0)):
  1039. # draw box only when left mouse button is pressed
  1040. self.MouseDraw(pdc=self.pdcTmp)
  1041. # event.Skip()
  1042. def OnLeftDownVDigitAddLine(self, event):
  1043. """!
  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. """!
  1295. Left mouse button down - vector digitizer label 3d vector
  1296. lines
  1297. """
  1298. digitToolbar = self.parent.toolbars['vdigit']
  1299. digitClass = self.parent.digit
  1300. if len(self.polycoords) > 1: # start new line
  1301. self.polycoords = []
  1302. self.ClearLines(pdc=self.pdcTmp)
  1303. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1304. if len(self.polycoords) == 1:
  1305. begin = self.Pixel2Cell(self.polycoords[-1])
  1306. end = self.Pixel2Cell(self.mouse['end'])
  1307. else:
  1308. end = self.Pixel2Cell(self.polycoords[-1])
  1309. begin = self.Pixel2Cell(self.mouse['begin'])
  1310. self.DrawLines(self.pdcTmp, polycoords = (begin, end))
  1311. def OnLeftDown(self, event):
  1312. """!
  1313. Left mouse button pressed
  1314. """
  1315. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  1316. self.mouse["use"])
  1317. self.mouse['begin'] = event.GetPositionTuple()[:]
  1318. if self.mouse["use"] in ["measure", "profile"]:
  1319. # measure or profile
  1320. if len(self.polycoords) == 0:
  1321. self.mouse['end'] = self.mouse['begin']
  1322. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  1323. self.ClearLines(pdc=self.pdcTmp)
  1324. else:
  1325. self.mouse['begin'] = self.mouse['end']
  1326. elif self.mouse['use'] == 'zoom':
  1327. pass
  1328. #
  1329. # vector digizer
  1330. #
  1331. elif self.mouse["use"] == "pointer" and \
  1332. self.parent.toolbars['vdigit']:
  1333. digitToolbar = self.parent.toolbars['vdigit']
  1334. digitClass = self.parent.digit
  1335. try:
  1336. mapLayer = digitToolbar.GetLayer().GetName()
  1337. except:
  1338. wx.MessageBox(parent=self,
  1339. message=_("No vector map selected for editing."),
  1340. caption=_("Vector digitizer"),
  1341. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1342. event.Skip()
  1343. return
  1344. if digitToolbar.GetAction() not in ("moveVertex",
  1345. "addVertex",
  1346. "removeVertex",
  1347. "editLine"):
  1348. # set pen
  1349. self.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  1350. self.polypen = wx.Pen(colour='dark green', width=2, style=wx.SOLID)
  1351. if digitToolbar.GetAction() in ("addVertex",
  1352. "removeVertex",
  1353. "splitLines"):
  1354. # unselect
  1355. digitClass.driver.SetSelected([])
  1356. if digitToolbar.GetAction() == "addLine":
  1357. self.OnLeftDownVDigitAddLine(event)
  1358. elif digitToolbar.GetAction() == "editLine" and \
  1359. hasattr(self, "vdigitMove"):
  1360. self.OnLeftDownVDigitEditLine(event)
  1361. elif digitToolbar.GetAction() in ("moveLine",
  1362. "moveVertex",
  1363. "editLine") and \
  1364. not hasattr(self, "vdigitMove"):
  1365. self.OnLeftDownVDigitMoveLine(event)
  1366. elif digitToolbar.GetAction() in ("displayAttrs"
  1367. "displayCats"):
  1368. self.OnLeftDownVDigitDisplayCA(event)
  1369. elif digitToolbar.GetAction() in ("copyCats",
  1370. "copyAttrs"):
  1371. self.OnLeftDownVDigitCopyCA(event)
  1372. elif digitToolbar.GetAction() == "copyLine":
  1373. self.OnLeftDownVDigitCopyLine(event)
  1374. elif digitToolbar.GetAction() == "zbulkLine":
  1375. self.OnLeftDownVDigitBulkLine(event)
  1376. elif self.mouse['use'] == 'pointer':
  1377. # get decoration or text id
  1378. self.idlist = []
  1379. self.dragid = ''
  1380. self.lastpos = self.mouse['begin']
  1381. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  1382. self.hitradius)
  1383. if 99 in idlist:
  1384. idlist.remove(99)
  1385. if idlist != []:
  1386. self.dragid = idlist[0] #drag whatever is on top
  1387. else:
  1388. pass
  1389. event.Skip()
  1390. def OnLeftUpVDigitVarious(self, event):
  1391. """!
  1392. Left mouse button up - vector digitizer various actions
  1393. """
  1394. digitToolbar = self.parent.toolbars['vdigit']
  1395. digitClass = self.parent.digit
  1396. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1397. pos2 = self.Pixel2Cell(self.mouse['end'])
  1398. nselected = 0
  1399. # -> delete line || move line || move vertex
  1400. if digitToolbar.GetAction() in ("moveVertex",
  1401. "editLine"):
  1402. if len(digitClass.driver.GetSelected()) == 0:
  1403. nselected = digitClass.driver.SelectLineByPoint(pos1, type=VDigit_Lines_Type)
  1404. if digitToolbar.GetAction() == "editLine":
  1405. try:
  1406. selVertex = digitClass.driver.GetSelectedVertex(pos1)[0]
  1407. except IndexError:
  1408. selVertex = None
  1409. if selVertex:
  1410. # self.UpdateMap(render=False)
  1411. ids = digitClass.driver.GetSelected(grassId=False)
  1412. # move this line to tmp layer
  1413. self.polycoords = []
  1414. for id in ids:
  1415. if id % 2: # register only vertices
  1416. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  1417. self.polycoords.append((e, n))
  1418. digitClass.driver.DrawSelected(False)
  1419. if selVertex < ids[-1] / 2:
  1420. # choose first or last node of line
  1421. self.vdigitMove['id'].reverse()
  1422. self.polycoords.reverse()
  1423. else:
  1424. # unselect
  1425. digitClass.driver.SetSelected([])
  1426. del self.vdigitMove
  1427. self.UpdateMap(render=False)
  1428. elif digitToolbar.GetAction() in ("copyCats",
  1429. "copyAttrs"):
  1430. if not hasattr(self, "copyCatsIds"):
  1431. # 'from' -> select by point
  1432. nselected = digitClass.driver.SelectLineByPoint(pos1, digitClass.GetSelectType())
  1433. if nselected:
  1434. self.copyCatsList = digitClass.driver.GetSelected()
  1435. else:
  1436. # -> 'to' -> select by bbox
  1437. digitClass.driver.SetSelected([])
  1438. # return number of selected features (by box/point)
  1439. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1440. digitClass.GetSelectType())
  1441. if nselected == 0:
  1442. if digitClass.driver.SelectLineByPoint(pos1,
  1443. digitClass.GetSelectType()) is not None:
  1444. nselected = 1
  1445. if nselected > 0:
  1446. self.copyCatsIds = digitClass.driver.GetSelected()
  1447. elif digitToolbar.GetAction() == "queryLine":
  1448. selected = digitClass.SelectLinesByQuery(pos1, pos2)
  1449. nselected = len(selected)
  1450. if nselected > 0:
  1451. digitClass.driver.SetSelected(selected)
  1452. else:
  1453. # -> moveLine || deleteLine, etc. (select by point/box)
  1454. if digitToolbar.GetAction() == 'moveLine' and \
  1455. len(digitClass.driver.GetSelected()) > 0:
  1456. nselected = 0
  1457. else:
  1458. if digitToolbar.GetAction() == 'moveLine':
  1459. drawSeg = True
  1460. else:
  1461. drawSeg = False
  1462. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1463. digitClass.GetSelectType(),
  1464. drawSeg)
  1465. if nselected == 0:
  1466. if digitClass.driver.SelectLineByPoint(pos1,
  1467. digitClass.GetSelectType()) is not None:
  1468. nselected = 1
  1469. if nselected > 0:
  1470. if digitToolbar.GetAction() in ("moveLine",
  1471. "moveVertex"):
  1472. # get pseudoDC id of objects which should be redrawn
  1473. if digitToolbar.GetAction() == "moveLine":
  1474. # -> move line
  1475. self.vdigitMove['id'] = digitClass.driver.GetSelected(grassId=False)
  1476. self.vdigitMove['coord'] = digitClass.driver.GetSelectedCoord()
  1477. else: # moveVertex
  1478. self.vdigitMove['id'] = digitClass.driver.GetSelectedVertex(pos1)
  1479. if len(self.vdigitMove['id']) == 0: # no vertex found
  1480. digitClass.driver.SetSelected([])
  1481. #
  1482. # check for duplicates
  1483. #
  1484. if UserSettings.Get(group='vdigit', key='checkForDupl', subkey='enabled') is True:
  1485. dupl = digitClass.driver.GetDuplicates()
  1486. self.UpdateMap(render=False)
  1487. if dupl:
  1488. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1489. self.mouse['end'][1] + self.dialogOffset))
  1490. dlg = VDigitDuplicatesDialog(parent=self, data=dupl, pos=posWindow)
  1491. if dlg.ShowModal() == wx.ID_OK:
  1492. digitClass.driver.UnSelect(dlg.GetUnSelected())
  1493. # update selected
  1494. self.UpdateMap(render=False)
  1495. if digitToolbar.GetAction() != "editLine":
  1496. # -> move line || move vertex
  1497. self.UpdateMap(render=False)
  1498. else: # no vector object found
  1499. if not (digitToolbar.GetAction() in ("moveLine",
  1500. "moveVertex") and \
  1501. len(self.vdigitMove['id']) > 0):
  1502. # avoid left-click when features are already selected
  1503. self.UpdateMap(render=False, renderVector=False)
  1504. def OnLeftUpVDigitModifyLine(self, event):
  1505. """!
  1506. Left mouse button up - vector digitizer split line, add/remove
  1507. vertex action
  1508. """
  1509. digitToolbar = self.parent.toolbars['vdigit']
  1510. digitClass = self.parent.digit
  1511. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1512. pointOnLine = digitClass.driver.SelectLineByPoint(pos1,
  1513. type=VDigit_Lines_Type)
  1514. if not pointOnLine:
  1515. return
  1516. if digitToolbar.GetAction() in ["splitLine", "addVertex"]:
  1517. self.UpdateMap(render=False) # highlight object
  1518. self.DrawCross(pdc=self.pdcTmp, coords=self.Cell2Pixel(pointOnLine),
  1519. size=5)
  1520. else: # removeVertex
  1521. # get only id of vertex
  1522. try:
  1523. id = digitClass.driver.GetSelectedVertex(pos1)[0]
  1524. except IndexError:
  1525. id = None
  1526. if id:
  1527. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  1528. self.pdcVector.RemoveId(id)
  1529. self.UpdateMap(render=False) # highlight object
  1530. self.DrawCross(pdc=self.pdcTmp, coords=(x, y),
  1531. size=5)
  1532. else:
  1533. # unselect
  1534. digitClass.driver.SetSelected([])
  1535. self.UpdateMap(render=False)
  1536. def OnLeftUpVDigitCopyLine(self, event):
  1537. """!
  1538. Left mouse button up - vector digitizer copy feature action
  1539. """
  1540. digitToolbar = self.parent.toolbars['vdigit']
  1541. digitClass = self.parent.digit
  1542. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1543. pos2 = self.Pixel2Cell(self.mouse['end'])
  1544. if UserSettings.Get(group='vdigit', key='bgmap',
  1545. subkey='value', internal=True) == '':
  1546. # no background map -> copy from current vector map layer
  1547. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1548. digitClass.GetSelectType())
  1549. if nselected > 0:
  1550. # highlight selected features
  1551. self.UpdateMap(render=False)
  1552. else:
  1553. self.UpdateMap(render=False, renderVector=False)
  1554. else:
  1555. # copy features from background map
  1556. self.copyIds += digitClass.SelectLinesFromBackgroundMap(pos1, pos2)
  1557. if len(self.copyIds) > 0:
  1558. color = UserSettings.Get(group='vdigit', key='symbol',
  1559. subkey=['highlight', 'color'])
  1560. colorStr = str(color[0]) + ":" + \
  1561. str(color[1]) + ":" + \
  1562. str(color[2])
  1563. dVectTmp = ['d.vect',
  1564. 'map=%s' % UserSettings.Get(group='vdigit', key='bgmap',
  1565. subkey='value', internal=True),
  1566. 'cats=%s' % utils.ListOfCatsToRange(self.copyIds),
  1567. '-i',
  1568. 'color=%s' % colorStr,
  1569. 'fcolor=%s' % colorStr,
  1570. 'type=point,line,boundary,centroid',
  1571. 'width=2']
  1572. if not self.layerTmp:
  1573. self.layerTmp = self.Map.AddLayer(type='vector',
  1574. name=globalvar.QUERYLAYER,
  1575. command=dVectTmp)
  1576. else:
  1577. self.layerTmp.SetCmd(dVectTmp)
  1578. self.UpdateMap(render=True, renderVector=False)
  1579. else:
  1580. self.UpdateMap(render=False, renderVector=False)
  1581. self.redrawAll = None
  1582. def OnLeftUpVDigitBulkLine(self, event):
  1583. """!
  1584. Left mouse button up - vector digitizer z-bulk line action
  1585. """
  1586. digitToolbar = self.parent.toolbars['vdigit']
  1587. digitClass = self.parent.digit
  1588. # select lines to be labeled
  1589. pos1 = self.polycoords[0]
  1590. pos2 = self.polycoords[1]
  1591. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1592. digitClass.GetSelectType())
  1593. if nselected > 0:
  1594. # highlight selected features
  1595. self.UpdateMap(render=False)
  1596. self.DrawLines(pdc=self.pdcTmp) # redraw temp line
  1597. else:
  1598. self.UpdateMap(render=False, renderVector=False)
  1599. def OnLeftUpVDigitConnectLine(self, event):
  1600. """!
  1601. Left mouse button up - vector digitizer connect line action
  1602. """
  1603. digitToolbar = self.parent.toolbars['vdigit']
  1604. digitClass = self.parent.digit
  1605. if len(digitClass.driver.GetSelected()) > 0:
  1606. self.UpdateMap(render=False)
  1607. def OnLeftUp(self, event):
  1608. """!Left mouse button released
  1609. """
  1610. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  1611. self.mouse["use"])
  1612. self.mouse['end'] = event.GetPositionTuple()[:]
  1613. if self.mouse['use'] in ["zoom", "pan"]:
  1614. # set region in zoom or pan
  1615. begin = self.mouse['begin']
  1616. end = self.mouse['end']
  1617. if self.mouse['use'] == 'zoom':
  1618. # set region for click (zero-width box)
  1619. if begin[0] - end[0] == 0 or \
  1620. begin[1] - end[1] == 0:
  1621. # zoom 1/2 of the screen (TODO: settings)
  1622. begin = (end[0] - self.Map.width / 4,
  1623. end[1] - self.Map.height / 4)
  1624. end = (end[0] + self.Map.width / 4,
  1625. end[1] + self.Map.height / 4)
  1626. self.Zoom(begin, end, self.zoomtype)
  1627. # redraw map
  1628. self.UpdateMap(render=True)
  1629. # update statusbar
  1630. self.parent.StatusbarUpdate()
  1631. elif self.mouse["use"] == "query":
  1632. # querying
  1633. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  1634. elif self.mouse["use"] == "queryVector":
  1635. # editable mode for vector map layers
  1636. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  1637. # clear temp canvas
  1638. self.UpdateMap(render=False, renderVector=False)
  1639. elif self.mouse["use"] in ["measure", "profile"]:
  1640. # measure or profile
  1641. if self.mouse["use"] == "measure":
  1642. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  1643. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1644. self.ClearLines(pdc=self.pdcTmp)
  1645. self.DrawLines(pdc=self.pdcTmp)
  1646. elif self.mouse["use"] == "pointer" and \
  1647. self.parent.GetLayerManager().gcpmanagement:
  1648. # -> GCP manager
  1649. if self.parent.toolbars['gcpdisp']:
  1650. coord = self.Pixel2Cell(self.mouse['end'])
  1651. if self.parent.MapWindow == self.parent.SrcMapWindow:
  1652. coordtype = 'source'
  1653. else:
  1654. coordtype = 'target'
  1655. self.parent.GetLayerManager().gcpmanagement.SetGCPData(coordtype, coord, self, confirm=True)
  1656. self.UpdateMap(render=False, renderVector=False)
  1657. elif self.mouse["use"] == "pointer" and \
  1658. self.parent.GetLayerManager().georectifying:
  1659. # -> georectifying
  1660. coord = self.Pixel2Cell(self.mouse['end'])
  1661. if self.parent.toolbars['georect']:
  1662. coordtype = 'gcpcoord'
  1663. else:
  1664. coordtype = 'mapcoord'
  1665. self.parent.GetLayerManager().georectifying.SetGCPData(coordtype, coord, self)
  1666. self.UpdateMap(render=False, renderVector=False)
  1667. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  1668. # digitization tool active
  1669. digitToolbar = self.parent.toolbars['vdigit']
  1670. digitClass = self.parent.digit
  1671. if hasattr(self, "vdigitMove"):
  1672. if len(digitClass.driver.GetSelected()) == 0:
  1673. self.vdigitMove['begin'] = self.Pixel2Cell(self.mouse['begin']) # left down
  1674. # eliminate initial mouse moving efect
  1675. self.mouse['begin'] = self.mouse['end']
  1676. if digitToolbar.GetAction() in ("deleteLine",
  1677. "moveLine",
  1678. "moveVertex",
  1679. "copyCats",
  1680. "copyAttrs",
  1681. "editLine",
  1682. "flipLine",
  1683. "mergeLine",
  1684. "snapLine",
  1685. "queryLine",
  1686. "breakLine",
  1687. "typeConv",
  1688. "connectLine"):
  1689. self.OnLeftUpVDigitVarious(event)
  1690. elif digitToolbar.GetAction() in ("splitLine",
  1691. "addVertex",
  1692. "removeVertex"):
  1693. self.OnLeftUpVDigitModifyLine(event)
  1694. elif digitToolbar.GetAction() == "copyLine":
  1695. self.OnLeftUpVDigitCopyLine(event)
  1696. elif digitToolbar.GetAction() == "zbulkLine" and \
  1697. len(self.polycoords) == 2:
  1698. self.OnLeftUpVDigitBulkLine(event)
  1699. elif digitToolbar.GetAction() == "connectLine":
  1700. self.OnLeftUpConnectLine(event)
  1701. if len(digitClass.driver.GetSelected()) > 0:
  1702. self.redrawAll = None
  1703. elif (self.mouse['use'] == 'pointer' and
  1704. self.dragid >= 0):
  1705. # end drag of overlay decoration
  1706. if self.dragid < 99 and self.overlays.has_key(self.dragid):
  1707. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1708. elif self.dragid > 100 and self.textdict.has_key(self.dragid):
  1709. self.textdict[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1710. else:
  1711. pass
  1712. self.dragid = None
  1713. self.currtxtid = None
  1714. def OnButtonDClick(self, event):
  1715. """!
  1716. Mouse button double click
  1717. """
  1718. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1719. self.mouse["use"])
  1720. if self.mouse["use"] == "measure":
  1721. # measure
  1722. self.ClearLines(pdc=self.pdcTmp)
  1723. self.polycoords = []
  1724. self.mouse['use'] = 'pointer'
  1725. self.mouse['box'] = 'point'
  1726. self.mouse['end'] = [0, 0]
  1727. self.Refresh()
  1728. self.SetCursor(self.parent.cursors["default"])
  1729. elif self.mouse["use"] == "profile":
  1730. pass
  1731. elif self.mouse['use'] == 'pointer' and \
  1732. self.parent.toolbars['vdigit']:
  1733. # vector digitizer
  1734. pass
  1735. else:
  1736. # select overlay decoration options dialog
  1737. clickposition = event.GetPositionTuple()[:]
  1738. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1739. if idlist == []:
  1740. return
  1741. self.dragid = idlist[0]
  1742. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1743. if self.dragid > 100:
  1744. self.currtxtid = self.dragid
  1745. self.parent.OnAddText(None)
  1746. elif self.dragid == 0:
  1747. self.parent.OnAddBarscale(None)
  1748. elif self.dragid == 1:
  1749. self.parent.OnAddLegend(None)
  1750. def OnRightDown(self, event):
  1751. """!
  1752. Right mouse button pressed
  1753. """
  1754. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1755. self.mouse["use"])
  1756. digitToolbar = self.parent.toolbars['vdigit']
  1757. if digitToolbar:
  1758. digitClass = self.parent.digit
  1759. # digitization tool (confirm action)
  1760. if digitToolbar.GetAction() in ("moveLine",
  1761. "moveVertex") and \
  1762. hasattr(self, "vdigitMove"):
  1763. pFrom = self.vdigitMove['begin']
  1764. pTo = self.Pixel2Cell(event.GetPositionTuple())
  1765. move = (pTo[0] - pFrom[0],
  1766. pTo[1] - pFrom[1])
  1767. if digitToolbar.GetAction() == "moveLine":
  1768. # move line
  1769. if digitClass.MoveSelectedLines(move) < 0:
  1770. return
  1771. elif digitToolbar.GetAction() == "moveVertex":
  1772. # move vertex
  1773. fid = digitClass.MoveSelectedVertex(pFrom, move)
  1774. if fid < 0:
  1775. return
  1776. self.__geomAttrbUpdate([fid,])
  1777. del self.vdigitMove
  1778. event.Skip()
  1779. def OnRightUp(self, event):
  1780. """!
  1781. Right mouse button released
  1782. """
  1783. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1784. self.mouse["use"])
  1785. digitToolbar = self.parent.toolbars['vdigit']
  1786. if digitToolbar:
  1787. digitClass = self.parent.digit
  1788. # digitization tool (confirm action)
  1789. if digitToolbar.GetAction() == "addLine" and \
  1790. digitToolbar.GetAction('type') in ["line", "boundary"]:
  1791. # -> add new line / boundary
  1792. try:
  1793. map = digitToolbar.GetLayer().GetName()
  1794. except:
  1795. map = None
  1796. wx.MessageBox(parent=self,
  1797. message=_("No vector map selected for editing."),
  1798. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1799. if map:
  1800. # mapcoords = []
  1801. # xy -> EN
  1802. # for coord in self.polycoords:
  1803. # mapcoords.append(self.Pixel2Cell(coord))
  1804. if digitToolbar.GetAction('type') == 'line':
  1805. line = True
  1806. else:
  1807. line = False
  1808. if len(self.polycoords) < 2: # ignore 'one-point' lines
  1809. return
  1810. fid = digitClass.AddLine(map, line, self.polycoords)
  1811. if fid < 0:
  1812. return
  1813. position = self.Cell2Pixel(self.polycoords[-1])
  1814. self.polycoords = []
  1815. self.UpdateMap(render=False)
  1816. self.redrawAll = True
  1817. self.Refresh()
  1818. # add new record into atribute table
  1819. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') and \
  1820. (line is True or \
  1821. (not line and fid > 0)):
  1822. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  1823. position[1] + self.dialogOffset))
  1824. # select attributes based on layer and category
  1825. cats = { fid : {
  1826. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  1827. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  1828. }}
  1829. addRecordDlg = dbm_dialogs.DisplayAttributesDialog(parent=self, map=map,
  1830. cats=cats,
  1831. pos=posWindow,
  1832. action="add")
  1833. self.__geomAttrb(fid, addRecordDlg, 'length', digitClass,
  1834. digitToolbar.GetLayer())
  1835. # auto-placing centroid
  1836. self.__geomAttrb(fid, addRecordDlg, 'area', digitClass,
  1837. digitToolbar.GetLayer())
  1838. self.__geomAttrb(fid, addRecordDlg, 'perimeter', digitClass,
  1839. digitToolbar.GetLayer())
  1840. if addRecordDlg.mapDBInfo and \
  1841. addRecordDlg.ShowModal() == wx.ID_OK:
  1842. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1843. for sql in addRecordDlg.GetSQLString():
  1844. sqlfile.file.write(sql + ";\n")
  1845. sqlfile.file.flush()
  1846. gcmd.RunCommand('db.execute',
  1847. parent = True,
  1848. quiet = True,
  1849. input = sqlfile.name)
  1850. if addRecordDlg.mapDBInfo:
  1851. self.__updateATM()
  1852. elif digitToolbar.GetAction() == "deleteLine":
  1853. # -> delete selected vector features
  1854. if digitClass.DeleteSelectedLines() < 0:
  1855. return
  1856. self.__updateATM()
  1857. elif digitToolbar.GetAction() == "splitLine":
  1858. # split line
  1859. if digitClass.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1860. return
  1861. elif digitToolbar.GetAction() == "addVertex":
  1862. # add vertex
  1863. fid = digitClass.AddVertex(self.Pixel2Cell(self.mouse['begin']))
  1864. if fid < 0:
  1865. return
  1866. elif digitToolbar.GetAction() == "removeVertex":
  1867. # remove vertex
  1868. fid = digitClass.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
  1869. if fid < 0:
  1870. return
  1871. self.__geomAttrbUpdate([fid,])
  1872. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1873. try:
  1874. if digitToolbar.GetAction() == 'copyCats':
  1875. if digitClass.CopyCats(self.copyCatsList,
  1876. self.copyCatsIds, copyAttrb=False) < 0:
  1877. return
  1878. else:
  1879. if digitClass.CopyCats(self.copyCatsList,
  1880. self.copyCatsIds, copyAttrb=True) < 0:
  1881. return
  1882. del self.copyCatsList
  1883. del self.copyCatsIds
  1884. except AttributeError:
  1885. pass
  1886. self.__updateATM()
  1887. elif digitToolbar.GetAction() == "editLine" and \
  1888. hasattr(self, "vdigitMove"):
  1889. line = digitClass.driver.GetSelected()
  1890. if digitClass.EditLine(line, self.polycoords) < 0:
  1891. return
  1892. del self.vdigitMove
  1893. elif digitToolbar.GetAction() == "flipLine":
  1894. if digitClass.FlipLine() < 0:
  1895. return
  1896. elif digitToolbar.GetAction() == "mergeLine":
  1897. if digitClass.MergeLine() < 0:
  1898. return
  1899. elif digitToolbar.GetAction() == "breakLine":
  1900. if digitClass.BreakLine() < 0:
  1901. return
  1902. elif digitToolbar.GetAction() == "snapLine":
  1903. if digitClass.SnapLine() < 0:
  1904. return
  1905. elif digitToolbar.GetAction() == "connectLine":
  1906. if len(digitClass.driver.GetSelected()) > 1:
  1907. if digitClass.ConnectLine() < 0:
  1908. return
  1909. elif digitToolbar.GetAction() == "copyLine":
  1910. if digitClass.CopyLine(self.copyIds) < 0:
  1911. return
  1912. del self.copyIds
  1913. if self.layerTmp:
  1914. self.Map.DeleteLayer(self.layerTmp)
  1915. self.UpdateMap(render=True, renderVector=False)
  1916. del self.layerTmp
  1917. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1918. pos1 = self.polycoords[0]
  1919. pos2 = self.polycoords[1]
  1920. selected = digitClass.driver.GetSelected()
  1921. dlg = VDigitZBulkDialog(parent=self, title=_("Z bulk-labeling dialog"),
  1922. nselected=len(selected))
  1923. if dlg.ShowModal() == wx.ID_OK:
  1924. if digitClass.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
  1925. dlg.step.GetValue()) < 0:
  1926. return
  1927. self.UpdateMap(render=False, renderVector=True)
  1928. elif digitToolbar.GetAction() == "typeConv":
  1929. # -> feature type conversion
  1930. # - point <-> centroid
  1931. # - line <-> boundary
  1932. if digitClass.TypeConvForSelectedLines() < 0:
  1933. return
  1934. if digitToolbar.GetAction() != "addLine":
  1935. # unselect and re-render
  1936. digitClass.driver.SetSelected([])
  1937. self.polycoords = []
  1938. self.UpdateMap(render=False)
  1939. self.redrawAll = True
  1940. self.Refresh()
  1941. event.Skip()
  1942. def OnMiddleDown(self, event):
  1943. """!
  1944. Middle mouse button pressed
  1945. """
  1946. self.mouse['begin'] = event.GetPositionTuple()[:]
  1947. digitToolbar = self.parent.toolbars['vdigit']
  1948. # digitization tool
  1949. if self.mouse["use"] == "pointer" and digitToolbar:
  1950. digitClass = self.parent.digit
  1951. if (digitToolbar.GetAction() == "addLine" and \
  1952. digitToolbar.GetAction('type') in ["line", "boundary"]) or \
  1953. digitToolbar.GetAction() == "editLine":
  1954. # add line or boundary -> remove last point from the line
  1955. try:
  1956. removed = self.polycoords.pop()
  1957. Debug.msg(4, "BufferedWindow.OnMiddleDown(): polycoords_poped=%s" % \
  1958. [removed,])
  1959. self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
  1960. except:
  1961. pass
  1962. if digitToolbar.GetAction() == "editLine":
  1963. # remove last vertex & line
  1964. if len(self.vdigitMove['id']) > 1:
  1965. self.vdigitMove['id'].pop()
  1966. self.UpdateMap(render=False, renderVector=False)
  1967. elif digitToolbar.GetAction() in ["deleteLine", "moveLine", "splitLine",
  1968. "addVertex", "removeVertex", "moveVertex",
  1969. "copyCats", "flipLine", "mergeLine",
  1970. "snapLine", "connectLine", "copyLine",
  1971. "queryLine", "breakLine", "typeConv"]:
  1972. # varios tools -> unselected selected features
  1973. digitClass.driver.SetSelected([])
  1974. if digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  1975. hasattr(self, "vdigitMove"):
  1976. del self.vdigitMove
  1977. elif digitToolbar.GetAction() == "copyCats":
  1978. try:
  1979. del self.copyCatsList
  1980. del self.copyCatsIds
  1981. except AttributeError:
  1982. pass
  1983. elif digitToolbar.GetAction() == "copyLine":
  1984. del self.copyIds
  1985. if self.layerTmp:
  1986. self.Map.DeleteLayer(self.layerTmp)
  1987. self.UpdateMap(render=True, renderVector=False)
  1988. del self.layerTmp
  1989. self.polycoords = []
  1990. self.UpdateMap(render=False) # render vector
  1991. elif digitToolbar.GetAction() == "zbulkLine":
  1992. # reset polyline
  1993. self.polycoords = []
  1994. digitClass.driver.SetSelected([])
  1995. self.UpdateMap(render=False)
  1996. self.redrawAll = True
  1997. def OnMiddleUp(self, event):
  1998. """!
  1999. Middle mouse button released
  2000. """
  2001. self.mouse['end'] = event.GetPositionTuple()[:]
  2002. # set region in zoom or pan
  2003. begin = self.mouse['begin']
  2004. end = self.mouse['end']
  2005. self.Zoom(begin, end, 0) # no zoom
  2006. # redraw map
  2007. self.UpdateMap(render=True)
  2008. # update statusbar
  2009. self.parent.StatusbarUpdate()
  2010. def OnMouseEnter(self, event):
  2011. """!
  2012. Mouse entered window and no mouse buttons were pressed
  2013. """
  2014. if self.parent.GetLayerManager().gcpmanagement:
  2015. if self.parent.toolbars['gcpdisp']:
  2016. if not self.parent.MapWindow == self:
  2017. self.parent.MapWindow = self
  2018. self.parent.Map = self.Map
  2019. self.parent.UpdateActive(self)
  2020. # needed for wingrass
  2021. self.SetFocus()
  2022. else:
  2023. event.Skip()
  2024. def OnMouseMoving(self, event):
  2025. """!
  2026. Motion event and no mouse buttons were pressed
  2027. """
  2028. digitToolbar = self.parent.toolbars['vdigit']
  2029. if self.mouse["use"] == "pointer" and digitToolbar:
  2030. digitClass = self.parent.digit
  2031. self.mouse['end'] = event.GetPositionTuple()[:]
  2032. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  2033. (self.mouse['end'][0], self.mouse['end'][1]))
  2034. if digitToolbar.GetAction() == "addLine" and digitToolbar.GetAction('type') in ["line", "boundary"]:
  2035. if len(self.polycoords) > 0:
  2036. self.MouseDraw(pdc=self.pdcTmp, begin=self.Cell2Pixel(self.polycoords[-1]))
  2037. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] \
  2038. and hasattr(self, "vdigitMove"):
  2039. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  2040. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  2041. if len(self.vdigitMove['id']) > 0:
  2042. # draw lines on new position
  2043. if digitToolbar.GetAction() == "moveLine":
  2044. # move line
  2045. for id in self.vdigitMove['id']:
  2046. self.pdcTmp.TranslateId(id, dx, dy)
  2047. elif digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  2048. # move vertex ->
  2049. # (vertex, left vertex, left line,
  2050. # right vertex, right line)
  2051. # do not draw static lines
  2052. if digitToolbar.GetAction() == "moveVertex":
  2053. self.polycoords = []
  2054. ### self.pdcTmp.TranslateId(self.vdigitMove['id'][0], dx, dy)
  2055. self.pdcTmp.RemoveId(self.vdigitMove['id'][0])
  2056. if self.vdigitMove['id'][1] > 0: # previous vertex
  2057. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][1])[0:2])
  2058. self.pdcTmp.RemoveId(self.vdigitMove['id'][1]+1)
  2059. self.polycoords.append((x, y))
  2060. ### x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][0])[0:2])
  2061. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  2062. if self.vdigitMove['id'][2] > 0: # next vertex
  2063. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][2])[0:2])
  2064. self.pdcTmp.RemoveId(self.vdigitMove['id'][2]-1)
  2065. self.polycoords.append((x, y))
  2066. self.ClearLines(pdc=self.pdcTmp)
  2067. self.DrawLines(pdc=self.pdcTmp)
  2068. else: # edit line
  2069. try:
  2070. if self.vdigitMove['id'][-1] > 0: # previous vertex
  2071. self.MouseDraw(pdc=self.pdcTmp,
  2072. begin=self.Cell2Pixel(self.polycoords[-1]))
  2073. except: # no line
  2074. self.vdigitMove['id'] = []
  2075. self.polycoords = []
  2076. self.Refresh() # TODO: use RefreshRect()
  2077. self.mouse['begin'] = self.mouse['end']
  2078. elif digitToolbar.GetAction() == "zbulkLine":
  2079. if len(self.polycoords) == 1:
  2080. # draw mouse moving
  2081. self.MouseDraw(self.pdcTmp)
  2082. event.Skip()
  2083. def ClearLines(self, pdc=None):
  2084. """!
  2085. Clears temporary drawn lines from PseudoDC
  2086. """
  2087. if not pdc:
  2088. pdc=self.pdcTmp
  2089. try:
  2090. pdc.ClearId(self.lineid)
  2091. pdc.RemoveId(self.lineid)
  2092. except:
  2093. pass
  2094. try:
  2095. pdc.ClearId(self.plineid)
  2096. pdc.RemoveId(self.plineid)
  2097. except:
  2098. pass
  2099. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  2100. (self.lineid, self.plineid))
  2101. ### self.Refresh()
  2102. return True
  2103. def Pixel2Cell(self, (x, y)):
  2104. """!Convert image coordinates to real word coordinates
  2105. @param x, y image coordinates
  2106. @return easting, northing
  2107. @return None on error
  2108. """
  2109. try:
  2110. x = int(x)
  2111. y = int(y)
  2112. except:
  2113. return None
  2114. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  2115. res = self.Map.region["ewres"]
  2116. else:
  2117. res = self.Map.region["nsres"]
  2118. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  2119. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  2120. east = w + x * res
  2121. north = n - y * res
  2122. return (east, north)
  2123. def Cell2Pixel(self, (east, north)):
  2124. """!Convert real word coordinates to image coordinates
  2125. """
  2126. try:
  2127. east = float(east)
  2128. north = float(north)
  2129. except:
  2130. return None
  2131. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  2132. res = self.Map.region["ewres"]
  2133. else:
  2134. res = self.Map.region["nsres"]
  2135. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  2136. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  2137. x = (east - w) / res
  2138. y = (n - north) / res
  2139. return (x, y)
  2140. def Zoom(self, begin, end, zoomtype):
  2141. """!
  2142. Calculates new region while (un)zoom/pan-ing
  2143. """
  2144. x1, y1 = begin
  2145. x2, y2 = end
  2146. newreg = {}
  2147. # threshold - too small squares do not make sense
  2148. # can only zoom to windows of > 5x5 screen pixels
  2149. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  2150. if x1 > x2:
  2151. x1, x2 = x2, x1
  2152. if y1 > y2:
  2153. y1, y2 = y2, y1
  2154. # zoom in
  2155. if zoomtype > 0:
  2156. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  2157. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  2158. # zoom out
  2159. elif zoomtype < 0:
  2160. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  2161. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  2162. (self.Map.width - x2),
  2163. self.Map.height + 2 * \
  2164. (self.Map.height - y2)))
  2165. # pan
  2166. elif zoomtype == 0:
  2167. dx = x1 - x2
  2168. dy = y1 - y2
  2169. if dx == 0 and dy == 0:
  2170. dx = x1 - self.Map.width / 2
  2171. dy = y1 - self.Map.height / 2
  2172. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  2173. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  2174. self.Map.height + dy))
  2175. # if new region has been calculated, set the values
  2176. if newreg != {}:
  2177. # LL locations
  2178. if self.parent.Map.projinfo['proj'] == 'll':
  2179. if newreg['n'] > 90.0:
  2180. newreg['n'] = 90.0
  2181. if newreg['s'] < -90.0:
  2182. newreg['s'] = -90.0
  2183. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  2184. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  2185. if hasattr(self, "vdigitMove"):
  2186. # xo = self.Cell2Pixel((self.Map.region['center_easting'], self.Map.region['center_northing']))
  2187. # xn = self.Cell2Pixel(ce, cn))
  2188. tmp = self.Pixel2Cell(self.mouse['end'])
  2189. # calculate new center point and display resolution
  2190. self.Map.region['center_easting'] = ce
  2191. self.Map.region['center_northing'] = cn
  2192. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  2193. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  2194. self.Map.AlignExtentFromDisplay()
  2195. if hasattr(self, "vdigitMove"):
  2196. tmp1 = self.mouse['end']
  2197. tmp2 = self.Cell2Pixel(self.vdigitMove['begin'])
  2198. dx = tmp1[0] - tmp2[0]
  2199. dy = tmp1[1] - tmp2[1]
  2200. self.vdigitMove['beginDiff'] = (dx, dy)
  2201. for id in self.vdigitMove['id']:
  2202. self.pdcTmp.RemoveId(id)
  2203. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2204. self.Map.region['e'], self.Map.region['w'])
  2205. if self.redrawAll is False:
  2206. self.redrawAll = True
  2207. def ZoomBack(self):
  2208. """!Zoom to previous extents in zoomhistory list
  2209. """
  2210. zoom = list()
  2211. if len(self.zoomhistory) > 1:
  2212. self.zoomhistory.pop()
  2213. zoom = self.zoomhistory[-1]
  2214. # disable tool if stack is empty
  2215. if len(self.zoomhistory) < 2: # disable tool
  2216. if self.parent.GetName() == 'MapWindow':
  2217. toolbar = self.parent.toolbars['map']
  2218. elif self.parent.GetName() == 'GRMapWindow':
  2219. toolbar = self.parent.toolbars['georect']
  2220. elif self.parent.GetName() == 'GCPMapWindow':
  2221. toolbar = self.parent.toolbars['gcpdisp']
  2222. toolbar.Enable('zoomback', enable = False)
  2223. # zoom to selected region
  2224. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  2225. e = zoom[2], w = zoom[3],
  2226. update = True)
  2227. # update map
  2228. self.UpdateMap()
  2229. # update statusbar
  2230. self.parent.StatusbarUpdate()
  2231. def ZoomHistory(self, n, s, e, w):
  2232. """!
  2233. Manages a list of last 10 zoom extents
  2234. @param n,s,e,w north, south, east, west
  2235. @return removed history item if exists (or None)
  2236. """
  2237. removed = None
  2238. self.zoomhistory.append((n,s,e,w))
  2239. if len(self.zoomhistory) > 10:
  2240. removed = self.zoomhistory.pop(0)
  2241. if removed:
  2242. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  2243. (self.zoomhistory, removed))
  2244. else:
  2245. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  2246. (self.zoomhistory))
  2247. # update toolbar
  2248. if len(self.zoomhistory) > 1:
  2249. enable = True
  2250. else:
  2251. enable = False
  2252. if self.parent.GetName() == 'MapWindow':
  2253. toolbar = self.parent.toolbars['map']
  2254. elif self.parent.GetName() == 'GRMapWindow':
  2255. toolbar = self.parent.toolbars['georect']
  2256. elif self.parent.GetName() == 'GCPMapWindow':
  2257. toolbar = self.parent.toolbars['gcpdisp']
  2258. toolbar.Enable('zoomback', enable)
  2259. return removed
  2260. def ResetZoomHistory(self):
  2261. """!Reset zoom history"""
  2262. self.zoomhistory = list()
  2263. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  2264. """!
  2265. Set display extents to match selected raster
  2266. or vector map(s).
  2267. @param layer list of layers to be zoom to
  2268. @param ignoreNulls True to ignore null-values
  2269. @param render True to re-render display
  2270. """
  2271. zoomreg = {}
  2272. if not layers:
  2273. layers = self.GetSelectedLayer(multi = True)
  2274. if not layers:
  2275. return
  2276. rast = []
  2277. vect = []
  2278. updated = False
  2279. for l in layers:
  2280. # only raster/vector layers are currently supported
  2281. if l.type == 'raster':
  2282. rast.append(l.name)
  2283. elif l.type == 'vector':
  2284. digitToolbar = self.parent.toolbars['vdigit']
  2285. if digitToolbar and digitToolbar.GetLayer() == l:
  2286. w, s, b, e, n, t = self.parent.digit.driver.GetMapBoundingBox()
  2287. self.Map.GetRegion(n=n, s=s, w=w, e=e,
  2288. update=True)
  2289. updated = True
  2290. else:
  2291. vect.append(l.name)
  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))