mapdisp_window.py 110 KB

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