mapdisp_window.py 99 KB

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