mapdisp_window.py 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934
  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. try:
  627. if render:
  628. # update display size
  629. self.Map.ChangeMapSize(self.GetClientSize())
  630. if self.parent.statusbarWin['resolution'].IsChecked():
  631. # use computation region resolution for rendering
  632. windres = True
  633. else:
  634. windres = False
  635. self.mapfile = self.Map.Render(force = True, mapWindow = self.parent,
  636. windres = windres)
  637. else:
  638. self.mapfile = self.Map.Render(force = False, mapWindow = self.parent)
  639. except gcmd.GException, e:
  640. gcmd.GError(message = e)
  641. self.mapfile = None
  642. self.img = self.GetImage() # id=99
  643. #
  644. # clear pseudoDcs
  645. #
  646. for pdc in (self.pdc,
  647. self.pdcDec,
  648. self.pdcTmp):
  649. pdc.Clear()
  650. pdc.RemoveAll()
  651. #
  652. # draw background map image to PseudoDC
  653. #
  654. if not self.img:
  655. self.Draw(self.pdc, pdctype='clear')
  656. else:
  657. try:
  658. id = self.imagedict[self.img]['id']
  659. except:
  660. return False
  661. self.Draw(self.pdc, self.img, drawid=id)
  662. #
  663. # render vector map layer
  664. #
  665. digitToolbar = self.parent.toolbars['vdigit']
  666. if renderVector and digitToolbar and \
  667. digitToolbar.GetLayer():
  668. # set region
  669. self.parent.digit.driver.UpdateRegion()
  670. # re-calculate threshold for digitization tool
  671. self.parent.digit.driver.GetThreshold()
  672. # draw map
  673. if self.pdcVector:
  674. self.pdcVector.Clear()
  675. self.pdcVector.RemoveAll()
  676. try:
  677. item = self.tree.FindItemByData('maplayer', digitToolbar.GetLayer())
  678. except TypeError:
  679. item = None
  680. if item and self.tree.IsItemChecked(item):
  681. self.parent.digit.driver.DrawMap()
  682. # translate tmp objects (pointer position)
  683. if digitToolbar.GetAction() == 'moveLine':
  684. if hasattr(self, "vdigitMove") and \
  685. self.vdigitMove.has_key('beginDiff'):
  686. # move line
  687. for id in self.vdigitMove['id']:
  688. self.pdcTmp.TranslateId(id,
  689. self.vdigitMove['beginDiff'][0],
  690. self.vdigitMove['beginDiff'][1])
  691. del self.vdigitMove['beginDiff']
  692. #
  693. # render overlays
  694. #
  695. for img in self.GetOverlay():
  696. # draw any active and defined overlays
  697. if self.imagedict[img]['layer'].IsActive():
  698. id = self.imagedict[img]['id']
  699. self.Draw(self.pdc, img=img, drawid=id,
  700. pdctype=self.overlays[id]['pdcType'], coords=self.overlays[id]['coords'])
  701. for id in self.textdict.keys():
  702. self.Draw(self.pdc, img=self.textdict[id], drawid=id,
  703. pdctype='text', coords=[10, 10, 10, 10])
  704. # optionally draw computational extent box
  705. self.DrawCompRegionExtent()
  706. #
  707. # redraw pdcTmp if needed
  708. #
  709. if len(self.polycoords) > 0:
  710. self.DrawLines(self.pdcTmp)
  711. if not self.parent.IsStandalone() and \
  712. self.parent.GetLayerManager().georectifying:
  713. # -> georectifier (redraw GCPs)
  714. if self.parent.toolbars['georect']:
  715. coordtype = 'gcpcoord'
  716. else:
  717. coordtype = 'mapcoord'
  718. self.parent.GetLayerManager().georectifying.DrawGCP(coordtype)
  719. if not self.parent.IsStandalone() and \
  720. self.parent.GetLayerManager().gcpmanagement:
  721. # -> georectifier (redraw GCPs)
  722. if self.parent.toolbars['gcpdisp']:
  723. if self == self.parent.TgtMapWindow:
  724. coordtype = 'target'
  725. else:
  726. coordtype = 'source'
  727. self.parent.DrawGCP(coordtype)
  728. #
  729. # clear measurement
  730. #
  731. if self.mouse["use"] == "measure":
  732. self.ClearLines(pdc=self.pdcTmp)
  733. self.polycoords = []
  734. self.mouse['use'] = 'pointer'
  735. self.mouse['box'] = 'point'
  736. self.mouse['end'] = [0, 0]
  737. self.SetCursor(self.parent.cursors["default"])
  738. stop = time.clock()
  739. #
  740. # hide process bar
  741. #
  742. self.parent.statusbarWin['progress'].Hide()
  743. #
  744. # update statusbar
  745. #
  746. ### self.Map.SetRegion()
  747. self.parent.StatusbarUpdate()
  748. if grass.find_file(name = 'MASK', element = 'cell')['name']:
  749. # mask found
  750. self.parent.statusbarWin['mask'].SetLabel(_('MASK'))
  751. else:
  752. self.parent.statusbarWin['mask'].SetLabel('')
  753. Debug.msg (2, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  754. (render, renderVector, (stop-start)))
  755. return True
  756. def DrawCompRegionExtent(self):
  757. """!
  758. Draw computational region extent in the display
  759. Display region is drawn as a blue box inside the computational region,
  760. computational region inside a display region as a red box).
  761. """
  762. if hasattr(self, "regionCoords"):
  763. compReg = self.Map.GetRegion()
  764. dispReg = self.Map.GetCurrentRegion()
  765. reg = None
  766. if self.IsInRegion(dispReg, compReg):
  767. self.polypen = wx.Pen(colour=wx.Colour(0, 0, 255, 128), width=3, style=wx.SOLID)
  768. reg = dispReg
  769. else:
  770. self.polypen = wx.Pen(colour=wx.Colour(255, 0, 0, 128),
  771. width=3, style=wx.SOLID)
  772. reg = compReg
  773. self.regionCoords = []
  774. self.regionCoords.append((reg['w'], reg['n']))
  775. self.regionCoords.append((reg['e'], reg['n']))
  776. self.regionCoords.append((reg['e'], reg['s']))
  777. self.regionCoords.append((reg['w'], reg['s']))
  778. self.regionCoords.append((reg['w'], reg['n']))
  779. # draw region extent
  780. self.DrawLines(pdc=self.pdcDec, polycoords=self.regionCoords)
  781. def IsInRegion(self, region, refRegion):
  782. """!
  783. Test if 'region' is inside of 'refRegion'
  784. @param region input region
  785. @param refRegion reference region (e.g. computational region)
  786. @return True if region is inside of refRegion
  787. @return False
  788. """
  789. if region['s'] >= refRegion['s'] and \
  790. region['n'] <= refRegion['n'] and \
  791. region['w'] >= refRegion['w'] and \
  792. region['e'] <= refRegion['e']:
  793. return True
  794. return False
  795. def EraseMap(self):
  796. """!
  797. Erase the canvas
  798. """
  799. self.Draw(self.pdc, pdctype='clear')
  800. if self.pdcVector:
  801. self.Draw(self.pdcVector, pdctype='clear')
  802. self.Draw(self.pdcDec, pdctype='clear')
  803. self.Draw(self.pdcTmp, pdctype='clear')
  804. def DragMap(self, moveto):
  805. """!
  806. Drag the entire map image for panning.
  807. @param moveto dx,dy
  808. """
  809. dc = wx.BufferedDC(wx.ClientDC(self))
  810. dc.SetBackground(wx.Brush("White"))
  811. dc.Clear()
  812. self.dragimg = wx.DragImage(self.buffer)
  813. self.dragimg.BeginDrag((0, 0), self)
  814. self.dragimg.GetImageRect(moveto)
  815. self.dragimg.Move(moveto)
  816. self.dragimg.DoDrawImage(dc, moveto)
  817. self.dragimg.EndDrag()
  818. def DragItem(self, id, event):
  819. """!
  820. Drag an overlay decoration item
  821. """
  822. if id == 99 or id == '' or id == None: return
  823. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  824. x, y = self.lastpos
  825. dx = event.GetX() - x
  826. dy = event.GetY() - y
  827. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  828. r = self.pdc.GetIdBounds(id)
  829. ### FIXME in vdigit/pseudodc.i
  830. if type(r) is list:
  831. r = wx.Rect(r[0], r[1], r[2], r[3])
  832. if id > 100: # text dragging
  833. rtop = (r[0],r[1]-r[3],r[2],r[3])
  834. r = r.Union(rtop)
  835. rleft = (r[0]-r[2],r[1],r[2],r[3])
  836. r = r.Union(rleft)
  837. self.pdc.TranslateId(id, dx, dy)
  838. r2 = self.pdc.GetIdBounds(id)
  839. if type(r2) is list:
  840. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  841. if id > 100: # text
  842. self.textdict[id]['coords'] = r2
  843. r = r.Union(r2)
  844. r.Inflate(4,4)
  845. self.RefreshRect(r, False)
  846. self.lastpos = (event.GetX(), event.GetY())
  847. def MouseDraw(self, pdc=None, begin=None, end=None):
  848. """!
  849. Mouse box or line from 'begin' to 'end'
  850. If not given from self.mouse['begin'] to self.mouse['end'].
  851. """
  852. # self.redrawAll = False
  853. if not pdc:
  854. return
  855. if begin is None:
  856. begin = self.mouse['begin']
  857. if end is None:
  858. end = self.mouse['end']
  859. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  860. (self.mouse['use'], self.mouse['box'],
  861. begin[0], begin[1], end[0], end[1]))
  862. if self.mouse['box'] == "box":
  863. boxid = wx.ID_NEW
  864. mousecoords = [begin[0], begin[1],
  865. end[0], end[1]]
  866. r = pdc.GetIdBounds(boxid)
  867. if type(r) is list:
  868. r = wx.Rect(r[0], r[1], r[2], r[3])
  869. r.Inflate(4, 4)
  870. try:
  871. pdc.ClearId(boxid)
  872. except:
  873. pass
  874. self.RefreshRect(r, False)
  875. pdc.SetId(boxid)
  876. self.Draw(pdc, drawid=boxid, pdctype='box', coords=mousecoords)
  877. elif self.mouse['box'] == "line" or self.mouse['box'] == 'point':
  878. self.lineid = wx.ID_NEW
  879. mousecoords = [begin[0], begin[1], \
  880. end[0], end[1]]
  881. x1=min(begin[0],end[0])
  882. x2=max(begin[0],end[0])
  883. y1=min(begin[1],end[1])
  884. y2=max(begin[1],end[1])
  885. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  886. r.Inflate(4,4)
  887. try:
  888. pdc.ClearId(self.lineid)
  889. except:
  890. pass
  891. self.RefreshRect(r, False)
  892. pdc.SetId(self.lineid)
  893. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=mousecoords)
  894. def DrawLines(self, pdc=None, polycoords=None):
  895. """!
  896. Draw polyline in PseudoDC
  897. Set self.pline to wx.NEW_ID + 1
  898. polycoords - list of polyline vertices, geographical coordinates
  899. (if not given, self.polycoords is used)
  900. """
  901. if not pdc:
  902. pdc = self.pdcTmp
  903. if not polycoords:
  904. polycoords = self.polycoords
  905. if len(polycoords) > 0:
  906. self.plineid = wx.ID_NEW + 1
  907. # convert from EN to XY
  908. coords = []
  909. for p in polycoords:
  910. coords.append(self.Cell2Pixel(p))
  911. self.Draw(pdc, drawid=self.plineid, pdctype='polyline', coords=coords)
  912. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  913. (coords, self.plineid))
  914. return self.plineid
  915. return -1
  916. def DrawCross(self, pdc, coords, size, rotation=0,
  917. text=None, textAlign='lr', textOffset=(5, 5)):
  918. """!Draw cross in PseudoDC
  919. @todo implement rotation
  920. @param pdc PseudoDC
  921. @param coord center coordinates
  922. @param rotation rotate symbol
  923. @param text draw also text (text, font, color, rotation)
  924. @param textAlign alignment (default 'lower-right')
  925. @textOffset offset for text (from center point)
  926. """
  927. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  928. (pdc, coords, size))
  929. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  930. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  931. self.lineid = wx.NewId()
  932. for lineCoords in coordsCross:
  933. self.Draw(pdc, drawid=self.lineid, pdctype='line', coords=lineCoords)
  934. if not text:
  935. return self.lineid
  936. if textAlign == 'ul':
  937. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  938. elif textAlign == 'ur':
  939. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  940. elif textAlign == 'lr':
  941. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  942. else:
  943. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  944. self.Draw(pdc, img=text,
  945. pdctype='text', coords=coord)
  946. return self.lineid
  947. def MouseActions(self, event):
  948. """!
  949. Mouse motion and button click notifier
  950. """
  951. if not self.processMouse:
  952. return
  953. ### if self.redrawAll is False:
  954. ### self.redrawAll = True
  955. # zoom with mouse wheel
  956. if event.GetWheelRotation() != 0:
  957. self.OnMouseWheel(event)
  958. # left mouse button pressed
  959. elif event.LeftDown():
  960. self.OnLeftDown(event)
  961. # left mouse button released
  962. elif event.LeftUp():
  963. self.OnLeftUp(event)
  964. # dragging
  965. elif event.Dragging():
  966. self.OnDragging(event)
  967. # double click
  968. elif event.ButtonDClick():
  969. self.OnButtonDClick(event)
  970. # middle mouse button pressed
  971. elif event.MiddleDown():
  972. self.OnMiddleDown(event)
  973. # middle mouse button relesed
  974. elif event.MiddleUp():
  975. self.OnMiddleUp(event)
  976. # right mouse button pressed
  977. elif event.RightDown():
  978. self.OnRightDown(event)
  979. # right mouse button released
  980. elif event.RightUp():
  981. self.OnRightUp(event)
  982. elif event.Entering():
  983. self.OnMouseEnter(event)
  984. elif event.Moving():
  985. self.OnMouseMoving(event)
  986. # event.Skip()
  987. def OnMouseWheel(self, event):
  988. """!
  989. Mouse wheel moved
  990. """
  991. self.processMouse = False
  992. current = event.GetPositionTuple()[:]
  993. wheel = event.GetWheelRotation()
  994. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  995. # zoom 1/2 of the screen, centered to current mouse position (TODO: settings)
  996. begin = (current[0] - self.Map.width / 4,
  997. current[1] - self.Map.height / 4)
  998. end = (current[0] + self.Map.width / 4,
  999. current[1] + self.Map.height / 4)
  1000. if wheel > 0:
  1001. zoomtype = 1
  1002. else:
  1003. zoomtype = -1
  1004. # zoom
  1005. self.Zoom(begin, end, zoomtype)
  1006. # redraw map
  1007. self.UpdateMap()
  1008. ### self.OnPaint(None)
  1009. # update statusbar
  1010. self.parent.StatusbarUpdate()
  1011. self.Refresh()
  1012. self.processMouse = True
  1013. # event.Skip()
  1014. def OnDragging(self, event):
  1015. """!
  1016. Mouse dragging with left button down
  1017. """
  1018. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  1019. current = event.GetPositionTuple()[:]
  1020. previous = self.mouse['begin']
  1021. move = (current[0] - previous[0],
  1022. current[1] - previous[1])
  1023. digitToolbar = self.parent.toolbars['vdigit']
  1024. # dragging or drawing box with left button
  1025. if self.mouse['use'] == 'pan' or \
  1026. event.MiddleIsDown():
  1027. self.DragMap(move)
  1028. # dragging decoration overlay item
  1029. elif (self.mouse['use'] == 'pointer' and
  1030. not digitToolbar and
  1031. self.dragid != None):
  1032. self.DragItem(self.dragid, event)
  1033. # dragging anything else - rubber band box or line
  1034. else:
  1035. if (self.mouse['use'] == 'pointer' and
  1036. not digitToolbar): return
  1037. self.mouse['end'] = event.GetPositionTuple()[:]
  1038. digitClass = self.parent.digit
  1039. if (event.LeftIsDown() and
  1040. not (digitToolbar and
  1041. digitToolbar.GetAction() in ("moveLine",) and
  1042. digitClass.driver.GetSelected() > 0)):
  1043. # draw box only when left mouse button is pressed
  1044. self.MouseDraw(pdc=self.pdcTmp)
  1045. # event.Skip()
  1046. def OnLeftDownVDigitAddLine(self, event):
  1047. """!
  1048. Left mouse button down - vector digitizer add new line
  1049. action
  1050. """
  1051. digitToolbar = self.parent.toolbars['vdigit']
  1052. digitClass = self.parent.digit
  1053. try:
  1054. mapLayer = digitToolbar.GetLayer().GetName()
  1055. except:
  1056. return
  1057. if digitToolbar.GetAction('type') in ["point", "centroid"]:
  1058. # add new point
  1059. if digitToolbar.GetAction('type') == 'point':
  1060. point = True
  1061. else:
  1062. point = False
  1063. east, north = self.Pixel2Cell(self.mouse['begin'])
  1064. fid = digitClass.AddPoint(mapLayer, point, east, north)
  1065. if fid < 0:
  1066. return
  1067. self.UpdateMap(render=False) # redraw map
  1068. # add new record into atribute table
  1069. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') is True:
  1070. # select attributes based on layer and category
  1071. cats = { fid : {
  1072. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  1073. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  1074. }}
  1075. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1076. self.mouse['end'][1] + self.dialogOffset))
  1077. addRecordDlg = dbm_dialogs.DisplayAttributesDialog(parent=self, map=mapLayer,
  1078. cats=cats,
  1079. pos=posWindow,
  1080. action="add")
  1081. if not point:
  1082. self.__geomAttrb(fid, addRecordDlg, 'area', digitClass,
  1083. digitToolbar.GetLayer())
  1084. self.__geomAttrb(fid, addRecordDlg, 'perimeter', digitClass,
  1085. digitToolbar.GetLayer())
  1086. if addRecordDlg.mapDBInfo and \
  1087. addRecordDlg.ShowModal() == wx.ID_OK:
  1088. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1089. for sql in addRecordDlg.GetSQLString():
  1090. sqlfile.file.write(sql + ";\n")
  1091. sqlfile.file.flush()
  1092. gcmd.RunCommand('db.execute',
  1093. parent = self,
  1094. quiet = True,
  1095. input = sqlfile.name)
  1096. if addRecordDlg.mapDBInfo:
  1097. self.__updateATM()
  1098. elif digitToolbar.GetAction('type') in ["line", "boundary"]:
  1099. # add new point to the line
  1100. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1101. self.DrawLines(pdc=self.pdcTmp)
  1102. def __geomAttrb(self, fid, dialog, attrb, digit, mapLayer):
  1103. """!Trac geometry attributes?"""
  1104. item = self.tree.FindItemByData('maplayer', mapLayer)
  1105. vdigit = self.tree.GetPyData(item)[0]['vdigit']
  1106. if vdigit and \
  1107. vdigit.has_key('geomAttr') and \
  1108. vdigit['geomAttr'].has_key(attrb):
  1109. val = -1
  1110. if attrb == 'length':
  1111. val = digit.GetLineLength(fid)
  1112. type = attrb
  1113. elif attrb == 'area':
  1114. val = digit.GetAreaSize(fid)
  1115. type = attrb
  1116. elif attrb == 'perimeter':
  1117. val = digit.GetAreaPerimeter(fid)
  1118. type = 'length'
  1119. if val > 0:
  1120. layer = int(UserSettings.Get(group='vdigit', key="layer", subkey='value'))
  1121. column = vdigit['geomAttr'][attrb]['column']
  1122. val = UnitsConvertValue(val, type, vdigit['geomAttr'][attrb]['units'])
  1123. dialog.SetColumnValue(layer, column, val)
  1124. dialog.OnReset()
  1125. def __geomAttrbUpdate(self, fids):
  1126. """!Update geometry atrributes of currently selected features
  1127. @param fid list feature id
  1128. """
  1129. mapLayer = self.parent.toolbars['vdigit'].GetLayer()
  1130. vectorName = mapLayer.GetName()
  1131. digit = self.parent.digit
  1132. item = self.tree.FindItemByData('maplayer', mapLayer)
  1133. vdigit = self.tree.GetPyData(item)[0]['vdigit']
  1134. if vdigit is None or not vdigit.has_key('geomAttr'):
  1135. return
  1136. dbInfo = gselect.VectorDBInfo(vectorName)
  1137. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1138. for fid in fids:
  1139. for layer, cats in digit.GetLineCats(fid).iteritems():
  1140. table = dbInfo.GetTable(layer)
  1141. for attrb, item in vdigit['geomAttr'].iteritems():
  1142. val = -1
  1143. if attrb == 'length':
  1144. val = digit.GetLineLength(fid)
  1145. type = attrb
  1146. elif attrb == 'area':
  1147. val = digit.GetAreaSize(fid)
  1148. type = attrb
  1149. elif attrb == 'perimeter':
  1150. val = digit.GetAreaPerimeter(fid)
  1151. type = 'length'
  1152. if val < 0:
  1153. continue
  1154. val = UnitsConvertValue(val, type, item['units'])
  1155. for cat in cats:
  1156. sqlfile.write('UPDATE %s SET %s = %f WHERE %s = %d;\n' % \
  1157. (table, item['column'], val,
  1158. dbInfo.GetKeyColumn(layer), cat))
  1159. sqlfile.file.flush()
  1160. gcmd.RunCommand('db.execute',
  1161. parent = True,
  1162. quiet = True,
  1163. input = sqlfile.name)
  1164. def __updateATM(self):
  1165. """!Update open Attribute Table Manager
  1166. @todo: use AddDataRow() instead
  1167. """
  1168. # update ATM
  1169. digitToolbar = self.parent.toolbars['vdigit']
  1170. digitVector = digitToolbar.GetLayer().GetName()
  1171. for atm in self.lmgr.dialogs['atm']:
  1172. atmVector = atm.GetVectorName()
  1173. if atmVector == digitVector:
  1174. layer = UserSettings.Get(group='vdigit', key="layer", subkey='value')
  1175. # TODO: use AddDataRow instead
  1176. atm.LoadData(layer)
  1177. def OnLeftDownVDigitEditLine(self, event):
  1178. """!
  1179. Left mouse button down - vector digitizer edit linear feature
  1180. - add new vertex.
  1181. """
  1182. digitToolbar = self.parent.toolbars['vdigit']
  1183. digitClass = self.parent.digit
  1184. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  1185. self.vdigitMove['id'].append(wx.NewId())
  1186. self.DrawLines(pdc=self.pdcTmp)
  1187. def OnLeftDownVDigitMoveLine(self, event):
  1188. """!
  1189. Left mouse button down - vector digitizer move feature/vertex,
  1190. edit linear feature
  1191. """
  1192. digitToolbar = self.parent.toolbars['vdigit']
  1193. digitClass = self.parent.digit
  1194. self.vdigitMove = {}
  1195. # geographic coordinates of initial position (left-down)
  1196. self.vdigitMove['begin'] = None
  1197. # list of ids to modify
  1198. self.vdigitMove['id'] = []
  1199. # ids geographic coordinates
  1200. self.vdigitMove['coord'] = {}
  1201. if digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  1202. # set pen
  1203. pcolor = UserSettings.Get(group='vdigit', key="symbol",
  1204. subkey=["highlight", "color"])
  1205. self.pen = self.polypen = wx.Pen(colour=pcolor,
  1206. width=2, style=wx.SHORT_DASH)
  1207. self.pdcTmp.SetPen(self.polypen)
  1208. def OnLeftDownVDigitDisplayCA(self, event):
  1209. """!
  1210. Left mouse button down - vector digitizer display categories
  1211. or attributes action
  1212. """
  1213. digitToolbar = self.parent.toolbars['vdigit']
  1214. digitClass = self.parent.digit
  1215. try:
  1216. mapLayer = digitToolbar.GetLayer().GetName()
  1217. except:
  1218. return
  1219. coords = self.Pixel2Cell(self.mouse['begin'])
  1220. # unselect
  1221. digitClass.driver.SetSelected([])
  1222. # select feature by point
  1223. cats = {}
  1224. if digitClass.driver.SelectLineByPoint(coords,
  1225. digitClass.GetSelectType()) is None:
  1226. return
  1227. if UserSettings.Get(group='vdigit', key='checkForDupl',
  1228. subkey='enabled'):
  1229. lines = digitClass.driver.GetSelected()
  1230. else:
  1231. lines = (digitClass.driver.GetSelected()[0],) # only first found
  1232. for line in lines:
  1233. cats[line] = digitClass.GetLineCats(line)
  1234. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1235. self.mouse['end'][1] + self.dialogOffset))
  1236. if digitToolbar.GetAction() == "displayAttrs":
  1237. # select attributes based on coordinates (all layers)
  1238. if self.parent.dialogs['attributes'] is None:
  1239. self.parent.dialogs['attributes'] = \
  1240. dbm_dialogs.DisplayAttributesDialog(parent=self, map=mapLayer,
  1241. cats=cats,
  1242. action="update")
  1243. else:
  1244. # upgrade dialog
  1245. self.parent.dialogs['attributes'].UpdateDialog(cats=cats)
  1246. if self.parent.dialogs['attributes']:
  1247. if len(cats.keys()) > 0:
  1248. # highlight feature & re-draw map
  1249. if not self.parent.dialogs['attributes'].IsShown():
  1250. self.parent.dialogs['attributes'].Show()
  1251. else:
  1252. if self.parent.dialogs['attributes'] and \
  1253. self.parent.dialogs['attributes'].IsShown():
  1254. self.parent.dialogs['attributes'].Hide()
  1255. else: # displayCats
  1256. if self.parent.dialogs['category'] is None:
  1257. # open new dialog
  1258. dlg = VDigitCategoryDialog(parent=self,
  1259. map=mapLayer,
  1260. cats=cats,
  1261. pos=posWindow,
  1262. title=_("Update categories"))
  1263. self.parent.dialogs['category'] = dlg
  1264. else:
  1265. # update currently open dialog
  1266. self.parent.dialogs['category'].UpdateDialog(cats=cats)
  1267. if self.parent.dialogs['category']:
  1268. if len(cats.keys()) > 0:
  1269. # highlight feature & re-draw map
  1270. if not self.parent.dialogs['category'].IsShown():
  1271. self.parent.dialogs['category'].Show()
  1272. else:
  1273. if self.parent.dialogs['category'].IsShown():
  1274. self.parent.dialogs['category'].Hide()
  1275. self.UpdateMap(render=False)
  1276. def OnLeftDownVDigitCopyCA(self, event):
  1277. """!
  1278. Left mouse button down - vector digitizer copy categories
  1279. or attributes action
  1280. """
  1281. digitToolbar = self.parent.toolbars['vdigit']
  1282. digitClass = self.parent.digit
  1283. if not hasattr(self, "copyCatsList"):
  1284. self.copyCatsList = []
  1285. else:
  1286. self.copyCatsIds = []
  1287. self.mouse['box'] = 'box'
  1288. def OnLeftDownVDigitCopyLine(self, event):
  1289. """!
  1290. Left mouse button down - vector digitizer copy lines action
  1291. """
  1292. digitToolbar = self.parent.toolbars['vdigit']
  1293. digitClass = self.parent.digit
  1294. if not hasattr(self, "copyIds"):
  1295. self.copyIds = []
  1296. self.layerTmp = None
  1297. def OnLeftDownVDigitBulkLine(self, event):
  1298. """!
  1299. Left mouse button down - vector digitizer label 3d vector
  1300. lines
  1301. """
  1302. digitToolbar = self.parent.toolbars['vdigit']
  1303. digitClass = self.parent.digit
  1304. if len(self.polycoords) > 1: # start new line
  1305. self.polycoords = []
  1306. self.ClearLines(pdc=self.pdcTmp)
  1307. self.polycoords.append(self.Pixel2Cell(event.GetPositionTuple()[:]))
  1308. if len(self.polycoords) == 1:
  1309. begin = self.Pixel2Cell(self.polycoords[-1])
  1310. end = self.Pixel2Cell(self.mouse['end'])
  1311. else:
  1312. end = self.Pixel2Cell(self.polycoords[-1])
  1313. begin = self.Pixel2Cell(self.mouse['begin'])
  1314. self.DrawLines(self.pdcTmp, polycoords = (begin, end))
  1315. def OnLeftDown(self, event):
  1316. """!
  1317. Left mouse button pressed
  1318. """
  1319. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  1320. self.mouse["use"])
  1321. self.mouse['begin'] = event.GetPositionTuple()[:]
  1322. if self.mouse["use"] in ["measure", "profile"]:
  1323. # measure or profile
  1324. if len(self.polycoords) == 0:
  1325. self.mouse['end'] = self.mouse['begin']
  1326. self.polycoords.append(self.Pixel2Cell(self.mouse['begin']))
  1327. self.ClearLines(pdc=self.pdcTmp)
  1328. else:
  1329. self.mouse['begin'] = self.mouse['end']
  1330. elif self.mouse['use'] == 'zoom':
  1331. pass
  1332. #
  1333. # vector digizer
  1334. #
  1335. elif self.mouse["use"] == "pointer" and \
  1336. self.parent.toolbars['vdigit']:
  1337. digitToolbar = self.parent.toolbars['vdigit']
  1338. digitClass = self.parent.digit
  1339. try:
  1340. mapLayer = digitToolbar.GetLayer().GetName()
  1341. except:
  1342. wx.MessageBox(parent=self,
  1343. message=_("No vector map selected for editing."),
  1344. caption=_("Vector digitizer"),
  1345. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1346. event.Skip()
  1347. return
  1348. if digitToolbar.GetAction() not in ("moveVertex",
  1349. "addVertex",
  1350. "removeVertex",
  1351. "editLine"):
  1352. # set pen
  1353. self.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  1354. self.polypen = wx.Pen(colour='dark green', width=2, style=wx.SOLID)
  1355. if digitToolbar.GetAction() in ("addVertex",
  1356. "removeVertex",
  1357. "splitLines"):
  1358. # unselect
  1359. digitClass.driver.SetSelected([])
  1360. if digitToolbar.GetAction() == "addLine":
  1361. self.OnLeftDownVDigitAddLine(event)
  1362. elif digitToolbar.GetAction() == "editLine" and \
  1363. hasattr(self, "vdigitMove"):
  1364. self.OnLeftDownVDigitEditLine(event)
  1365. elif digitToolbar.GetAction() in ("moveLine",
  1366. "moveVertex",
  1367. "editLine") and \
  1368. not hasattr(self, "vdigitMove"):
  1369. self.OnLeftDownVDigitMoveLine(event)
  1370. elif digitToolbar.GetAction() in ("displayAttrs"
  1371. "displayCats"):
  1372. self.OnLeftDownVDigitDisplayCA(event)
  1373. elif digitToolbar.GetAction() in ("copyCats",
  1374. "copyAttrs"):
  1375. self.OnLeftDownVDigitCopyCA(event)
  1376. elif digitToolbar.GetAction() == "copyLine":
  1377. self.OnLeftDownVDigitCopyLine(event)
  1378. elif digitToolbar.GetAction() == "zbulkLine":
  1379. self.OnLeftDownVDigitBulkLine(event)
  1380. elif self.mouse['use'] == 'pointer':
  1381. # get decoration or text id
  1382. self.idlist = []
  1383. self.dragid = ''
  1384. self.lastpos = self.mouse['begin']
  1385. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  1386. self.hitradius)
  1387. if 99 in idlist:
  1388. idlist.remove(99)
  1389. if idlist != []:
  1390. self.dragid = idlist[0] #drag whatever is on top
  1391. else:
  1392. pass
  1393. event.Skip()
  1394. def OnLeftUpVDigitVarious(self, event):
  1395. """!
  1396. Left mouse button up - vector digitizer various actions
  1397. """
  1398. digitToolbar = self.parent.toolbars['vdigit']
  1399. digitClass = self.parent.digit
  1400. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1401. pos2 = self.Pixel2Cell(self.mouse['end'])
  1402. nselected = 0
  1403. # -> delete line || move line || move vertex
  1404. if digitToolbar.GetAction() in ("moveVertex",
  1405. "editLine"):
  1406. if len(digitClass.driver.GetSelected()) == 0:
  1407. nselected = digitClass.driver.SelectLineByPoint(pos1, type=VDigit_Lines_Type)
  1408. if digitToolbar.GetAction() == "editLine":
  1409. try:
  1410. selVertex = digitClass.driver.GetSelectedVertex(pos1)[0]
  1411. except IndexError:
  1412. selVertex = None
  1413. if selVertex:
  1414. # self.UpdateMap(render=False)
  1415. ids = digitClass.driver.GetSelected(grassId=False)
  1416. # move this line to tmp layer
  1417. self.polycoords = []
  1418. for id in ids:
  1419. if id % 2: # register only vertices
  1420. e, n = self.Pixel2Cell(self.pdcVector.GetIdBounds(id)[0:2])
  1421. self.polycoords.append((e, n))
  1422. digitClass.driver.DrawSelected(False)
  1423. if selVertex < ids[-1] / 2:
  1424. # choose first or last node of line
  1425. self.vdigitMove['id'].reverse()
  1426. self.polycoords.reverse()
  1427. else:
  1428. # unselect
  1429. digitClass.driver.SetSelected([])
  1430. del self.vdigitMove
  1431. self.UpdateMap(render=False)
  1432. elif digitToolbar.GetAction() in ("copyCats",
  1433. "copyAttrs"):
  1434. if not hasattr(self, "copyCatsIds"):
  1435. # 'from' -> select by point
  1436. nselected = digitClass.driver.SelectLineByPoint(pos1, digitClass.GetSelectType())
  1437. if nselected:
  1438. self.copyCatsList = digitClass.driver.GetSelected()
  1439. else:
  1440. # -> 'to' -> select by bbox
  1441. digitClass.driver.SetSelected([])
  1442. # return number of selected features (by box/point)
  1443. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1444. digitClass.GetSelectType())
  1445. if nselected == 0:
  1446. if digitClass.driver.SelectLineByPoint(pos1,
  1447. digitClass.GetSelectType()) is not None:
  1448. nselected = 1
  1449. if nselected > 0:
  1450. self.copyCatsIds = digitClass.driver.GetSelected()
  1451. elif digitToolbar.GetAction() == "queryLine":
  1452. selected = digitClass.SelectLinesByQuery(pos1, pos2)
  1453. nselected = len(selected)
  1454. if nselected > 0:
  1455. digitClass.driver.SetSelected(selected)
  1456. else:
  1457. # -> moveLine || deleteLine, etc. (select by point/box)
  1458. if digitToolbar.GetAction() == 'moveLine' and \
  1459. len(digitClass.driver.GetSelected()) > 0:
  1460. nselected = 0
  1461. else:
  1462. if digitToolbar.GetAction() == 'moveLine':
  1463. drawSeg = True
  1464. else:
  1465. drawSeg = False
  1466. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1467. digitClass.GetSelectType(),
  1468. drawSeg)
  1469. if nselected == 0:
  1470. if digitClass.driver.SelectLineByPoint(pos1,
  1471. digitClass.GetSelectType()) is not None:
  1472. nselected = 1
  1473. if nselected > 0:
  1474. if digitToolbar.GetAction() in ("moveLine",
  1475. "moveVertex"):
  1476. # get pseudoDC id of objects which should be redrawn
  1477. if digitToolbar.GetAction() == "moveLine":
  1478. # -> move line
  1479. self.vdigitMove['id'] = digitClass.driver.GetSelected(grassId=False)
  1480. self.vdigitMove['coord'] = digitClass.driver.GetSelectedCoord()
  1481. else: # moveVertex
  1482. self.vdigitMove['id'] = digitClass.driver.GetSelectedVertex(pos1)
  1483. if len(self.vdigitMove['id']) == 0: # no vertex found
  1484. digitClass.driver.SetSelected([])
  1485. #
  1486. # check for duplicates
  1487. #
  1488. if UserSettings.Get(group='vdigit', key='checkForDupl', subkey='enabled') is True:
  1489. dupl = digitClass.driver.GetDuplicates()
  1490. self.UpdateMap(render=False)
  1491. if dupl:
  1492. posWindow = self.ClientToScreen((self.mouse['end'][0] + self.dialogOffset,
  1493. self.mouse['end'][1] + self.dialogOffset))
  1494. dlg = VDigitDuplicatesDialog(parent=self, data=dupl, pos=posWindow)
  1495. if dlg.ShowModal() == wx.ID_OK:
  1496. digitClass.driver.UnSelect(dlg.GetUnSelected())
  1497. # update selected
  1498. self.UpdateMap(render=False)
  1499. if digitToolbar.GetAction() != "editLine":
  1500. # -> move line || move vertex
  1501. self.UpdateMap(render=False)
  1502. else: # no vector object found
  1503. if not (digitToolbar.GetAction() in ("moveLine",
  1504. "moveVertex") and \
  1505. len(self.vdigitMove['id']) > 0):
  1506. # avoid left-click when features are already selected
  1507. self.UpdateMap(render=False, renderVector=False)
  1508. def OnLeftUpVDigitModifyLine(self, event):
  1509. """!
  1510. Left mouse button up - vector digitizer split line, add/remove
  1511. vertex action
  1512. """
  1513. digitToolbar = self.parent.toolbars['vdigit']
  1514. digitClass = self.parent.digit
  1515. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1516. pointOnLine = digitClass.driver.SelectLineByPoint(pos1,
  1517. type=VDigit_Lines_Type)
  1518. if not pointOnLine:
  1519. return
  1520. if digitToolbar.GetAction() in ["splitLine", "addVertex"]:
  1521. self.UpdateMap(render=False) # highlight object
  1522. self.DrawCross(pdc=self.pdcTmp, coords=self.Cell2Pixel(pointOnLine),
  1523. size=5)
  1524. else: # removeVertex
  1525. # get only id of vertex
  1526. try:
  1527. id = digitClass.driver.GetSelectedVertex(pos1)[0]
  1528. except IndexError:
  1529. id = None
  1530. if id:
  1531. x, y = self.pdcVector.GetIdBounds(id)[0:2]
  1532. self.pdcVector.RemoveId(id)
  1533. self.UpdateMap(render=False) # highlight object
  1534. self.DrawCross(pdc=self.pdcTmp, coords=(x, y),
  1535. size=5)
  1536. else:
  1537. # unselect
  1538. digitClass.driver.SetSelected([])
  1539. self.UpdateMap(render=False)
  1540. def OnLeftUpVDigitCopyLine(self, event):
  1541. """!
  1542. Left mouse button up - vector digitizer copy feature action
  1543. """
  1544. digitToolbar = self.parent.toolbars['vdigit']
  1545. digitClass = self.parent.digit
  1546. pos1 = self.Pixel2Cell(self.mouse['begin'])
  1547. pos2 = self.Pixel2Cell(self.mouse['end'])
  1548. if UserSettings.Get(group='vdigit', key='bgmap',
  1549. subkey='value', internal=True) == '':
  1550. # no background map -> copy from current vector map layer
  1551. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1552. digitClass.GetSelectType())
  1553. if nselected > 0:
  1554. # highlight selected features
  1555. self.UpdateMap(render=False)
  1556. else:
  1557. self.UpdateMap(render=False, renderVector=False)
  1558. else:
  1559. # copy features from background map
  1560. self.copyIds += digitClass.SelectLinesFromBackgroundMap(pos1, pos2)
  1561. if len(self.copyIds) > 0:
  1562. color = UserSettings.Get(group='vdigit', key='symbol',
  1563. subkey=['highlight', 'color'])
  1564. colorStr = str(color[0]) + ":" + \
  1565. str(color[1]) + ":" + \
  1566. str(color[2])
  1567. dVectTmp = ['d.vect',
  1568. 'map=%s' % UserSettings.Get(group='vdigit', key='bgmap',
  1569. subkey='value', internal=True),
  1570. 'cats=%s' % utils.ListOfCatsToRange(self.copyIds),
  1571. '-i',
  1572. 'color=%s' % colorStr,
  1573. 'fcolor=%s' % colorStr,
  1574. 'type=point,line,boundary,centroid',
  1575. 'width=2']
  1576. if not self.layerTmp:
  1577. self.layerTmp = self.Map.AddLayer(type='vector',
  1578. name=globalvar.QUERYLAYER,
  1579. command=dVectTmp)
  1580. else:
  1581. self.layerTmp.SetCmd(dVectTmp)
  1582. self.UpdateMap(render=True, renderVector=False)
  1583. else:
  1584. self.UpdateMap(render=False, renderVector=False)
  1585. self.redrawAll = None
  1586. def OnLeftUpVDigitBulkLine(self, event):
  1587. """!
  1588. Left mouse button up - vector digitizer z-bulk line action
  1589. """
  1590. digitToolbar = self.parent.toolbars['vdigit']
  1591. digitClass = self.parent.digit
  1592. # select lines to be labeled
  1593. pos1 = self.polycoords[0]
  1594. pos2 = self.polycoords[1]
  1595. nselected = digitClass.driver.SelectLinesByBox(pos1, pos2,
  1596. digitClass.GetSelectType())
  1597. if nselected > 0:
  1598. # highlight selected features
  1599. self.UpdateMap(render=False)
  1600. self.DrawLines(pdc=self.pdcTmp) # redraw temp line
  1601. else:
  1602. self.UpdateMap(render=False, renderVector=False)
  1603. def OnLeftUpVDigitConnectLine(self, event):
  1604. """!
  1605. Left mouse button up - vector digitizer connect line action
  1606. """
  1607. digitToolbar = self.parent.toolbars['vdigit']
  1608. digitClass = self.parent.digit
  1609. if len(digitClass.driver.GetSelected()) > 0:
  1610. self.UpdateMap(render=False)
  1611. def OnLeftUp(self, event):
  1612. """!Left mouse button released
  1613. """
  1614. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  1615. self.mouse["use"])
  1616. self.mouse['end'] = event.GetPositionTuple()[:]
  1617. if self.mouse['use'] in ["zoom", "pan"]:
  1618. # set region in zoom or pan
  1619. begin = self.mouse['begin']
  1620. end = self.mouse['end']
  1621. if self.mouse['use'] == 'zoom':
  1622. # set region for click (zero-width box)
  1623. if begin[0] - end[0] == 0 or \
  1624. begin[1] - end[1] == 0:
  1625. # zoom 1/2 of the screen (TODO: settings)
  1626. begin = (end[0] - self.Map.width / 4,
  1627. end[1] - self.Map.height / 4)
  1628. end = (end[0] + self.Map.width / 4,
  1629. end[1] + self.Map.height / 4)
  1630. self.Zoom(begin, end, self.zoomtype)
  1631. # redraw map
  1632. self.UpdateMap(render=True)
  1633. # update statusbar
  1634. self.parent.StatusbarUpdate()
  1635. elif self.mouse["use"] == "query":
  1636. # querying
  1637. self.parent.QueryMap(self.mouse['begin'][0],self.mouse['begin'][1])
  1638. elif self.mouse["use"] == "queryVector":
  1639. # editable mode for vector map layers
  1640. self.parent.QueryVector(self.mouse['begin'][0], self.mouse['begin'][1])
  1641. # clear temp canvas
  1642. self.UpdateMap(render=False, renderVector=False)
  1643. elif self.mouse["use"] in ["measure", "profile"]:
  1644. # measure or profile
  1645. if self.mouse["use"] == "measure":
  1646. self.parent.MeasureDist(self.mouse['begin'], self.mouse['end'])
  1647. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  1648. self.ClearLines(pdc=self.pdcTmp)
  1649. self.DrawLines(pdc=self.pdcTmp)
  1650. elif self.mouse["use"] == "pointer" and \
  1651. self.parent.GetLayerManager().gcpmanagement:
  1652. # -> GCP manager
  1653. if self.parent.toolbars['gcpdisp']:
  1654. coord = self.Pixel2Cell(self.mouse['end'])
  1655. if self.parent.MapWindow == self.parent.SrcMapWindow:
  1656. coordtype = 'source'
  1657. else:
  1658. coordtype = 'target'
  1659. self.parent.GetLayerManager().gcpmanagement.SetGCPData(coordtype, coord, self, confirm=True)
  1660. self.UpdateMap(render=False, renderVector=False)
  1661. elif self.mouse["use"] == "pointer" and \
  1662. self.parent.GetLayerManager().georectifying:
  1663. # -> georectifying
  1664. coord = self.Pixel2Cell(self.mouse['end'])
  1665. if self.parent.toolbars['georect']:
  1666. coordtype = 'gcpcoord'
  1667. else:
  1668. coordtype = 'mapcoord'
  1669. self.parent.GetLayerManager().georectifying.SetGCPData(coordtype, coord, self)
  1670. self.UpdateMap(render=False, renderVector=False)
  1671. elif self.mouse["use"] == "pointer" and self.parent.toolbars['vdigit']:
  1672. # digitization tool active
  1673. digitToolbar = self.parent.toolbars['vdigit']
  1674. digitClass = self.parent.digit
  1675. if hasattr(self, "vdigitMove"):
  1676. if len(digitClass.driver.GetSelected()) == 0:
  1677. self.vdigitMove['begin'] = self.Pixel2Cell(self.mouse['begin']) # left down
  1678. # eliminate initial mouse moving efect
  1679. self.mouse['begin'] = self.mouse['end']
  1680. if digitToolbar.GetAction() in ("deleteLine",
  1681. "moveLine",
  1682. "moveVertex",
  1683. "copyCats",
  1684. "copyAttrs",
  1685. "editLine",
  1686. "flipLine",
  1687. "mergeLine",
  1688. "snapLine",
  1689. "queryLine",
  1690. "breakLine",
  1691. "typeConv",
  1692. "connectLine"):
  1693. self.OnLeftUpVDigitVarious(event)
  1694. elif digitToolbar.GetAction() in ("splitLine",
  1695. "addVertex",
  1696. "removeVertex"):
  1697. self.OnLeftUpVDigitModifyLine(event)
  1698. elif digitToolbar.GetAction() == "copyLine":
  1699. self.OnLeftUpVDigitCopyLine(event)
  1700. elif digitToolbar.GetAction() == "zbulkLine" and \
  1701. len(self.polycoords) == 2:
  1702. self.OnLeftUpVDigitBulkLine(event)
  1703. elif digitToolbar.GetAction() == "connectLine":
  1704. self.OnLeftUpConnectLine(event)
  1705. if len(digitClass.driver.GetSelected()) > 0:
  1706. self.redrawAll = None
  1707. elif (self.mouse['use'] == 'pointer' and
  1708. self.dragid >= 0):
  1709. # end drag of overlay decoration
  1710. if self.dragid < 99 and self.overlays.has_key(self.dragid):
  1711. self.overlays[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1712. elif self.dragid > 100 and self.textdict.has_key(self.dragid):
  1713. self.textdict[self.dragid]['coords'] = self.pdc.GetIdBounds(self.dragid)
  1714. else:
  1715. pass
  1716. self.dragid = None
  1717. self.currtxtid = None
  1718. def OnButtonDClick(self, event):
  1719. """!
  1720. Mouse button double click
  1721. """
  1722. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  1723. self.mouse["use"])
  1724. if self.mouse["use"] == "measure":
  1725. # measure
  1726. self.ClearLines(pdc=self.pdcTmp)
  1727. self.polycoords = []
  1728. self.mouse['use'] = 'pointer'
  1729. self.mouse['box'] = 'point'
  1730. self.mouse['end'] = [0, 0]
  1731. self.Refresh()
  1732. self.SetCursor(self.parent.cursors["default"])
  1733. elif self.mouse["use"] == "profile":
  1734. pass
  1735. elif self.mouse['use'] == 'pointer' and \
  1736. self.parent.toolbars['vdigit']:
  1737. # vector digitizer
  1738. pass
  1739. else:
  1740. # select overlay decoration options dialog
  1741. clickposition = event.GetPositionTuple()[:]
  1742. idlist = self.pdc.FindObjects(clickposition[0], clickposition[1], self.hitradius)
  1743. if idlist == []:
  1744. return
  1745. self.dragid = idlist[0]
  1746. # self.ovlcoords[self.dragid] = self.pdc.GetIdBounds(self.dragid)
  1747. if self.dragid > 100:
  1748. self.currtxtid = self.dragid
  1749. self.parent.OnAddText(None)
  1750. elif self.dragid == 0:
  1751. self.parent.OnAddBarscale(None)
  1752. elif self.dragid == 1:
  1753. self.parent.OnAddLegend(None)
  1754. def OnRightDown(self, event):
  1755. """!
  1756. Right mouse button pressed
  1757. """
  1758. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  1759. self.mouse["use"])
  1760. digitToolbar = self.parent.toolbars['vdigit']
  1761. if digitToolbar:
  1762. digitClass = self.parent.digit
  1763. # digitization tool (confirm action)
  1764. if digitToolbar.GetAction() in ("moveLine",
  1765. "moveVertex") and \
  1766. hasattr(self, "vdigitMove"):
  1767. pFrom = self.vdigitMove['begin']
  1768. pTo = self.Pixel2Cell(event.GetPositionTuple())
  1769. move = (pTo[0] - pFrom[0],
  1770. pTo[1] - pFrom[1])
  1771. if digitToolbar.GetAction() == "moveLine":
  1772. # move line
  1773. if digitClass.MoveSelectedLines(move) < 0:
  1774. return
  1775. elif digitToolbar.GetAction() == "moveVertex":
  1776. # move vertex
  1777. fid = digitClass.MoveSelectedVertex(pFrom, move)
  1778. if fid < 0:
  1779. return
  1780. self.__geomAttrbUpdate([fid,])
  1781. del self.vdigitMove
  1782. event.Skip()
  1783. def OnRightUp(self, event):
  1784. """!
  1785. Right mouse button released
  1786. """
  1787. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  1788. self.mouse["use"])
  1789. digitToolbar = self.parent.toolbars['vdigit']
  1790. if digitToolbar:
  1791. digitClass = self.parent.digit
  1792. # digitization tool (confirm action)
  1793. if digitToolbar.GetAction() == "addLine" and \
  1794. digitToolbar.GetAction('type') in ["line", "boundary"]:
  1795. # -> add new line / boundary
  1796. try:
  1797. map = digitToolbar.GetLayer().GetName()
  1798. except:
  1799. map = None
  1800. wx.MessageBox(parent=self,
  1801. message=_("No vector map selected for editing."),
  1802. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1803. if map:
  1804. # mapcoords = []
  1805. # xy -> EN
  1806. # for coord in self.polycoords:
  1807. # mapcoords.append(self.Pixel2Cell(coord))
  1808. if digitToolbar.GetAction('type') == 'line':
  1809. line = True
  1810. else:
  1811. line = False
  1812. if len(self.polycoords) < 2: # ignore 'one-point' lines
  1813. return
  1814. fid = digitClass.AddLine(map, line, self.polycoords)
  1815. if fid < 0:
  1816. return
  1817. position = self.Cell2Pixel(self.polycoords[-1])
  1818. self.polycoords = []
  1819. self.UpdateMap(render=False)
  1820. self.redrawAll = True
  1821. self.Refresh()
  1822. # add new record into atribute table
  1823. if UserSettings.Get(group='vdigit', key="addRecord", subkey='enabled') and \
  1824. (line is True or \
  1825. (not line and fid > 0)):
  1826. posWindow = self.ClientToScreen((position[0] + self.dialogOffset,
  1827. position[1] + self.dialogOffset))
  1828. # select attributes based on layer and category
  1829. cats = { fid : {
  1830. UserSettings.Get(group='vdigit', key="layer", subkey='value') :
  1831. (UserSettings.Get(group='vdigit', key="category", subkey='value'), )
  1832. }}
  1833. addRecordDlg = dbm_dialogs.DisplayAttributesDialog(parent=self, map=map,
  1834. cats=cats,
  1835. pos=posWindow,
  1836. action="add")
  1837. self.__geomAttrb(fid, addRecordDlg, 'length', digitClass,
  1838. digitToolbar.GetLayer())
  1839. # auto-placing centroid
  1840. self.__geomAttrb(fid, addRecordDlg, 'area', digitClass,
  1841. digitToolbar.GetLayer())
  1842. self.__geomAttrb(fid, addRecordDlg, 'perimeter', digitClass,
  1843. digitToolbar.GetLayer())
  1844. if addRecordDlg.mapDBInfo and \
  1845. addRecordDlg.ShowModal() == wx.ID_OK:
  1846. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  1847. for sql in addRecordDlg.GetSQLString():
  1848. sqlfile.file.write(sql + ";\n")
  1849. sqlfile.file.flush()
  1850. gcmd.RunCommand('db.execute',
  1851. parent = True,
  1852. quiet = True,
  1853. input = sqlfile.name)
  1854. if addRecordDlg.mapDBInfo:
  1855. self.__updateATM()
  1856. elif digitToolbar.GetAction() == "deleteLine":
  1857. # -> delete selected vector features
  1858. if digitClass.DeleteSelectedLines() < 0:
  1859. return
  1860. self.__updateATM()
  1861. elif digitToolbar.GetAction() == "splitLine":
  1862. # split line
  1863. if digitClass.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
  1864. return
  1865. elif digitToolbar.GetAction() == "addVertex":
  1866. # add vertex
  1867. fid = digitClass.AddVertex(self.Pixel2Cell(self.mouse['begin']))
  1868. if fid < 0:
  1869. return
  1870. elif digitToolbar.GetAction() == "removeVertex":
  1871. # remove vertex
  1872. fid = digitClass.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
  1873. if fid < 0:
  1874. return
  1875. self.__geomAttrbUpdate([fid,])
  1876. elif digitToolbar.GetAction() in ("copyCats", "copyAttrs"):
  1877. try:
  1878. if digitToolbar.GetAction() == 'copyCats':
  1879. if digitClass.CopyCats(self.copyCatsList,
  1880. self.copyCatsIds, copyAttrb=False) < 0:
  1881. return
  1882. else:
  1883. if digitClass.CopyCats(self.copyCatsList,
  1884. self.copyCatsIds, copyAttrb=True) < 0:
  1885. return
  1886. del self.copyCatsList
  1887. del self.copyCatsIds
  1888. except AttributeError:
  1889. pass
  1890. self.__updateATM()
  1891. elif digitToolbar.GetAction() == "editLine" and \
  1892. hasattr(self, "vdigitMove"):
  1893. line = digitClass.driver.GetSelected()
  1894. if digitClass.EditLine(line, self.polycoords) < 0:
  1895. return
  1896. del self.vdigitMove
  1897. elif digitToolbar.GetAction() == "flipLine":
  1898. if digitClass.FlipLine() < 0:
  1899. return
  1900. elif digitToolbar.GetAction() == "mergeLine":
  1901. if digitClass.MergeLine() < 0:
  1902. return
  1903. elif digitToolbar.GetAction() == "breakLine":
  1904. if digitClass.BreakLine() < 0:
  1905. return
  1906. elif digitToolbar.GetAction() == "snapLine":
  1907. if digitClass.SnapLine() < 0:
  1908. return
  1909. elif digitToolbar.GetAction() == "connectLine":
  1910. if len(digitClass.driver.GetSelected()) > 1:
  1911. if digitClass.ConnectLine() < 0:
  1912. return
  1913. elif digitToolbar.GetAction() == "copyLine":
  1914. if digitClass.CopyLine(self.copyIds) < 0:
  1915. return
  1916. del self.copyIds
  1917. if self.layerTmp:
  1918. self.Map.DeleteLayer(self.layerTmp)
  1919. self.UpdateMap(render=True, renderVector=False)
  1920. del self.layerTmp
  1921. elif digitToolbar.GetAction() == "zbulkLine" and len(self.polycoords) == 2:
  1922. pos1 = self.polycoords[0]
  1923. pos2 = self.polycoords[1]
  1924. selected = digitClass.driver.GetSelected()
  1925. dlg = VDigitZBulkDialog(parent=self, title=_("Z bulk-labeling dialog"),
  1926. nselected=len(selected))
  1927. if dlg.ShowModal() == wx.ID_OK:
  1928. if digitClass.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
  1929. dlg.step.GetValue()) < 0:
  1930. return
  1931. self.UpdateMap(render=False, renderVector=True)
  1932. elif digitToolbar.GetAction() == "typeConv":
  1933. # -> feature type conversion
  1934. # - point <-> centroid
  1935. # - line <-> boundary
  1936. if digitClass.TypeConvForSelectedLines() < 0:
  1937. return
  1938. if digitToolbar.GetAction() != "addLine":
  1939. # unselect and re-render
  1940. digitClass.driver.SetSelected([])
  1941. self.polycoords = []
  1942. self.UpdateMap(render=False)
  1943. self.redrawAll = True
  1944. self.Refresh()
  1945. event.Skip()
  1946. def OnMiddleDown(self, event):
  1947. """!
  1948. Middle mouse button pressed
  1949. """
  1950. self.mouse['begin'] = event.GetPositionTuple()[:]
  1951. digitToolbar = self.parent.toolbars['vdigit']
  1952. # digitization tool
  1953. if self.mouse["use"] == "pointer" and digitToolbar:
  1954. digitClass = self.parent.digit
  1955. if (digitToolbar.GetAction() == "addLine" and \
  1956. digitToolbar.GetAction('type') in ["line", "boundary"]) or \
  1957. digitToolbar.GetAction() == "editLine":
  1958. # add line or boundary -> remove last point from the line
  1959. try:
  1960. removed = self.polycoords.pop()
  1961. Debug.msg(4, "BufferedWindow.OnMiddleDown(): polycoords_poped=%s" % \
  1962. [removed,])
  1963. self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1])
  1964. except:
  1965. pass
  1966. if digitToolbar.GetAction() == "editLine":
  1967. # remove last vertex & line
  1968. if len(self.vdigitMove['id']) > 1:
  1969. self.vdigitMove['id'].pop()
  1970. self.UpdateMap(render=False, renderVector=False)
  1971. elif digitToolbar.GetAction() in ["deleteLine", "moveLine", "splitLine",
  1972. "addVertex", "removeVertex", "moveVertex",
  1973. "copyCats", "flipLine", "mergeLine",
  1974. "snapLine", "connectLine", "copyLine",
  1975. "queryLine", "breakLine", "typeConv"]:
  1976. # varios tools -> unselected selected features
  1977. digitClass.driver.SetSelected([])
  1978. if digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] and \
  1979. hasattr(self, "vdigitMove"):
  1980. del self.vdigitMove
  1981. elif digitToolbar.GetAction() == "copyCats":
  1982. try:
  1983. del self.copyCatsList
  1984. del self.copyCatsIds
  1985. except AttributeError:
  1986. pass
  1987. elif digitToolbar.GetAction() == "copyLine":
  1988. del self.copyIds
  1989. if self.layerTmp:
  1990. self.Map.DeleteLayer(self.layerTmp)
  1991. self.UpdateMap(render=True, renderVector=False)
  1992. del self.layerTmp
  1993. self.polycoords = []
  1994. self.UpdateMap(render=False) # render vector
  1995. elif digitToolbar.GetAction() == "zbulkLine":
  1996. # reset polyline
  1997. self.polycoords = []
  1998. digitClass.driver.SetSelected([])
  1999. self.UpdateMap(render=False)
  2000. self.redrawAll = True
  2001. def OnMiddleUp(self, event):
  2002. """!
  2003. Middle mouse button released
  2004. """
  2005. self.mouse['end'] = event.GetPositionTuple()[:]
  2006. # set region in zoom or pan
  2007. begin = self.mouse['begin']
  2008. end = self.mouse['end']
  2009. self.Zoom(begin, end, 0) # no zoom
  2010. # redraw map
  2011. self.UpdateMap(render=True)
  2012. # update statusbar
  2013. self.parent.StatusbarUpdate()
  2014. def OnMouseEnter(self, event):
  2015. """!
  2016. Mouse entered window and no mouse buttons were pressed
  2017. """
  2018. if self.parent.GetLayerManager().gcpmanagement:
  2019. if self.parent.toolbars['gcpdisp']:
  2020. if not self.parent.MapWindow == self:
  2021. self.parent.MapWindow = self
  2022. self.parent.Map = self.Map
  2023. self.parent.UpdateActive(self)
  2024. # needed for wingrass
  2025. self.SetFocus()
  2026. else:
  2027. event.Skip()
  2028. def OnMouseMoving(self, event):
  2029. """!
  2030. Motion event and no mouse buttons were pressed
  2031. """
  2032. digitToolbar = self.parent.toolbars['vdigit']
  2033. if self.mouse["use"] == "pointer" and digitToolbar:
  2034. digitClass = self.parent.digit
  2035. self.mouse['end'] = event.GetPositionTuple()[:]
  2036. Debug.msg (5, "BufferedWindow.OnMouseMoving(): coords=%f,%f" % \
  2037. (self.mouse['end'][0], self.mouse['end'][1]))
  2038. if digitToolbar.GetAction() == "addLine" and digitToolbar.GetAction('type') in ["line", "boundary"]:
  2039. if len(self.polycoords) > 0:
  2040. self.MouseDraw(pdc=self.pdcTmp, begin=self.Cell2Pixel(self.polycoords[-1]))
  2041. elif digitToolbar.GetAction() in ["moveLine", "moveVertex", "editLine"] \
  2042. and hasattr(self, "vdigitMove"):
  2043. dx = self.mouse['end'][0] - self.mouse['begin'][0]
  2044. dy = self.mouse['end'][1] - self.mouse['begin'][1]
  2045. if len(self.vdigitMove['id']) > 0:
  2046. # draw lines on new position
  2047. if digitToolbar.GetAction() == "moveLine":
  2048. # move line
  2049. for id in self.vdigitMove['id']:
  2050. self.pdcTmp.TranslateId(id, dx, dy)
  2051. elif digitToolbar.GetAction() in ["moveVertex", "editLine"]:
  2052. # move vertex ->
  2053. # (vertex, left vertex, left line,
  2054. # right vertex, right line)
  2055. # do not draw static lines
  2056. if digitToolbar.GetAction() == "moveVertex":
  2057. self.polycoords = []
  2058. ### self.pdcTmp.TranslateId(self.vdigitMove['id'][0], dx, dy)
  2059. self.pdcTmp.RemoveId(self.vdigitMove['id'][0])
  2060. if self.vdigitMove['id'][1] > 0: # previous vertex
  2061. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][1])[0:2])
  2062. self.pdcTmp.RemoveId(self.vdigitMove['id'][1]+1)
  2063. self.polycoords.append((x, y))
  2064. ### x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][0])[0:2])
  2065. self.polycoords.append(self.Pixel2Cell(self.mouse['end']))
  2066. if self.vdigitMove['id'][2] > 0: # next vertex
  2067. x, y = self.Pixel2Cell(self.pdcTmp.GetIdBounds(self.vdigitMove['id'][2])[0:2])
  2068. self.pdcTmp.RemoveId(self.vdigitMove['id'][2]-1)
  2069. self.polycoords.append((x, y))
  2070. self.ClearLines(pdc=self.pdcTmp)
  2071. self.DrawLines(pdc=self.pdcTmp)
  2072. else: # edit line
  2073. try:
  2074. if self.vdigitMove['id'][-1] > 0: # previous vertex
  2075. self.MouseDraw(pdc=self.pdcTmp,
  2076. begin=self.Cell2Pixel(self.polycoords[-1]))
  2077. except: # no line
  2078. self.vdigitMove['id'] = []
  2079. self.polycoords = []
  2080. self.Refresh() # TODO: use RefreshRect()
  2081. self.mouse['begin'] = self.mouse['end']
  2082. elif digitToolbar.GetAction() == "zbulkLine":
  2083. if len(self.polycoords) == 1:
  2084. # draw mouse moving
  2085. self.MouseDraw(self.pdcTmp)
  2086. event.Skip()
  2087. def ClearLines(self, pdc=None):
  2088. """!
  2089. Clears temporary drawn lines from PseudoDC
  2090. """
  2091. if not pdc:
  2092. pdc=self.pdcTmp
  2093. try:
  2094. pdc.ClearId(self.lineid)
  2095. pdc.RemoveId(self.lineid)
  2096. except:
  2097. pass
  2098. try:
  2099. pdc.ClearId(self.plineid)
  2100. pdc.RemoveId(self.plineid)
  2101. except:
  2102. pass
  2103. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  2104. (self.lineid, self.plineid))
  2105. ### self.Refresh()
  2106. return True
  2107. def Pixel2Cell(self, (x, y)):
  2108. """!Convert image coordinates to real word coordinates
  2109. @param x, y image coordinates
  2110. @return easting, northing
  2111. @return None on error
  2112. """
  2113. try:
  2114. x = int(x)
  2115. y = int(y)
  2116. except:
  2117. return None
  2118. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  2119. res = self.Map.region["ewres"]
  2120. else:
  2121. res = self.Map.region["nsres"]
  2122. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  2123. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  2124. east = w + x * res
  2125. north = n - y * res
  2126. return (east, north)
  2127. def Cell2Pixel(self, (east, north)):
  2128. """!Convert real word coordinates to image coordinates
  2129. """
  2130. try:
  2131. east = float(east)
  2132. north = float(north)
  2133. except:
  2134. return None
  2135. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  2136. res = self.Map.region["ewres"]
  2137. else:
  2138. res = self.Map.region["nsres"]
  2139. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  2140. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  2141. x = (east - w) / res
  2142. y = (n - north) / res
  2143. return (x, y)
  2144. def Zoom(self, begin, end, zoomtype):
  2145. """!
  2146. Calculates new region while (un)zoom/pan-ing
  2147. """
  2148. x1, y1 = begin
  2149. x2, y2 = end
  2150. newreg = {}
  2151. # threshold - too small squares do not make sense
  2152. # can only zoom to windows of > 5x5 screen pixels
  2153. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  2154. if x1 > x2:
  2155. x1, x2 = x2, x1
  2156. if y1 > y2:
  2157. y1, y2 = y2, y1
  2158. # zoom in
  2159. if zoomtype > 0:
  2160. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  2161. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  2162. # zoom out
  2163. elif zoomtype < 0:
  2164. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  2165. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  2166. (self.Map.width - x2),
  2167. self.Map.height + 2 * \
  2168. (self.Map.height - y2)))
  2169. # pan
  2170. elif zoomtype == 0:
  2171. dx = x1 - x2
  2172. dy = y1 - y2
  2173. if dx == 0 and dy == 0:
  2174. dx = x1 - self.Map.width / 2
  2175. dy = y1 - self.Map.height / 2
  2176. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  2177. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  2178. self.Map.height + dy))
  2179. # if new region has been calculated, set the values
  2180. if newreg != {}:
  2181. # LL locations
  2182. if self.parent.Map.projinfo['proj'] == 'll':
  2183. if newreg['n'] > 90.0:
  2184. newreg['n'] = 90.0
  2185. if newreg['s'] < -90.0:
  2186. newreg['s'] = -90.0
  2187. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  2188. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  2189. if hasattr(self, "vdigitMove"):
  2190. # xo = self.Cell2Pixel((self.Map.region['center_easting'], self.Map.region['center_northing']))
  2191. # xn = self.Cell2Pixel(ce, cn))
  2192. tmp = self.Pixel2Cell(self.mouse['end'])
  2193. # calculate new center point and display resolution
  2194. self.Map.region['center_easting'] = ce
  2195. self.Map.region['center_northing'] = cn
  2196. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  2197. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  2198. self.Map.AlignExtentFromDisplay()
  2199. if hasattr(self, "vdigitMove"):
  2200. tmp1 = self.mouse['end']
  2201. tmp2 = self.Cell2Pixel(self.vdigitMove['begin'])
  2202. dx = tmp1[0] - tmp2[0]
  2203. dy = tmp1[1] - tmp2[1]
  2204. self.vdigitMove['beginDiff'] = (dx, dy)
  2205. for id in self.vdigitMove['id']:
  2206. self.pdcTmp.RemoveId(id)
  2207. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2208. self.Map.region['e'], self.Map.region['w'])
  2209. if self.redrawAll is False:
  2210. self.redrawAll = True
  2211. def ZoomBack(self):
  2212. """!Zoom to previous extents in zoomhistory list
  2213. """
  2214. zoom = list()
  2215. if len(self.zoomhistory) > 1:
  2216. self.zoomhistory.pop()
  2217. zoom = self.zoomhistory[-1]
  2218. # disable tool if stack is empty
  2219. if len(self.zoomhistory) < 2: # disable tool
  2220. if self.parent.GetName() == 'MapWindow':
  2221. toolbar = self.parent.toolbars['map']
  2222. elif self.parent.GetName() == 'GRMapWindow':
  2223. toolbar = self.parent.toolbars['georect']
  2224. elif self.parent.GetName() == 'GCPMapWindow':
  2225. toolbar = self.parent.toolbars['gcpdisp']
  2226. toolbar.Enable('zoomback', enable = False)
  2227. # zoom to selected region
  2228. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  2229. e = zoom[2], w = zoom[3],
  2230. update = True)
  2231. # update map
  2232. self.UpdateMap()
  2233. # update statusbar
  2234. self.parent.StatusbarUpdate()
  2235. def ZoomHistory(self, n, s, e, w):
  2236. """!
  2237. Manages a list of last 10 zoom extents
  2238. @param n,s,e,w north, south, east, west
  2239. @return removed history item if exists (or None)
  2240. """
  2241. removed = None
  2242. self.zoomhistory.append((n,s,e,w))
  2243. if len(self.zoomhistory) > 10:
  2244. removed = self.zoomhistory.pop(0)
  2245. if removed:
  2246. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  2247. (self.zoomhistory, removed))
  2248. else:
  2249. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  2250. (self.zoomhistory))
  2251. # update toolbar
  2252. if len(self.zoomhistory) > 1:
  2253. enable = True
  2254. else:
  2255. enable = False
  2256. if self.parent.GetName() == 'MapWindow':
  2257. toolbar = self.parent.toolbars['map']
  2258. elif self.parent.GetName() == 'GRMapWindow':
  2259. toolbar = self.parent.toolbars['georect']
  2260. elif self.parent.GetName() == 'GCPMapWindow':
  2261. toolbar = self.parent.toolbars['gcpdisp']
  2262. toolbar.Enable('zoomback', enable)
  2263. return removed
  2264. def ResetZoomHistory(self):
  2265. """!Reset zoom history"""
  2266. self.zoomhistory = list()
  2267. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  2268. """!
  2269. Set display extents to match selected raster
  2270. or vector map(s).
  2271. @param layer list of layers to be zoom to
  2272. @param ignoreNulls True to ignore null-values
  2273. @param render True to re-render display
  2274. """
  2275. zoomreg = {}
  2276. if not layers:
  2277. layers = self.GetSelectedLayer(multi = True)
  2278. if not layers:
  2279. return
  2280. rast = []
  2281. vect = []
  2282. updated = False
  2283. for l in layers:
  2284. # only raster/vector layers are currently supported
  2285. if l.type == 'raster':
  2286. rast.append(l.name)
  2287. elif l.type == 'vector':
  2288. digitToolbar = self.parent.toolbars['vdigit']
  2289. if digitToolbar and digitToolbar.GetLayer() == l:
  2290. w, s, b, e, n, t = self.parent.digit.driver.GetMapBoundingBox()
  2291. self.Map.GetRegion(n=n, s=s, w=w, e=e,
  2292. update=True)
  2293. updated = True
  2294. else:
  2295. vect.append(l.name)
  2296. if not updated:
  2297. self.Map.GetRegion(rast = rast,
  2298. vect = vect,
  2299. update = True)
  2300. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2301. self.Map.region['e'], self.Map.region['w'])
  2302. if render:
  2303. self.UpdateMap()
  2304. self.parent.StatusbarUpdate()
  2305. def ZoomToWind(self):
  2306. """!Set display geometry to match computational region
  2307. settings (set with g.region)
  2308. """
  2309. self.Map.region = self.Map.GetRegion()
  2310. ### self.Map.SetRegion(windres=True)
  2311. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2312. self.Map.region['e'], self.Map.region['w'])
  2313. self.UpdateMap()
  2314. self.parent.StatusbarUpdate()
  2315. def ZoomToDefault(self):
  2316. """!Set display geometry to match default region settings
  2317. """
  2318. self.Map.region = self.Map.GetRegion(default=True)
  2319. self.Map.AdjustRegion() # aling region extent to the display
  2320. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  2321. self.Map.region['e'], self.Map.region['w'])
  2322. self.UpdateMap()
  2323. self.parent.StatusbarUpdate()
  2324. def DisplayToWind(self):
  2325. """!Set computational region (WIND file) to match display
  2326. extents
  2327. """
  2328. tmpreg = os.getenv("GRASS_REGION")
  2329. if tmpreg:
  2330. del os.environ["GRASS_REGION"]
  2331. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  2332. # for user to set explicitly with g.region
  2333. new = self.Map.AlignResolution()
  2334. gcmd.RunCommand('g.region',
  2335. parent = self,
  2336. overwrite = True,
  2337. n = new['n'],
  2338. s = new['s'],
  2339. e = new['e'],
  2340. w = new['w'],
  2341. rows = int(new['rows']),
  2342. cols = int(new['cols']))
  2343. if tmpreg:
  2344. os.environ["GRASS_REGION"] = tmpreg
  2345. def ZoomToSaved(self):
  2346. """!Set display geometry to match extents in
  2347. saved region file
  2348. """
  2349. dlg = gdialogs.SavedRegion(parent = self,
  2350. title = _("Zoom to saved region extents"),
  2351. loadsave='load')
  2352. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.wind:
  2353. dlg.Destroy()
  2354. return
  2355. if not grass.find_file(name = dlg.wind, element = 'windows')['name']:
  2356. wx.MessageBox(parent = self,
  2357. message = _("Region <%s> not found. Operation canceled.") % dlg.wind,
  2358. caption = _("Error"), style = wx.ICON_ERROR | wx.OK | wx.CENTRE)
  2359. dlg.Destroy()
  2360. return
  2361. self.Map.GetRegion(regionName = dlg.wind,
  2362. update = True)
  2363. dlg.Destroy()
  2364. self.ZoomHistory(self.Map.region['n'],
  2365. self.Map.region['s'],
  2366. self.Map.region['e'],
  2367. self.Map.region['w'])
  2368. self.UpdateMap()
  2369. def SaveDisplayRegion(self):
  2370. """!Save display extents to named region file.
  2371. """
  2372. dlg = gdialogs.SavedRegion(parent = self,
  2373. title = _("Save display extents to region file"),
  2374. loadsave='save')
  2375. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.wind:
  2376. dlg.Destroy()
  2377. return
  2378. # test to see if it already exists and ask permission to overwrite
  2379. if grass.find_file(name = dlg.wind, element = 'windows')['name']:
  2380. overwrite = wx.MessageBox(parent = self,
  2381. message = _("Region file <%s> already exists. "
  2382. "Do you want to overwrite it?") % (dlg.wind),
  2383. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  2384. if (overwrite == wx.YES):
  2385. self.SaveRegion(dlg.wind)
  2386. else:
  2387. self.SaveRegion(dlg.wind)
  2388. dlg.Destroy()
  2389. def SaveRegion(self, wind):
  2390. """!Save region settings
  2391. @param wind region name
  2392. """
  2393. new = self.Map.GetCurrentRegion()
  2394. tmpreg = os.getenv("GRASS_REGION")
  2395. if tmpreg:
  2396. del os.environ["GRASS_REGION"]
  2397. gcmd.RunCommand('g.region',
  2398. overwrite = True,
  2399. parent = self,
  2400. flags = 'u',
  2401. n = new['n'],
  2402. s = new['s'],
  2403. e = new['e'],
  2404. w = new['w'],
  2405. rows = int(new['rows']),
  2406. cols = int(new['cols']),
  2407. save = wind)
  2408. if tmpreg:
  2409. os.environ["GRASS_REGION"] = tmpreg
  2410. def Distance(self, beginpt, endpt, screen=True):
  2411. """!Calculete distance
  2412. LL-locations not supported
  2413. @todo Use m.distance
  2414. @param beginpt first point
  2415. @param endpt second point
  2416. @param screen True for screen coordinates otherwise EN
  2417. """
  2418. x1, y1 = beginpt
  2419. x2, y2 = endpt
  2420. if screen:
  2421. dEast = (x2 - x1) * self.Map.region["ewres"]
  2422. dNorth = (y2 - y1) * self.Map.region["nsres"]
  2423. else:
  2424. dEast = (x2 - x1)
  2425. dNorth = (y2 - y1)
  2426. return (math.sqrt(math.pow((dEast),2) + math.pow((dNorth),2)), (dEast, dNorth))