mapdisp_window.py 102 KB

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