mapwindow.py 76 KB

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