mapdisp_window.py 98 KB

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