mapdisp_window.py 107 KB

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