mapdisp_window.py 109 KB

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