mapwindow.py 77 KB

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