mapdisp_window.py 101 KB

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