mapwindow.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  1. """!
  2. @package mapdisp.mapwindow
  3. @brief Map display canvas - buffered window.
  4. Classes:
  5. - mapwindow::BufferedWindow
  6. - mapwindow::GraphicsSet
  7. - mapwindow::GraphicsSetItem
  8. (C) 2006-2013 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Martin Landa <landa.martin gmail.com>
  12. @author Michael Barton
  13. @author Jachym Cepicky
  14. @author Stepan Turek <stepan.turek seznam.cz> (handlers support, GraphicsSet)
  15. @author Anna Petrasova <kratochanna gmail.com> (refactoring)
  16. @author Vaclav Petras <wenzeslaus gmail.com> (refactoring)
  17. """
  18. import os
  19. import time
  20. import math
  21. import sys
  22. from copy import copy
  23. import wx
  24. from grass.pydispatch.signal import Signal
  25. import grass.script as grass
  26. from gui_core.dialogs import SavedRegion
  27. from core.gcmd import RunCommand, GException, GError, GMessage
  28. from core.debug import Debug
  29. from core.settings import UserSettings
  30. from gui_core.mapwindow import MapWindow
  31. from core.utils import GetGEventAttribsForHandler, _
  32. import core.utils as utils
  33. try:
  34. import grass.lib.gis as gislib
  35. haveCtypes = True
  36. except ImportError:
  37. haveCtypes = False
  38. class BufferedWindow(MapWindow, wx.Window):
  39. """!A Buffered window class (2D view mode)
  40. Superclass for VDigitWindow (vector digitizer).
  41. When the drawing needs to change, you app needs to call the
  42. UpdateMap() method. Since the drawing is stored in a bitmap, you
  43. can also save the drawing to file by calling the
  44. SaveToFile() method.
  45. """
  46. def __init__(self, parent, giface, Map, frame, properties,
  47. id=wx.ID_ANY, overlays=None,
  48. style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
  49. """!
  50. @param parent parent window
  51. @param giface grass interface instance
  52. @param Map map instance
  53. @param frame map frame instance (to be removed)
  54. @param id wx window id
  55. @param style wx window style
  56. @param kwargs keyword arguments passed to MapWindow and wx.Window
  57. """
  58. MapWindow.__init__(self, parent=parent, giface=giface, Map=Map)
  59. wx.Window.__init__(self, parent = parent, id = id, style = style, **kwargs)
  60. self._properties = properties
  61. self.frame = frame # remove including a frame parameter
  62. # flags
  63. self.resize = False # indicates whether or not a resize event has taken place
  64. self.dragimg = None # initialize variable for map panning
  65. self.alwaysRender = False # if it always sets render to True in self.UpdateMap()
  66. # variables for drawing on DC
  67. self.pen = None # pen for drawing zoom boxes, etc.
  68. self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
  69. # List of wx.Point tuples defining a polyline (geographical coordinates)
  70. self.polycoords = []
  71. # ID of rubber band line
  72. self.lineid = None
  73. # ID of poly line resulting from cumulative rubber band lines (e.g. measurement)
  74. self.plineid = None
  75. # Emitted when zoom of a window is changed
  76. self.zoomChanged = Signal('BufferedWindow.zoomChanged')
  77. # Emitted when map was queried, parameters x, y are mouse coordinates
  78. # TODO: change pixel coordinates to map coordinates (using Pixel2Cell)
  79. self.mapQueried = Signal('BufferedWindow.mapQueried')
  80. # Emitted when the zoom history stack is emptied
  81. self.zoomHistoryUnavailable = Signal('BufferedWindow.zoomHistoryUnavailable')
  82. # Emitted when the zoom history stack is not empty
  83. self.zoomHistoryAvailable = Signal('BufferedWindow.zoomHistoryAvailable')
  84. # Emitted when map enters the window
  85. self.mouseEntered = Signal('BufferedWindow.mouseEntered')
  86. # Emitted when left mouse button is released and mouse use is 'pointer'
  87. # Parameters are x and y of the mouse click in map (cell) units
  88. # new and experimental, if the concept would be used widely,
  89. # it could replace register and unregister mechanism
  90. # and partially maybe also internal mouse use dictionary
  91. self.mouseLeftUpPointer = Signal('BufferedWindow.mouseLeftUpPointer')
  92. # Emitted when left mouse button is released
  93. self.mouseLeftUp = Signal('BufferedWindow.mouseLeftUp')
  94. # Emitted when left mouse button was pressed
  95. self.mouseLeftDown = Signal('BufferedWindow.mouseLeftDown')
  96. # Emitted after double-click
  97. self.mouseDClick = Signal('BufferedWindow.mouseDClick')
  98. # Emitted when mouse us moving (mouse motion event)
  99. # Parametres are x and y of the mouse position in map (cell) units
  100. self.mouseMoving = Signal('BufferedWindow.mouseMoving')
  101. # event bindings
  102. self.Bind(wx.EVT_PAINT, self.OnPaint)
  103. self.Bind(wx.EVT_SIZE, self.OnSize)
  104. self.Bind(wx.EVT_IDLE, self.OnIdle)
  105. self._bindMouseEvents()
  106. self.processMouse = True
  107. # render output objects
  108. self.mapfile = None # image file to be rendered
  109. self.img = None # wx.Image object (self.mapfile)
  110. # decoration overlays
  111. self.overlays = overlays
  112. # images and their PseudoDC ID's for painting and dragging
  113. self.imagedict = {}
  114. self.select = {} # selecting/unselecting decorations for dragging
  115. self.textdict = {} # text, font, and color indexed by id
  116. # zoom objects
  117. self.zoomhistory = [] # list of past zoom extents
  118. self.currzoom = 0 # current set of extents in zoom history being used
  119. self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
  120. self.hitradius = 10 # distance for selecting map decorations
  121. self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
  122. # OnSize called to make sure the buffer is initialized.
  123. # This might result in OnSize getting called twice on some
  124. # platforms at initialization, but little harm done.
  125. ### self.OnSize(None)
  126. self._definePseudoDC()
  127. # redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
  128. self.redrawAll = True
  129. # will store an off screen empty bitmap for saving to file
  130. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  131. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
  132. # rerender when Map reports change
  133. self.Map.layerChanged.connect(lambda: self.UpdateMap())
  134. # vars for handling mouse clicks
  135. self.dragid = -1
  136. self.lastpos = (0, 0)
  137. # list for registration of graphics to draw
  138. self.graphicsSetList = []
  139. def _definePseudoDC(self):
  140. """!Define PseudoDC objects to use
  141. """
  142. # create PseudoDC used for background map, map decorations like scales and legends
  143. self.pdc = wx.PseudoDC()
  144. # used for digitization tool
  145. self.pdcVector = None
  146. # decorations (region box, etc.)
  147. self.pdcDec = wx.PseudoDC()
  148. # pseudoDC for temporal objects (select box, measurement tool, etc.)
  149. self.pdcTmp = wx.PseudoDC()
  150. def _bindMouseEvents(self):
  151. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  152. self.Bind(wx.EVT_MOTION, self.OnMotion)
  153. self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
  154. def OnContextMenu(self, event):
  155. """!Show Map Display context menu"""
  156. if hasattr(self, "digit"):
  157. event.Skip()
  158. return
  159. if not hasattr(self, "popupCopyCoordinates"):
  160. self.popupCopyCoordinates = wx.NewId()
  161. self.Bind(wx.EVT_MENU, self.OnCopyCoordinates, id = self.popupCopyCoordinates)
  162. # generate popup-menu
  163. menu = wx.Menu()
  164. menu.Append(self.popupCopyCoordinates, _("Copy coordinates to clipboard"))
  165. self.PopupMenu(menu)
  166. menu.Destroy()
  167. def Draw(self, pdc, img = None, drawid = None, pdctype = 'image', coords = [0, 0, 0, 0], pen = None):
  168. """!Draws map and overlay decorations
  169. """
  170. if drawid == None:
  171. if pdctype == 'image' and img:
  172. drawid = self.imagedict[img]
  173. elif pdctype == 'clear':
  174. drawid = None
  175. else:
  176. drawid = wx.NewId()
  177. # TODO: find better solution
  178. if not pen:
  179. if pdctype == 'polyline':
  180. pen = self.polypen
  181. else:
  182. pen = self.pen
  183. if img and pdctype == 'image':
  184. # self.imagedict[img]['coords'] = coords
  185. self.select[self.imagedict[img]['id']] = False # ?
  186. pdc.BeginDrawing()
  187. if drawid != 99:
  188. bg = wx.TRANSPARENT_BRUSH
  189. else:
  190. bg = wx.Brush(self.GetBackgroundColour())
  191. pdc.SetBackground(bg)
  192. Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype = %s, coord=%s" % \
  193. (drawid, pdctype, coords))
  194. # set PseudoDC id
  195. if drawid is not None:
  196. pdc.SetId(drawid)
  197. if pdctype == 'clear': # erase the display
  198. bg = wx.WHITE_BRUSH
  199. # bg = wx.Brush(self.GetBackgroundColour())
  200. pdc.SetBackground(bg)
  201. pdc.RemoveAll()
  202. pdc.Clear()
  203. pdc.EndDrawing()
  204. self.Refresh()
  205. return
  206. if pdctype == 'image': # draw selected image
  207. bitmap = wx.BitmapFromImage(img)
  208. w,h = bitmap.GetSize()
  209. pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
  210. pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
  211. elif pdctype == 'box': # draw a box on top of the map
  212. if pen:
  213. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  214. pdc.SetPen(pen)
  215. x2 = max(coords[0],coords[2])
  216. x1 = min(coords[0],coords[2])
  217. y2 = max(coords[1],coords[3])
  218. y1 = min(coords[1],coords[3])
  219. rwidth = x2-x1
  220. rheight = y2-y1
  221. rect = wx.Rect(x1, y1, rwidth, rheight)
  222. pdc.DrawRectangleRect(rect)
  223. pdc.SetIdBounds(drawid, rect)
  224. elif pdctype == 'line': # draw a line on top of the map
  225. if pen:
  226. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  227. pdc.SetPen(pen)
  228. pdc.DrawLinePoint(wx.Point(coords[0], coords[1]),wx.Point(coords[2], coords[3]))
  229. pdc.SetIdBounds(drawid, wx.Rect(coords[0], coords[1], coords[2], coords[3]))
  230. elif pdctype == 'polyline': # draw a polyline on top of the map
  231. if pen:
  232. pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  233. pdc.SetPen(pen)
  234. if (len(coords) < 2):
  235. return
  236. i = 1
  237. while i < len(coords):
  238. pdc.DrawLinePoint(wx.Point(coords[i-1][0], coords[i-1][1]),
  239. wx.Point(coords[i][0], coords[i][1]))
  240. i += 1
  241. # get bounding rectangle for polyline
  242. xlist = []
  243. ylist = []
  244. if len(coords) > 0:
  245. for point in coords:
  246. x,y = point
  247. xlist.append(x)
  248. ylist.append(y)
  249. x1 = min(xlist)
  250. x2 = max(xlist)
  251. y1 = min(ylist)
  252. y2 = max(ylist)
  253. pdc.SetIdBounds(drawid, wx.Rect(x1,y1,x2,y2))
  254. # self.ovlcoords[drawid] = [x1,y1,x2,y2]
  255. elif pdctype == 'point': # draw point
  256. if pen:
  257. pdc.SetPen(pen)
  258. pdc.DrawPoint(coords[0], coords[1])
  259. coordsBound = (coords[0] - 5,
  260. coords[1] - 5,
  261. coords[0] + 5,
  262. coords[1] + 5)
  263. pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
  264. elif pdctype == 'text': # draw text on top of map
  265. if not img['active']:
  266. return # only draw active text
  267. if 'rotation' in img:
  268. rotation = float(img['rotation'])
  269. else:
  270. rotation = 0.0
  271. w, h = self.GetFullTextExtent(img['text'])[0:2]
  272. pdc.SetFont(img['font'])
  273. pdc.SetTextForeground(img['color'])
  274. coords, bbox = self.TextBounds(img)
  275. if rotation == 0:
  276. pdc.DrawText(img['text'], coords[0], coords[1])
  277. else:
  278. pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
  279. pdc.SetIdBounds(drawid, bbox)
  280. pdc.EndDrawing()
  281. self.Refresh()
  282. return drawid
  283. def TextBounds(self, textinfo, relcoords = False):
  284. """!Return text boundary data
  285. @param textinfo text metadata (text, font, color, rotation)
  286. @param coords reference point
  287. @return coords of nonrotated text bbox (TL corner)
  288. @return bbox of rotated text bbox (wx.Rect)
  289. @return relCoords are text coord inside bbox
  290. """
  291. if 'rotation' in textinfo:
  292. rotation = float(textinfo['rotation'])
  293. else:
  294. rotation = 0.0
  295. coords = textinfo['coords']
  296. bbox = wx.Rect(coords[0], coords[1], 0, 0)
  297. relCoords = (0, 0)
  298. Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
  299. (textinfo['text'], rotation))
  300. self.Update()
  301. self.SetFont(textinfo['font'])
  302. w, h = self.GetTextExtent(textinfo['text'])
  303. if rotation == 0:
  304. bbox[2], bbox[3] = w, h
  305. if relcoords:
  306. return coords, bbox, relCoords
  307. else:
  308. return coords, bbox
  309. boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
  310. boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
  311. if rotation > 0 and rotation < 90:
  312. bbox[1] -= boxh
  313. relCoords = (0, boxh)
  314. elif rotation >= 90 and rotation < 180:
  315. bbox[0] -= boxw
  316. bbox[1] -= boxh
  317. relCoords = (boxw, boxh)
  318. elif rotation >= 180 and rotation < 270:
  319. bbox[0] -= boxw
  320. relCoords = (boxw, 0)
  321. bbox[2] = boxw
  322. bbox[3] = boxh
  323. bbox.Inflate(h,h)
  324. if relcoords:
  325. return coords, bbox, relCoords
  326. else:
  327. return coords, bbox
  328. def OnPaint(self, event):
  329. """!Draw PseudoDC's to buffered paint DC
  330. If self.redrawAll is False on self.pdcTmp content is re-drawn
  331. """
  332. Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
  333. dc = wx.BufferedPaintDC(self, self._buffer)
  334. dc.Clear()
  335. # use PrepareDC to set position correctly
  336. # probably does nothing, removed from wxPython 2.9
  337. # self.PrepareDC(dc)
  338. # create a clipping rect from our position and size
  339. # and update region
  340. rgn = self.GetUpdateRegion().GetBox()
  341. dc.SetClippingRect(rgn)
  342. switchDraw = False
  343. if self.redrawAll is None:
  344. self.redrawAll = True
  345. switchDraw = True
  346. if self.redrawAll: # redraw pdc and pdcVector
  347. # draw to the dc using the calculated clipping rect
  348. self.pdc.DrawToDCClipped(dc, rgn)
  349. # draw vector map layer
  350. if hasattr(self, "digit"):
  351. # decorate with GDDC (transparency)
  352. try:
  353. gcdc = wx.GCDC(dc)
  354. self.pdcVector.DrawToDCClipped(gcdc, rgn)
  355. except NotImplementedError, e:
  356. print >> sys.stderr, e
  357. self.pdcVector.DrawToDCClipped(dc, rgn)
  358. self.bufferLast = None
  359. else: # do not redraw pdc and pdcVector
  360. if self.bufferLast is None:
  361. # draw to the dc
  362. self.pdc.DrawToDC(dc)
  363. if hasattr(self, "digit"):
  364. # decorate with GDDC (transparency)
  365. try:
  366. gcdc = wx.GCDC(dc)
  367. self.pdcVector.DrawToDC(gcdc)
  368. except NotImplementedError, e:
  369. print >> sys.stderr, e
  370. self.pdcVector.DrawToDC(dc)
  371. # store buffered image
  372. # self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
  373. self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
  374. self.pdc.DrawBitmap(self.bufferLast, 0, 0, False)
  375. self.pdc.DrawToDC(dc)
  376. # draw decorations (e.g. region box)
  377. try:
  378. gcdc = wx.GCDC(dc)
  379. self.pdcDec.DrawToDC(gcdc)
  380. except NotImplementedError, e:
  381. print >> sys.stderr, e
  382. self.pdcDec.DrawToDC(dc)
  383. # draw temporary object on the foreground
  384. ### self.pdcTmp.DrawToDCClipped(dc, rgn)
  385. self.pdcTmp.DrawToDC(dc)
  386. if switchDraw:
  387. self.redrawAll = False
  388. def OnSize(self, event):
  389. """!Scale map image so that it is the same size as the Window
  390. """
  391. # re-render image on idle
  392. self.resize = time.clock()
  393. def OnIdle(self, event):
  394. """!Only re-render a composite map image from GRASS during
  395. idle time instead of multiple times during resizing.
  396. """
  397. # use OnInternalIdle() instead ?
  398. if self.resize and self.resize + 0.2 < time.clock():
  399. Debug.msg(3, "BufferedWindow.OnSize():")
  400. # set size of the input image
  401. self.Map.ChangeMapSize(self.GetClientSize())
  402. # Make new off screen bitmap: this bitmap will always have the
  403. # current drawing in it, so it can be used to save the image to
  404. # a file, or whatever.
  405. self._buffer.Destroy()
  406. self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
  407. # get the image to be rendered
  408. self.img = self.GetImage()
  409. # update map display
  410. updatemap = True
  411. if self.img and self.Map.width + self.Map.height > 0: # scale image after resize
  412. self.img = self.img.Scale(self.Map.width, self.Map.height)
  413. if len(self.Map.GetListOfLayers()) > 0:
  414. self.UpdateMap()
  415. updatemap = False
  416. if updatemap:
  417. self.UpdateMap(render = True)
  418. self.resize = False
  419. elif self.resize:
  420. event.RequestMore()
  421. event.Skip()
  422. def SaveToFile(self, FileName, FileType, width, height):
  423. """!This draws the pseudo DC to a buffer that can be saved to
  424. a file.
  425. @param FileName file name
  426. @param FileType type of bitmap
  427. @param width image width
  428. @param height image height
  429. """
  430. busy = wx.BusyInfo(message = _("Please wait, exporting image..."),
  431. parent = self)
  432. wx.Yield()
  433. self.Map.ChangeMapSize((width, height))
  434. ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
  435. self.Map.Render(force = True, windres = self._properties.resolution)
  436. img = self.GetImage()
  437. self.pdc.RemoveAll()
  438. self.Draw(self.pdc, img, drawid = 99)
  439. # compute size ratio to move overlay accordingly
  440. cSize = self.GetClientSizeTuple()
  441. ratio = float(width) / cSize[0], float(height) / cSize[1]
  442. # redraw legend, scalebar
  443. for img in self.GetOverlay():
  444. # draw any active and defined overlays
  445. if self.imagedict[img]['layer'].IsActive():
  446. id = self.imagedict[img]['id']
  447. coords = int(ratio[0] * self.overlays[id].coords[0]),\
  448. int(ratio[1] * self.overlays[id].coords[1])
  449. self.Draw(self.pdc, img = img, drawid = id,
  450. pdctype = self.overlays[id].pdcType, coords = coords)
  451. # redraw text labels
  452. for id in self.textdict.keys():
  453. textinfo = self.textdict[id]
  454. oldCoords = textinfo['coords']
  455. textinfo['coords'] = ratio[0] * textinfo['coords'][0],\
  456. ratio[1] * textinfo['coords'][1]
  457. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  458. pdctype = 'text')
  459. # set back old coordinates
  460. textinfo['coords'] = oldCoords
  461. dc = wx.BufferedDC(None, ibuffer)
  462. dc.Clear()
  463. # probably does nothing, removed from wxPython 2.9
  464. # self.PrepareDC(dc)
  465. self.pdc.DrawToDC(dc)
  466. if self.pdcVector:
  467. self.pdcVector.DrawToDC(dc)
  468. ibuffer.SaveFile(FileName, FileType)
  469. busy.Destroy()
  470. self.UpdateMap(render = True)
  471. self.Refresh()
  472. def GetOverlay(self):
  473. """!Converts rendered overlay files to wx.Image
  474. Updates self.imagedict
  475. @return list of images
  476. """
  477. imgs = []
  478. for overlay in self.Map.GetListOfLayers(ltype = "overlay", active = True):
  479. if overlay.mapfile is not None \
  480. and os.path.isfile(overlay.mapfile) and os.path.getsize(overlay.mapfile):
  481. img = wx.Image(overlay.mapfile, wx.BITMAP_TYPE_ANY)
  482. for key in self.imagedict.keys():
  483. if self.imagedict[key]['id'] == overlay.id:
  484. del self.imagedict[key]
  485. self.imagedict[img] = { 'id' : overlay.id,
  486. 'layer' : overlay }
  487. imgs.append(img)
  488. return imgs
  489. def GetImage(self):
  490. """!Converts redered map files to wx.Image
  491. Updates self.imagedict (id=99)
  492. @return wx.Image instance (map composition)
  493. """
  494. imgId = 99
  495. if self.mapfile and self.Map.mapfile and os.path.isfile(self.Map.mapfile) and \
  496. os.path.getsize(self.Map.mapfile):
  497. img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
  498. else:
  499. img = None
  500. for key in self.imagedict.keys():
  501. if self.imagedict[key]['id'] == imgId:
  502. del self.imagedict[key]
  503. self.imagedict[img] = { 'id': imgId }
  504. return img
  505. def SetAlwaysRenderEnabled(self, alwaysRender = True):
  506. self.alwaysRender = alwaysRender
  507. def IsAlwaysRenderEnabled(self):
  508. return self.alwaysRender
  509. def UpdateMap(self, render = True, renderVector = True):
  510. """!Updates the canvas anytime there is a change to the
  511. underlaying images or to the geometry of the canvas.
  512. This method should not be called directly.
  513. @todo change direct calling of UpdateMap method to emittig grass
  514. interface updateMap signal
  515. @param render re-render map composition
  516. @param renderVector re-render vector map layer enabled for editing (used for digitizer)
  517. """
  518. start = time.clock()
  519. self.resize = False
  520. # was if self.Map.cmdfile and ...
  521. if self.IsAlwaysRenderEnabled() and self.img is None:
  522. render = True
  523. #
  524. # render background image if needed
  525. #
  526. # here was the change of the layertree rerender variable
  527. # but it is fully the problem of layertree
  528. # and so it is handled there
  529. # remove this comment when it is old enough
  530. try:
  531. if render:
  532. # update display size
  533. self.Map.ChangeMapSize(self.GetClientSize())
  534. if self._properties.resolution:
  535. # use computation region resolution for rendering
  536. windres = True
  537. else:
  538. windres = False
  539. self.mapfile = self.Map.Render(force = True,
  540. windres = windres)
  541. else:
  542. self.mapfile = self.Map.Render(force = False)
  543. except GException, e:
  544. GError(message = e.value)
  545. self.mapfile = None
  546. self.img = self.GetImage() # id=99
  547. #
  548. # clear pseudoDcs
  549. #
  550. for pdc in (self.pdc,
  551. self.pdcDec,
  552. self.pdcTmp):
  553. pdc.Clear()
  554. pdc.RemoveAll()
  555. #
  556. # draw background map image to PseudoDC
  557. #
  558. if not self.img:
  559. self.Draw(self.pdc, pdctype = 'clear')
  560. else:
  561. try:
  562. id = self.imagedict[self.img]['id']
  563. except:
  564. return False
  565. self.Draw(self.pdc, self.img, drawid = id)
  566. #
  567. # render vector map layer
  568. #
  569. if renderVector and hasattr(self, "digit"):
  570. self._updateMap()
  571. #
  572. # render overlays
  573. #
  574. for img in self.GetOverlay():
  575. # draw any active and defined overlays
  576. if self.imagedict[img]['layer'].IsActive():
  577. id = self.imagedict[img]['id']
  578. self.Draw(self.pdc, img = img, drawid = id,
  579. pdctype = self.overlays[id].pdcType, coords = self.overlays[id].coords)
  580. for id in self.textdict.keys():
  581. self.Draw(self.pdc, img = self.textdict[id], drawid = id,
  582. pdctype = 'text', coords = [10, 10, 10, 10])
  583. # optionally draw computational extent box
  584. self.DrawCompRegionExtent()
  585. #
  586. # redraw pdcTmp if needed
  587. #
  588. # draw registered graphics
  589. if len(self.graphicsSetList) > 0:
  590. penOrig = self.pen
  591. polypenOrig = self.polypen
  592. for item in self.graphicsSetList:
  593. try:
  594. item.Draw(self.pdcTmp)
  595. except:
  596. GError(parent = self,
  597. message = _('Unable to draw registered graphics. '
  598. 'The graphics was unregistered.'))
  599. self.UnregisterGraphicsToDraw(item)
  600. self.pen = penOrig
  601. self.polypen = polypenOrig
  602. if len(self.polycoords) > 0:
  603. self.DrawLines(self.pdcTmp)
  604. stop = time.clock()
  605. Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
  606. (render, renderVector, (stop-start)))
  607. return True
  608. def DrawCompRegionExtent(self):
  609. """!Draw computational region extent in the display
  610. Display region is drawn as a blue box inside the computational region,
  611. computational region inside a display region as a red box).
  612. """
  613. if self._properties.showRegion:
  614. compReg = self.Map.GetRegion()
  615. dispReg = self.Map.GetCurrentRegion()
  616. reg = None
  617. if utils.isInRegion(dispReg, compReg):
  618. self.polypen = wx.Pen(colour = wx.Colour(0, 0, 255, 128), width = 3, style = wx.SOLID)
  619. reg = dispReg
  620. else:
  621. self.polypen = wx.Pen(colour = wx.Colour(255, 0, 0, 128),
  622. width = 3, style = wx.SOLID)
  623. reg = compReg
  624. regionCoords = []
  625. regionCoords.append((reg['w'], reg['n']))
  626. regionCoords.append((reg['e'], reg['n']))
  627. regionCoords.append((reg['e'], reg['s']))
  628. regionCoords.append((reg['w'], reg['s']))
  629. regionCoords.append((reg['w'], reg['n']))
  630. # draw region extent
  631. self.DrawLines(pdc=self.pdcDec, polycoords=regionCoords)
  632. def EraseMap(self):
  633. """!Erase map canvas
  634. """
  635. self.Draw(self.pdc, pdctype = 'clear')
  636. if hasattr(self, "digit"):
  637. self.Draw(self.pdcVector, pdctype = 'clear')
  638. self.Draw(self.pdcDec, pdctype = 'clear')
  639. self.Draw(self.pdcTmp, pdctype = 'clear')
  640. self.Map.AbortAllThreads()
  641. def DragMap(self, moveto):
  642. """!Drag the entire map image for panning.
  643. @param moveto dx,dy
  644. """
  645. dc = wx.BufferedDC(wx.ClientDC(self))
  646. dc.SetBackground(wx.Brush("White"))
  647. dc.Clear()
  648. self.dragimg = wx.DragImage(self._buffer)
  649. self.dragimg.BeginDrag((0, 0), self)
  650. self.dragimg.GetImageRect(moveto)
  651. self.dragimg.Move(moveto)
  652. self.dragimg.DoDrawImage(dc, moveto)
  653. self.dragimg.EndDrag()
  654. def DragItem(self, id, coords):
  655. """!Drag an overlay decoration item
  656. """
  657. if id == 99 or id == '' or id == None: return
  658. Debug.msg (5, "BufferedWindow.DragItem(): id=%d" % id)
  659. x, y = self.lastpos
  660. dx = coords[0] - x
  661. dy = coords[1] - y
  662. self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
  663. r = self.pdc.GetIdBounds(id)
  664. if type(r) is list:
  665. r = wx.Rect(r[0], r[1], r[2], r[3])
  666. if id > 100: # text dragging
  667. rtop = (r[0],r[1]-r[3],r[2],r[3])
  668. r = r.Union(rtop)
  669. rleft = (r[0]-r[2],r[1],r[2],r[3])
  670. r = r.Union(rleft)
  671. self.pdc.TranslateId(id, dx, dy)
  672. r2 = self.pdc.GetIdBounds(id)
  673. if type(r2) is list:
  674. r2 = wx.Rect(r[0], r[1], r[2], r[3])
  675. if id > 100: # text
  676. self.textdict[id]['bbox'] = r2
  677. self.textdict[id]['coords'][0] += dx
  678. self.textdict[id]['coords'][1] += dy
  679. r = r.Union(r2)
  680. r.Inflate(4,4)
  681. self.RefreshRect(r, False)
  682. self.lastpos = (coords[0], coords[1])
  683. def MouseDraw(self, pdc = None, begin = None, end = None):
  684. """!Mouse box or line from 'begin' to 'end'
  685. If not given from self.mouse['begin'] to self.mouse['end'].
  686. """
  687. if not pdc:
  688. return
  689. if begin is None:
  690. begin = self.mouse['begin']
  691. if end is None:
  692. end = self.mouse['end']
  693. Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
  694. (self.mouse['use'], self.mouse['box'],
  695. begin[0], begin[1], end[0], end[1]))
  696. if self.mouse['box'] == "box":
  697. boxid = wx.ID_NEW
  698. mousecoords = [begin[0], begin[1],
  699. end[0], end[1]]
  700. r = pdc.GetIdBounds(boxid)
  701. if type(r) is list:
  702. r = wx.Rect(r[0], r[1], r[2], r[3])
  703. r.Inflate(4, 4)
  704. try:
  705. pdc.ClearId(boxid)
  706. except:
  707. pass
  708. self.RefreshRect(r, False)
  709. pdc.SetId(boxid)
  710. self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
  711. elif self.mouse['box'] == "line":
  712. self.lineid = wx.ID_NEW
  713. mousecoords = [begin[0], begin[1], \
  714. end[0], end[1]]
  715. x1 = min(begin[0],end[0])
  716. x2 = max(begin[0],end[0])
  717. y1 = min(begin[1],end[1])
  718. y2 = max(begin[1],end[1])
  719. r = wx.Rect(x1,y1,x2-x1,y2-y1)
  720. r.Inflate(4,4)
  721. try:
  722. pdc.ClearId(self.lineid)
  723. except:
  724. pass
  725. self.RefreshRect(r, False)
  726. pdc.SetId(self.lineid)
  727. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = mousecoords)
  728. def DrawLines(self, pdc = None, polycoords = None):
  729. """!Draw polyline in PseudoDC
  730. Set self.pline to wx.NEW_ID + 1
  731. polycoords - list of polyline vertices, geographical coordinates
  732. (if not given, self.polycoords is used)
  733. """
  734. if not pdc:
  735. pdc = self.pdcTmp
  736. if not polycoords:
  737. polycoords = self.polycoords
  738. if len(polycoords) > 0:
  739. self.plineid = wx.ID_NEW + 1
  740. # convert from EN to XY
  741. coords = []
  742. for p in polycoords:
  743. coords.append(self.Cell2Pixel(p))
  744. self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
  745. Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
  746. (coords, self.plineid))
  747. return self.plineid
  748. return -1
  749. def DrawCross(self, pdc, coords, size, rotation = 0, pen = None,
  750. text = None, textAlign = 'lr', textOffset = (5, 5)):
  751. """!Draw cross in PseudoDC
  752. @todo implement rotation
  753. @param pdc PseudoDC
  754. @param coords center coordinates
  755. @param rotation rotate symbol
  756. @param text draw also text (text, font, color, rotation)
  757. @param textAlign alignment (default 'lower-right')
  758. @param textOffset offset for text (from center point)
  759. """
  760. Debug.msg(4, "BufferedWindow.DrawCross(): pdc=%s, coords=%s, size=%d" % \
  761. (pdc, coords, size))
  762. coordsCross = ((coords[0] - size, coords[1], coords[0] + size, coords[1]),
  763. (coords[0], coords[1] - size, coords[0], coords[1] + size))
  764. self.lineid = wx.NewId()
  765. for lineCoords in coordsCross:
  766. self.Draw(pdc, drawid = self.lineid, pdctype = 'line', coords = lineCoords, pen = pen)
  767. if not text:
  768. return self.lineid
  769. if textAlign == 'ul':
  770. coord = [coords[0] - textOffset[0], coords[1] - textOffset[1], 0, 0]
  771. elif textAlign == 'ur':
  772. coord = [coords[0] + textOffset[0], coords[1] - textOffset[1], 0, 0]
  773. elif textAlign == 'lr':
  774. coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
  775. else:
  776. coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
  777. self.Draw(pdc, img = text,
  778. pdctype = 'text', coords = coord, pen = pen)
  779. return self.lineid
  780. def _computeZoomToPointAndRecenter(self, position, zoomtype):
  781. """!Computes zoom parameters for recenter mode.
  782. Computes begin and end parameters for Zoom() method.
  783. Used for zooming by single click (not box)
  784. and mouse wheel zooming (zoom and recenter mode).
  785. """
  786. if zoomtype > 0:
  787. begin = (position[0] - self.Map.width / 4,
  788. position[1] - self.Map.height / 4)
  789. end = (position[0] + self.Map.width / 4,
  790. position[1] + self.Map.height / 4)
  791. else:
  792. begin = ((self.Map.width - position[0]) / 2,
  793. (self.Map.height - position[1]) / 2)
  794. end = (begin[0] + self.Map.width / 2,
  795. begin[1] + self.Map.height / 2)
  796. return begin, end
  797. def MouseActions(self, event):
  798. """!Mouse motion and button click notifier
  799. """
  800. if not self.processMouse:
  801. return
  802. # zoom with mouse wheel
  803. if event.GetWheelRotation() != 0:
  804. self.OnMouseWheel(event)
  805. # left mouse button pressed
  806. elif event.LeftDown():
  807. self.OnLeftDown(event)
  808. # left mouse button released
  809. elif event.LeftUp():
  810. self.OnLeftUp(event)
  811. # dragging
  812. elif event.Dragging():
  813. self.OnDragging(event)
  814. # double click
  815. elif event.ButtonDClick():
  816. self.OnButtonDClick(event)
  817. # middle mouse button pressed
  818. elif event.MiddleDown():
  819. self.OnMiddleDown(event)
  820. # middle mouse button relesed
  821. elif event.MiddleUp():
  822. self.OnMiddleUp(event)
  823. # right mouse button pressed
  824. elif event.RightDown():
  825. self.OnRightDown(event)
  826. # right mouse button released
  827. elif event.RightUp():
  828. self.OnRightUp(event)
  829. elif event.Entering():
  830. self.OnMouseEnter(event)
  831. elif event.Moving():
  832. pixelCoordinates = event.GetPositionTuple()[:]
  833. coordinates = self.Pixel2Cell(pixelCoordinates)
  834. self.mouseMoving.emit(x=coordinates[0], y=coordinates[1])
  835. self.OnMouseMoving(event)
  836. def OnMouseWheel(self, event):
  837. """!Mouse wheel moved
  838. """
  839. zoomBehaviour = UserSettings.Get(group = 'display',
  840. key = 'mouseWheelZoom',
  841. subkey = 'selection')
  842. if zoomBehaviour == 2:
  843. event.Skip()
  844. return
  845. self.processMouse = False
  846. current = event.GetPositionTuple()[:]
  847. wheel = event.GetWheelRotation()
  848. Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
  849. if wheel > 0:
  850. zoomtype = 1
  851. else:
  852. zoomtype = -1
  853. if UserSettings.Get(group = 'display',
  854. key = 'scrollDirection',
  855. subkey = 'selection'):
  856. zoomtype *= -1
  857. # zoom 1/2 of the screen (TODO: settings)
  858. if zoomBehaviour == 0: # zoom and recenter
  859. begin, end = self._computeZoomToPointAndRecenter(position = current, zoomtype = zoomtype)
  860. elif zoomBehaviour == 1: # zoom to current cursor position
  861. begin = (current[0]/2, current[1]/2)
  862. end = ((self.Map.width - current[0])/2 + current[0],
  863. (self.Map.height - current[1])/2 + current[1])
  864. # zoom
  865. self.Zoom(begin, end, zoomtype)
  866. # redraw map
  867. self.UpdateMap()
  868. self.Refresh()
  869. self.processMouse = True
  870. def OnDragging(self, event):
  871. """!Mouse dragging
  872. """
  873. Debug.msg (5, "BufferedWindow.MouseAction(): Dragging")
  874. current = event.GetPositionTuple()[:]
  875. previous = self.mouse['begin']
  876. move = (current[0] - previous[0],
  877. current[1] - previous[1])
  878. if hasattr(self, "digit"):
  879. digitToolbar = self.toolbar
  880. else:
  881. digitToolbar = None
  882. # dragging or drawing box with left button
  883. if self.mouse['use'] == 'pan' or \
  884. event.MiddleIsDown():
  885. self.DragMap(move)
  886. # dragging decoration overlay item
  887. elif (self.mouse['use'] == 'pointer' and
  888. not digitToolbar and
  889. self.dragid != None):
  890. coords = event.GetPositionTuple()
  891. self.DragItem(self.dragid, coords)
  892. # dragging anything else - rubber band box or line
  893. else:
  894. if (self.mouse['use'] == 'pointer' and
  895. not digitToolbar):
  896. return
  897. self.mouse['end'] = event.GetPositionTuple()[:]
  898. if (event.LeftIsDown() and
  899. not (digitToolbar and
  900. digitToolbar.GetAction() in ("moveLine",) and
  901. self.digit.GetDisplay().GetSelected() > 0)):
  902. self.MouseDraw(pdc = self.pdcTmp)
  903. def OnLeftDown(self, event):
  904. """!Left mouse button pressed
  905. """
  906. Debug.msg (5, "BufferedWindow.OnLeftDown(): use=%s" % \
  907. self.mouse["use"])
  908. self.mouse['begin'] = event.GetPositionTuple()[:]
  909. # vector digizer
  910. if self.mouse["use"] == "pointer" and \
  911. hasattr(self, "digit"):
  912. if event.ControlDown():
  913. self.OnLeftDownUndo(event)
  914. else:
  915. self._onLeftDown(event)
  916. elif self.mouse['use'] == 'pointer':
  917. # get decoration or text id
  918. idlist = []
  919. self.dragid = ''
  920. self.lastpos = self.mouse['begin']
  921. idlist = self.pdc.FindObjects(self.lastpos[0], self.lastpos[1],
  922. self.hitradius)
  923. if 99 in idlist:
  924. idlist.remove(99)
  925. if idlist != []:
  926. self.dragid = idlist[0] #drag whatever is on top
  927. else:
  928. pass
  929. coords = self.Pixel2Cell(self.mouse['begin'])
  930. self.mouseLeftDown.emit(x=coords[0], y=coords[1])
  931. event.Skip()
  932. def OnLeftUp(self, event):
  933. """!Left mouse button released
  934. Emits mapQueried signal when mouse use is 'query'.
  935. """
  936. Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
  937. self.mouse["use"])
  938. self.mouse['end'] = event.GetPositionTuple()[:]
  939. coordinates = self.Pixel2Cell(self.mouse['end'])
  940. if self.mouse['use'] in ["zoom", "pan"]:
  941. # set region in zoom or pan
  942. begin = self.mouse['begin']
  943. end = self.mouse['end']
  944. if self.mouse['use'] == 'zoom':
  945. # set region for click (zero-width box)
  946. if begin[0] - end[0] == 0 or \
  947. begin[1] - end[1] == 0:
  948. begin, end = self._computeZoomToPointAndRecenter(position = end, zoomtype = self.zoomtype)
  949. self.Zoom(begin, end, self.zoomtype)
  950. # redraw map
  951. self.UpdateMap(render = True)
  952. elif self.mouse["use"] == "query":
  953. self.mapQueried.emit(x=self.mouse['end'][0], y=self.mouse['end'][1])
  954. elif self.mouse["use"] == "pointer" and \
  955. hasattr(self, "digit"):
  956. self._onLeftUp(event)
  957. elif (self.mouse['use'] == 'pointer' and
  958. self.dragid >= 0):
  959. # end drag of overlay decoration
  960. if self.dragid < 99 and self.dragid in self.overlays:
  961. self.overlays[self.dragid].coords = self.pdc.GetIdBounds(self.dragid)
  962. elif self.dragid > 100 and self.dragid in self.textdict:
  963. self.textdict[self.dragid]['bbox'] = self.pdc.GetIdBounds(self.dragid)
  964. else:
  965. pass
  966. self.dragid = None
  967. self.mouseLeftUpPointer.emit(x=coordinates[0], y=coordinates[1])
  968. # TODO: decide which coordinates to send (e, n, mouse['begin'], mouse['end'])
  969. self.mouseLeftUp.emit(x=coordinates[0], y=coordinates[1])
  970. def OnButtonDClick(self, event):
  971. """!Mouse button double click
  972. """
  973. Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
  974. self.mouse["use"])
  975. screenCoords = event.GetPosition()
  976. if self.mouse['use'] == 'pointer':
  977. # select overlay decoration options dialog
  978. idlist = self.pdc.FindObjects(screenCoords[0], screenCoords[1], self.hitradius)
  979. if idlist:
  980. self.dragid = idlist[0]
  981. self.overlayActivated.emit(overlayId=self.dragid)
  982. coords = self.Pixel2Cell(screenCoords)
  983. self.mouseDClick.emit(x=coords[0], y=coords[1])
  984. def OnRightDown(self, event):
  985. """!Right mouse button pressed
  986. """
  987. Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
  988. self.mouse["use"])
  989. if hasattr(self, "digit"):
  990. self._onRightDown(event)
  991. event.Skip()
  992. def OnRightUp(self, event):
  993. """!Right mouse button released
  994. """
  995. Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
  996. self.mouse["use"])
  997. if hasattr(self, "digit"):
  998. self._onRightUp(event)
  999. self.redrawAll = True
  1000. self.Refresh()
  1001. event.Skip()
  1002. def OnMiddleDown(self, event):
  1003. """!Middle mouse button pressed
  1004. """
  1005. if not event:
  1006. return
  1007. self.mouse['begin'] = event.GetPositionTuple()[:]
  1008. def OnMiddleUp(self, event):
  1009. """!Middle mouse button released
  1010. """
  1011. self.mouse['end'] = event.GetPositionTuple()[:]
  1012. # set region in zoom or pan
  1013. begin = self.mouse['begin']
  1014. end = self.mouse['end']
  1015. self.Zoom(begin, end, 0) # no zoom
  1016. # redraw map
  1017. self.UpdateMap(render = True)
  1018. def OnMouseEnter(self, event):
  1019. """!Mouse entered window and no mouse buttons were pressed
  1020. Emits the mouseEntered signal.
  1021. """
  1022. self.mouseEntered.emit()
  1023. event.Skip()
  1024. def OnMouseMoving(self, event):
  1025. """!Motion event and no mouse buttons were pressed
  1026. """
  1027. if self.mouse["use"] == "pointer" and \
  1028. hasattr(self, "digit"):
  1029. self._onMouseMoving(event)
  1030. event.Skip()
  1031. def OnCopyCoordinates(self, event):
  1032. """!Copy coordinates to cliboard"""
  1033. e, n = self.GetLastEN()
  1034. if wx.TheClipboard.Open():
  1035. do = wx.TextDataObject()
  1036. # TODO: put delimiter in settings and apply also for Go to in statusbar
  1037. delim = ';'
  1038. do.SetText(str(e) + delim + str(n))
  1039. wx.TheClipboard.SetData(do)
  1040. wx.TheClipboard.Close()
  1041. def ClearLines(self, pdc = None):
  1042. """!Clears temporary drawn lines from PseudoDC
  1043. """
  1044. if not pdc:
  1045. pdc = self.pdcTmp
  1046. try:
  1047. pdc.ClearId(self.lineid)
  1048. pdc.RemoveId(self.lineid)
  1049. except:
  1050. pass
  1051. try:
  1052. pdc.ClearId(self.plineid)
  1053. pdc.RemoveId(self.plineid)
  1054. except:
  1055. pass
  1056. Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
  1057. (self.lineid, self.plineid))
  1058. return True
  1059. def Pixel2Cell(self, xyCoords):
  1060. """!Convert image coordinates to real word coordinates
  1061. @param x, y image coordinates
  1062. @return easting, northing
  1063. @return None on error
  1064. """
  1065. try:
  1066. x = int(xyCoords[0])
  1067. y = int(xyCoords[1])
  1068. except:
  1069. return None
  1070. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1071. res = self.Map.region["ewres"]
  1072. else:
  1073. res = self.Map.region["nsres"]
  1074. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1075. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1076. east = w + x * res
  1077. north = n - y * res
  1078. return (east, north)
  1079. def Cell2Pixel(self, enCoords):
  1080. """!Convert real word coordinates to image coordinates
  1081. """
  1082. try:
  1083. east = float(enCoords[0])
  1084. north = float(enCoords[1])
  1085. except:
  1086. return None
  1087. if self.Map.region["ewres"] > self.Map.region["nsres"]:
  1088. res = self.Map.region["ewres"]
  1089. else:
  1090. res = self.Map.region["nsres"]
  1091. w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
  1092. n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
  1093. x = (east - w) / res
  1094. y = (n - north) / res
  1095. return (x, y)
  1096. def Zoom(self, begin, end, zoomtype):
  1097. """!Calculates new region while (un)zoom/pan-ing
  1098. """
  1099. x1, y1 = begin
  1100. x2, y2 = end
  1101. newreg = {}
  1102. # threshold - too small squares do not make sense
  1103. # can only zoom to windows of > 5x5 screen pixels
  1104. if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
  1105. if x1 > x2:
  1106. x1, x2 = x2, x1
  1107. if y1 > y2:
  1108. y1, y2 = y2, y1
  1109. # zoom in
  1110. if zoomtype > 0:
  1111. newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
  1112. newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
  1113. # zoom out
  1114. elif zoomtype < 0:
  1115. newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
  1116. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + 2 * \
  1117. (self.Map.width - x2),
  1118. self.Map.height + 2 * \
  1119. (self.Map.height - y2)))
  1120. # pan
  1121. elif zoomtype == 0:
  1122. dx = x1 - x2
  1123. dy = y1 - y2
  1124. if dx == 0 and dy == 0:
  1125. dx = x1 - self.Map.width / 2
  1126. dy = y1 - self.Map.height / 2
  1127. newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
  1128. newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
  1129. self.Map.height + dy))
  1130. # if new region has been calculated, set the values
  1131. if newreg != {}:
  1132. # LL locations
  1133. if self.Map.projinfo['proj'] == 'll':
  1134. self.Map.region['n'] = min(self.Map.region['n'], 90.0)
  1135. self.Map.region['s'] = max(self.Map.region['s'], -90.0)
  1136. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1137. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1138. # calculate new center point and display resolution
  1139. self.Map.region['center_easting'] = ce
  1140. self.Map.region['center_northing'] = cn
  1141. self.Map.region['ewres'] = (newreg['e'] - newreg['w']) / self.Map.width
  1142. self.Map.region['nsres'] = (newreg['n'] - newreg['s']) / self.Map.height
  1143. if self._properties.alignExtent:
  1144. self.Map.AlignExtentFromDisplay()
  1145. else:
  1146. for k in ('n', 's', 'e', 'w'):
  1147. self.Map.region[k] = newreg[k]
  1148. if hasattr(self, "digit") and \
  1149. hasattr(self, "moveInfo"):
  1150. self._zoom(None)
  1151. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1152. self.Map.region['e'], self.Map.region['w'])
  1153. if self.redrawAll is False:
  1154. self.redrawAll = True
  1155. def ZoomBack(self):
  1156. """!Zoom to previous extents in zoomhistory list
  1157. Emits zoomChanged signal.
  1158. Emits zoomHistoryUnavailable signal when stack is empty.
  1159. """
  1160. Debug.msg(4, "BufferedWindow.ZoomBack(): hist)=%s" % self.zoomhistory)
  1161. zoom = list()
  1162. if len(self.zoomhistory) > 1:
  1163. self.zoomhistory.pop()
  1164. zoom = self.zoomhistory[-1]
  1165. if len(self.zoomhistory) < 2:
  1166. self.zoomHistoryUnavailable.emit()
  1167. # zoom to selected region
  1168. self.Map.GetRegion(n = zoom[0], s = zoom[1],
  1169. e = zoom[2], w = zoom[3],
  1170. update = True)
  1171. # update map
  1172. self.UpdateMap()
  1173. self.zoomChanged.emit()
  1174. def ZoomHistory(self, n, s, e, w):
  1175. """!Manages a list of last 10 zoom extents
  1176. Emits zoomChanged signal.
  1177. Emits zoomHistoryAvailable signal when stack is not empty.
  1178. Emits zoomHistoryUnavailable signal when stack is empty.
  1179. All methods which are changing zoom should call this method
  1180. to make a record in the history. The signal zoomChanged will be
  1181. then emitted automatically.
  1182. @param n,s,e,w north, south, east, west
  1183. @return removed history item if exists (or None)
  1184. """
  1185. removed = None
  1186. self.zoomhistory.append((n,s,e,w))
  1187. if len(self.zoomhistory) > 10:
  1188. removed = self.zoomhistory.pop(0)
  1189. if removed:
  1190. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
  1191. (self.zoomhistory, removed))
  1192. else:
  1193. Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
  1194. (self.zoomhistory))
  1195. # update toolbar
  1196. if len(self.zoomhistory) > 1:
  1197. self.zoomHistoryAvailable.emit()
  1198. else:
  1199. self.zoomHistoryUnavailable.emit()
  1200. self.zoomChanged.emit()
  1201. return removed
  1202. def InitZoomHistory(self):
  1203. """Initializes zoom history.
  1204. @todo First item is handled in some special way. Improve the
  1205. documentation or fix the code.
  1206. It does not emits any signals.
  1207. This method can be possibly removed when the history will solve the
  1208. fist item in different way or when GCP manager (and possibly others)
  1209. will handle Map variable in the way that it will be prepared for
  1210. MapWindow/BufferedWindow and thus usable to initialize history.
  1211. """
  1212. self.zoomhistory.append((self.Map.region['n'],
  1213. self.Map.region['s'],
  1214. self.Map.region['e'],
  1215. self.Map.region['w']))
  1216. Debug.msg(4, "BufferedWindow.InitZoomHistory(): hist=%s" %
  1217. (self.zoomhistory))
  1218. def ResetZoomHistory(self):
  1219. """!Reset zoom history"""
  1220. self.zoomhistory = list()
  1221. def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
  1222. """!Set display extents to match selected raster
  1223. or vector map(s).
  1224. @param layers list of layers to be zoom to
  1225. @param ignoreNulls True to ignore null-values (valid only for rasters)
  1226. @param render True to re-render display
  1227. """
  1228. if not layers:
  1229. layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
  1230. layers = [layer.maplayer for layer in layers]
  1231. if not layers:
  1232. return
  1233. rast = []
  1234. vect = []
  1235. updated = False
  1236. for l in layers:
  1237. # only raster/vector layers are currently supported
  1238. if l.type == 'raster':
  1239. rast.append(l.GetName())
  1240. elif l.type == 'vector':
  1241. if hasattr(self, "digit") and \
  1242. self.toolbar.GetLayer() == l:
  1243. w, s, b, e, n, t = self.digit.GetDisplay().GetMapBoundingBox()
  1244. self.Map.GetRegion(n = n, s = s, w = w, e = e,
  1245. update = True)
  1246. updated = True
  1247. else:
  1248. vect.append(l.name)
  1249. elif l.type == 'rgb':
  1250. for rname in l.GetName().splitlines():
  1251. rast.append(rname)
  1252. if not updated:
  1253. self.Map.GetRegion(rast = rast,
  1254. vect = vect,
  1255. zoom = ignoreNulls,
  1256. update = True)
  1257. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1258. self.Map.region['e'], self.Map.region['w'])
  1259. if render:
  1260. self.UpdateMap()
  1261. def ZoomToWind(self):
  1262. """!Set display geometry to match computational region
  1263. settings (set with g.region)
  1264. """
  1265. self.Map.region = self.Map.GetRegion()
  1266. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1267. self.Map.region['e'], self.Map.region['w'])
  1268. self.UpdateMap()
  1269. def ZoomToDefault(self):
  1270. """!Set display geometry to match default region settings
  1271. """
  1272. self.Map.region = self.Map.GetRegion(default = True)
  1273. self.Map.AdjustRegion() # aling region extent to the display
  1274. self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1275. self.Map.region['e'], self.Map.region['w'])
  1276. self.UpdateMap()
  1277. def GoTo(self, e, n):
  1278. region = self.Map.GetCurrentRegion()
  1279. region['center_easting'], region['center_northing'] = e, n
  1280. dn = (region['nsres'] * region['rows']) / 2.
  1281. region['n'] = region['center_northing'] + dn
  1282. region['s'] = region['center_northing'] - dn
  1283. de = (region['ewres'] * region['cols']) / 2.
  1284. region['e'] = region['center_easting'] + de
  1285. region['w'] = region['center_easting'] - de
  1286. self.Map.AdjustRegion()
  1287. # add to zoom history
  1288. self.ZoomHistory(region['n'], region['s'],
  1289. region['e'], region['w'])
  1290. self.UpdateMap()
  1291. def DisplayToWind(self):
  1292. """!Set computational region (WIND file) to match display
  1293. extents
  1294. """
  1295. tmpreg = os.getenv("GRASS_REGION")
  1296. if tmpreg:
  1297. del os.environ["GRASS_REGION"]
  1298. # We ONLY want to set extents here. Don't mess with resolution. Leave that
  1299. # for user to set explicitly with g.region
  1300. new = self.Map.AlignResolution()
  1301. RunCommand('g.region',
  1302. parent = self,
  1303. overwrite = True,
  1304. n = new['n'],
  1305. s = new['s'],
  1306. e = new['e'],
  1307. w = new['w'],
  1308. rows = int(new['rows']),
  1309. cols = int(new['cols']))
  1310. if tmpreg:
  1311. os.environ["GRASS_REGION"] = tmpreg
  1312. def ZoomToSaved(self):
  1313. """!Set display geometry to match extents in
  1314. saved region file
  1315. """
  1316. dlg = SavedRegion(parent = self,
  1317. title = _("Zoom to saved region extents"),
  1318. loadsave = 'load')
  1319. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1320. dlg.Destroy()
  1321. return
  1322. if not grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1323. wx.MessageBox(parent = self,
  1324. message = _("Region <%s> not found. Operation canceled.") % dlg.GetName(),
  1325. caption = _("Error"), style = wx.ICON_ERROR | wx.OK | wx.CENTRE)
  1326. dlg.Destroy()
  1327. return
  1328. self.Map.GetRegion(regionName = dlg.GetName(),
  1329. update = True)
  1330. dlg.Destroy()
  1331. self.ZoomHistory(self.Map.region['n'],
  1332. self.Map.region['s'],
  1333. self.Map.region['e'],
  1334. self.Map.region['w'])
  1335. self.UpdateMap()
  1336. def SaveRegion(self, display = True):
  1337. """!Save display extents/compulational region to named region
  1338. file.
  1339. @param display True for display extends otherwise computational region
  1340. """
  1341. if display:
  1342. title = _("Save display extents to region file")
  1343. else:
  1344. title = _("Save computational region to region file")
  1345. dlg = SavedRegion(parent = self, title = title, loadsave = 'save')
  1346. if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
  1347. dlg.Destroy()
  1348. return
  1349. # test to see if it already exists and ask permission to overwrite
  1350. if grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
  1351. overwrite = wx.MessageBox(parent = self,
  1352. message = _("Region file <%s> already exists. "
  1353. "Do you want to overwrite it?") % (dlg.GetName()),
  1354. caption = _("Warning"), style = wx.YES_NO | wx.CENTRE)
  1355. if overwrite != wx.YES:
  1356. dlg.Destroy()
  1357. return
  1358. if display:
  1359. self._saveDisplayRegion(dlg.GetName())
  1360. else:
  1361. self._saveCompRegion(dlg.GetName())
  1362. dlg.Destroy()
  1363. def _saveCompRegion(self, name):
  1364. """!Save region settings to region file
  1365. @param name region name
  1366. """
  1367. RunCommand('g.region',
  1368. overwrite = True,
  1369. parent = self,
  1370. flags = 'u',
  1371. save = name)
  1372. def _saveDisplayRegion(self, name):
  1373. """!Save display extents to region file
  1374. @param name region name
  1375. """
  1376. new = self.Map.GetCurrentRegion()
  1377. tmpreg = os.getenv("GRASS_REGION")
  1378. if tmpreg:
  1379. del os.environ["GRASS_REGION"]
  1380. RunCommand('g.region',
  1381. overwrite = True,
  1382. parent = self,
  1383. flags = 'u',
  1384. n = new['n'],
  1385. s = new['s'],
  1386. e = new['e'],
  1387. w = new['w'],
  1388. rows = int(new['rows']),
  1389. cols = int(new['cols']),
  1390. save = name)
  1391. if tmpreg:
  1392. os.environ["GRASS_REGION"] = tmpreg
  1393. def Distance(self, beginpt, endpt, screen = True):
  1394. """!Calculates distance
  1395. Ctypes required for LL-locations
  1396. @param beginpt first point
  1397. @param endpt second point
  1398. @param screen True for screen coordinates otherwise EN
  1399. """
  1400. if screen:
  1401. e1, n1 = self.Pixel2Cell(beginpt)
  1402. e2, n2 = self.Pixel2Cell(endpt)
  1403. else:
  1404. e1, n1 = beginpt
  1405. e2, n2 = endpt
  1406. dEast = (e2 - e1)
  1407. dNorth = (n2 - n1)
  1408. if self.Map.projinfo['proj'] == 'll' and haveCtypes:
  1409. dist = gislib.G_distance(e1, n1, e2, n2)
  1410. else:
  1411. dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
  1412. return (dist, (dEast, dNorth))
  1413. def GetMap(self):
  1414. """!Get render.Map() instance"""
  1415. return self.Map
  1416. def RegisterGraphicsToDraw(self, graphicsType, setStatusFunc = None, drawFunc = None):
  1417. """! This method registers graphics to draw.
  1418. @param type (string) - graphics type: "point" or "line"
  1419. @param setStatusFunc (function reference) - function called before drawing each item
  1420. Status function should be in this form: setStatusFunc(item, itemOrderNum)
  1421. item - passes instance of GraphicsSetItem which will be drawn
  1422. itemOrderNum - number of item in drawing order (from O)
  1423. Hidden items are also counted in drawing order.
  1424. @param drawFunc (function reference) - defines own function for drawing
  1425. If function is not defined DrawCross method is used for type "point"
  1426. or DrawLines method for type "line".
  1427. @return reference to GraphicsSet, which was added.
  1428. """
  1429. item = GraphicsSet(parentMapWin = self,
  1430. graphicsType = graphicsType,
  1431. setStatusFunc = setStatusFunc,
  1432. drawFunc = drawFunc)
  1433. self.graphicsSetList.append(item)
  1434. return item
  1435. def UnregisterGraphicsToDraw(self, item):
  1436. """!Unregisteres GraphicsSet instance
  1437. @param item (GraphicsSetItem) - item to unregister
  1438. @return True - if item was unregistered
  1439. @return False - if item was not found
  1440. """
  1441. if item in self.graphicsSetList:
  1442. self.graphicsSetList.remove(item)
  1443. return True
  1444. return False
  1445. class GraphicsSet:
  1446. def __init__(self, parentMapWin, graphicsType, setStatusFunc = None, drawFunc = None):
  1447. """!Class, which contains instances of GraphicsSetItem and
  1448. draws them For description of parameters look at method
  1449. RegisterGraphicsToDraw in BufferedWindow class.
  1450. """
  1451. self.pens = {
  1452. "default" : wx.Pen(colour = wx.BLACK, width = 2, style = wx.SOLID),
  1453. "selected" : wx.Pen(colour = wx.GREEN, width = 2, style = wx.SOLID),
  1454. "unused" : wx.Pen(colour = wx.LIGHT_GREY, width = 2, style = wx.SOLID),
  1455. "highest" : wx.Pen(colour = wx.RED, width = 2, style = wx.SOLID)
  1456. }
  1457. # list contains instances of GraphicsSetItem
  1458. self.itemsList = []
  1459. self.properties = {}
  1460. self.graphicsType = graphicsType
  1461. self.parentMapWin = parentMapWin
  1462. self.setStatusFunc = setStatusFunc
  1463. if drawFunc:
  1464. self.drawFunc = drawFunc
  1465. elif self.graphicsType == "point":
  1466. self.properties["size"] = 5
  1467. self.properties["text"] = {}
  1468. self.properties["text"]['font'] = wx.Font(pointSize = self.properties["size"],
  1469. family = wx.FONTFAMILY_DEFAULT,
  1470. style = wx.FONTSTYLE_NORMAL,
  1471. weight = wx.FONTWEIGHT_NORMAL)
  1472. self.properties["text"]['active'] = True
  1473. self.drawFunc = self.parentMapWin.DrawCross
  1474. elif self.graphicsType == "line":
  1475. self.drawFunc = self.parentMapWin.DrawLines
  1476. def Draw(self, pdc):
  1477. """!Draws all containing items.
  1478. @param pdc - device context, where items are drawn
  1479. """
  1480. itemOrderNum = 0
  1481. for item in self.itemsList:
  1482. if self.setStatusFunc is not None:
  1483. self.setStatusFunc(item, itemOrderNum)
  1484. if item.GetPropertyVal("hide") == True:
  1485. itemOrderNum += 1
  1486. continue
  1487. if self.graphicsType == "point":
  1488. if item.GetPropertyVal("penName"):
  1489. self.parentMapWin.pen = self.pens[item.GetPropertyVal("penName")]
  1490. else:
  1491. self.parentMapWin.pen = self.pens["default"]
  1492. coords = self.parentMapWin.Cell2Pixel(item.GetCoords())
  1493. size = self.properties["size"]
  1494. self.properties["text"]['coords'] = [coords[0] + size, coords[1] + size, size, size]
  1495. self.properties["text"]['color'] = self.parentMapWin.pen.GetColour()
  1496. self.properties["text"]['text'] = item.GetPropertyVal("label")
  1497. self.drawFunc(pdc = pdc,
  1498. coords = coords,
  1499. text = self.properties["text"],
  1500. size = self.properties["size"])
  1501. elif self.graphicsType == "line":
  1502. if item.GetPropertyVal("penName"):
  1503. self.parentMapWin.polypen = self.pens[item.GetPropertyVal("penName")]
  1504. else:
  1505. self.parentMapWin.polypen = self.pens["default"]
  1506. coords = item.GetCoords()
  1507. self.drawFunc(pdc = pdc,
  1508. polycoords = coords)
  1509. itemOrderNum += 1
  1510. def AddItem(self, coords, penName = None, label = None, hide = False):
  1511. """!Append item to the list.
  1512. Added item is put to the last place in drawing order.
  1513. Could be 'point' or 'line' according to graphicsType.
  1514. @param coords - list of east, north coordinates (double) of item
  1515. Example: point: [1023, 122]
  1516. line: [[10, 12],[20,40],[23, 2334]]
  1517. @param penName (string) - the 'default' pen is used if is not defined
  1518. @param label (string) - label, which will be drawn with point. It is relavant just for 'point' type.
  1519. @param hide (bool) - If it is True, the item is not drawn, when self.Draw is called.
  1520. Hidden items are also counted in drawing order.
  1521. @return (GraphicsSetItem) - added item reference
  1522. """
  1523. item = GraphicsSetItem(coords = coords, penName = penName, label = label, hide = hide)
  1524. self.itemsList.append(item)
  1525. return item
  1526. def DeleteItem(self, item):
  1527. """!Deletes item
  1528. @param item (GraphicsSetItem) - item to remove
  1529. @return True if item was removed
  1530. @return False if item was not found
  1531. """
  1532. try:
  1533. self.itemsList.remove(item)
  1534. except ValueError:
  1535. return False
  1536. return True
  1537. def GetAllItems(self):
  1538. """!Returns list of all containing instances of GraphicsSetItem, in order
  1539. as they are drawn. If you want to change order of drawing use: SetItemDrawOrder method.
  1540. """
  1541. # user can edit objects but not order in list, that is reason,
  1542. # why is returned shallow copy of data list it should be used
  1543. # SetItemDrawOrder for changing order
  1544. return copy(self.itemsList)
  1545. def GetItem(self, drawNum):
  1546. """!Get given item from the list.
  1547. @param drawNum (int) - drawing order (index) number of item
  1548. @return instance of GraphicsSetItem which is drawn in drawNum order
  1549. @return False if drawNum was out of range
  1550. """
  1551. if drawNum < len(self.itemsList) and drawNum >= 0:
  1552. return self.itemsList[drawNum]
  1553. else:
  1554. return False
  1555. def SetPropertyVal(self, propName, propVal):
  1556. """!Set property value
  1557. @param propName (string) - property name: "size", "text"
  1558. - both properties are relevant for "point" type
  1559. @param propVal - property value to be set
  1560. @return True - if value was set
  1561. @return False - if propName is not "size" or "text" or type is "line"
  1562. """
  1563. if self.properties.has_key(propName):
  1564. self.properties[propName] = propVal
  1565. return True
  1566. return False
  1567. def GetPropertyVal(self, propName):
  1568. """!Get property value
  1569. Raises KeyError if propName is not "size" or "text" or type is
  1570. "line"
  1571. @param propName (string) - property name: "size", "text"
  1572. - both properties are relevant for "point" type
  1573. @return value of property
  1574. """
  1575. if self.properties.has_key(propName):
  1576. return self.properties[propName]
  1577. raise KeyError(_("Property does not exist: %s") % (propName))
  1578. def AddPen(self, penName, pen):
  1579. """!Add pen
  1580. @param penName (string) - name of added pen
  1581. @param pen (wx.Pen) - added pen
  1582. @return True - if pen was added
  1583. @return False - if pen already exists
  1584. """
  1585. if self.pens.has_key(penName):
  1586. return False
  1587. self.pens[penName] = pen
  1588. return True
  1589. def GetPen(self, penName):
  1590. """!Get existing pen
  1591. @param penName (string) - name of pen
  1592. @return wx.Pen reference if is found
  1593. @return None if penName was not found
  1594. """
  1595. if self.pens.has_key(penName):
  1596. return self.pens[penName]
  1597. return None
  1598. def SetItemDrawOrder(self, item, drawNum):
  1599. """!Set draw order for item
  1600. @param item (GraphicsSetItem)
  1601. @param drawNum (int) - drawing order of item to be set
  1602. @return True - if order was changed
  1603. @return False - if drawNum is out of range or item was not found
  1604. """
  1605. if drawNum < len(self.itemsList) and drawNum >= 0 and \
  1606. item in self.itemsList:
  1607. self.itemsList.insert(drawNum, self.itemsList.pop(self.itemsList.index(item)))
  1608. return True
  1609. return False
  1610. def GetItemDrawOrder(self, item):
  1611. """!Get draw order for given item
  1612. @param item (GraphicsSetItem)
  1613. @return (int) - drawing order of item
  1614. @return None - if item was not found
  1615. """
  1616. try:
  1617. return self.itemsList.index(item)
  1618. except ValueError:
  1619. return None
  1620. class GraphicsSetItem:
  1621. def __init__(self, coords, penName = None, label = None, hide = False):
  1622. """!Could be point or line according to graphicsType in
  1623. GraphicsSet class
  1624. @param coords - list of coordinates (double) of item
  1625. Example: point: [1023, 122]
  1626. line: [[10, 12],[20,40],[23, 2334]]
  1627. @param penName (string) - if it is not defined 'default' pen is used
  1628. @param label (string) - label, which will be drawn with point. It is relevant just for 'point' type
  1629. @param hide (bool) - if it is True, item is not drawn
  1630. Hidden items are also counted in drawing order in GraphicsSet class.
  1631. """
  1632. self.coords = coords
  1633. self.properties = { "penName" : penName,
  1634. "hide" : hide,
  1635. "label" : label }
  1636. def SetPropertyVal(self, propName, propVal):
  1637. """!Set property value
  1638. @param propName (string) - property name: "penName", "hide" or "label"
  1639. - property "label" is relevant just for 'point' type
  1640. @param propVal - property value to be set
  1641. @return True - if value was set
  1642. @return False - if propName is not "penName", "hide" or "label"
  1643. """
  1644. if self.properties.has_key(propName):
  1645. self.properties[propName] = propVal
  1646. return True
  1647. return False
  1648. def GetPropertyVal(self, propName):
  1649. """!Get property value
  1650. Raises KeyError if propName is not "penName", "hide" or
  1651. "label".
  1652. @param propName (string) - property name: "penName", "hide" or "label"
  1653. - property "label" is relevant just for 'point' type
  1654. @return value of property
  1655. """
  1656. if self.properties.has_key(propName):
  1657. return self.properties[propName]
  1658. raise KeyError(_("Property does not exist: %s") % (propName))
  1659. def SetCoords(self, coords):
  1660. """!Set coordinates of item
  1661. @param coords - list of east, north coordinates (double) of item
  1662. Example: point: [1023, 122]
  1663. line: [[10, 12],[20,40],[23, 2334]]
  1664. """
  1665. self.coords = coords
  1666. def GetCoords(self):
  1667. """!Get item coordinates
  1668. @returns coordinates
  1669. """
  1670. return self.coords