mapwindow.py 74 KB

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