mapdisp_window.py 110 KB

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