mapwindow.py 76 KB

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