mapdisp_window.py 109 KB

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