mapdisp.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  1. """!
  2. @package mapdisp.py
  3. @brief GIS map display canvas, with toolbar for various display
  4. management functions, and additional toolbars (vector digitizer, 3d
  5. view).
  6. Can be used either from Layer Manager or as p.mon backend.
  7. Classes:
  8. - MapFrame
  9. - MapApp
  10. Usage:
  11. python mapdisp.py monitor-identifier /path/to/command/file
  12. (C) 2006-2010 by the GRASS Development Team
  13. This program is free software under the GNU General Public
  14. License (>=v2). Read the file COPYING that comes with GRASS
  15. for details.
  16. @author Michael Barton
  17. @author Jachym Cepicky
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import glob
  23. import math
  24. import tempfile
  25. import copy
  26. import globalvar
  27. if not os.getenv("GRASS_WXBUNDLED"):
  28. globalvar.CheckForWx()
  29. import wx
  30. import wx.aui
  31. try:
  32. import subprocess
  33. except:
  34. CompatPath = os.path.join(globalvar.ETCWXDIR)
  35. sys.path.append(CompatPath)
  36. from compat import subprocess
  37. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  38. sys.path.append(gmpath)
  39. grassPath = os.path.join(globalvar.ETCDIR, "python")
  40. sys.path.append(grassPath)
  41. import render
  42. import toolbars
  43. import menuform
  44. import gselect
  45. import disp_print
  46. import gcmd
  47. import dbm
  48. import dbm_dialogs
  49. import histogram
  50. import profile
  51. import globalvar
  52. import utils
  53. import gdialogs
  54. from grass.script import core as grass
  55. from debug import Debug
  56. from icon import Icons
  57. from preferences import globalSettings as UserSettings
  58. from mapdisp_command import Command
  59. from mapdisp_window import BufferedWindow
  60. import images
  61. imagepath = images.__path__[0]
  62. sys.path.append(imagepath)
  63. ###
  64. ### global variables
  65. ###
  66. # for standalone app
  67. cmdfilename = None
  68. class MapFrame(wx.Frame):
  69. """!Main frame for map display window. Drawing takes place in
  70. child double buffered drawing window.
  71. """
  72. def __init__(self, parent = None, id = wx.ID_ANY, title = _("GRASS GIS - Map display"),
  73. style = wx.DEFAULT_FRAME_STYLE, toolbars = ["map"],
  74. tree = None, notebook = None, lmgr = None, page = None,
  75. Map = None, auimgr = None, **kwargs):
  76. """!Main map display window with toolbars, statusbar and
  77. DrawWindow
  78. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  79. @param tree reference to layer tree
  80. @param notebook control book ID in Layer Manager
  81. @param lmgr Layer Manager
  82. @param page notebook page with layer tree
  83. @param Map instance of render.Map
  84. @param auimgs AUI manager
  85. @param kwargs wx.Frame attribures
  86. """
  87. self._layerManager = lmgr # Layer Manager object
  88. self.Map = Map # instance of render.Map
  89. self.tree = tree # Layer Manager layer tree object
  90. self.page = page # Notebook page holding the layer tree
  91. self.layerbook = notebook # Layer Manager layer tree notebook
  92. self.parent = parent
  93. if not kwargs.has_key('name'):
  94. kwargs['name'] = 'MapWindow'
  95. wx.Frame.__init__(self, parent, id, title, style = style, **kwargs)
  96. # available cursors
  97. self.cursors = {
  98. # default: cross
  99. # "default" : wx.StockCursor(wx.CURSOR_DEFAULT),
  100. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  101. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  102. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  103. "pencil" : wx.StockCursor(wx.CURSOR_PENCIL),
  104. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  105. }
  106. #
  107. # set the size & system icon
  108. #
  109. self.SetClientSize(self.GetSize())
  110. self.iconsize = (16, 16)
  111. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  112. #
  113. # Fancy gui
  114. #
  115. # self._mgr = auimgr
  116. self._mgr = wx.aui.AuiManager(self)
  117. #
  118. # Add toolbars
  119. #
  120. self.toolbars = { 'map' : None,
  121. 'vdigit' : None,
  122. 'georect' : None,
  123. 'gcpdisp' : None,
  124. 'nviz' : None }
  125. for toolb in toolbars:
  126. self.AddToolbar(toolb)
  127. #
  128. # Add statusbar
  129. #
  130. self.statusbar = self.CreateStatusBar(number = 4, style = 0)
  131. self.statusbar.SetStatusWidths([-5, -2, -1, -1])
  132. self.statusbarWin = dict()
  133. self.statusbarWin['toggle'] = wx.Choice(self.statusbar, wx.ID_ANY,
  134. choices = globalvar.MAP_DISPLAY_STATUSBAR_MODE)
  135. self.statusbarWin['toggle'].SetSelection(UserSettings.Get(group = 'display',
  136. key = 'statusbarMode',
  137. subkey = 'selection'))
  138. self.statusbar.Bind(wx.EVT_CHOICE, self.OnToggleStatus, self.statusbarWin['toggle'])
  139. # auto-rendering checkbox
  140. self.statusbarWin['render'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  141. label = _("Render"))
  142. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleRender, self.statusbarWin['render'])
  143. self.statusbarWin['render'].SetValue(UserSettings.Get(group = 'display',
  144. key = 'autoRendering',
  145. subkey = 'enabled'))
  146. self.statusbarWin['render'].SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
  147. # show region
  148. self.statusbarWin['region'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  149. label = _("Show computational extent"))
  150. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion, self.statusbarWin['region'])
  151. self.statusbarWin['region'].SetValue(False)
  152. self.statusbarWin['region'].Hide()
  153. self.statusbarWin['region'].SetToolTip(wx.ToolTip (_("Show/hide computational "
  154. "region extent (set with g.region). "
  155. "Display region drawn as a blue box inside the "
  156. "computational region, "
  157. "computational region inside a display region "
  158. "as a red box).")))
  159. # set resolution
  160. self.statusbarWin['resolution'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  161. label = _("Constrain display resolution to computational settings"))
  162. self.statusbar.Bind(wx.EVT_CHECKBOX, self.OnToggleResolution, self.statusbarWin['resolution'])
  163. self.statusbarWin['resolution'].SetValue(UserSettings.Get(group = 'display', key = 'compResolution', subkey = 'enabled'))
  164. self.statusbarWin['resolution'].Hide()
  165. self.statusbarWin['resolution'].SetToolTip(wx.ToolTip (_("Constrain display resolution "
  166. "to computational region settings. "
  167. "Default value for new map displays can "
  168. "be set up in 'User GUI settings' dialog.")))
  169. # map scale
  170. self.statusbarWin['mapscale'] = wx.ComboBox(parent = self.statusbar, id = wx.ID_ANY,
  171. style = wx.TE_PROCESS_ENTER,
  172. size = (150, -1))
  173. self.statusbarWin['mapscale'].SetItems(['1:1000',
  174. '1:5000',
  175. '1:10000',
  176. '1:25000',
  177. '1:50000',
  178. '1:100000',
  179. '1:1000000'])
  180. self.statusbarWin['mapscale'].Hide()
  181. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  182. self.statusbar.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale, self.statusbarWin['mapscale'])
  183. # go to
  184. self.statusbarWin['goto'] = wx.TextCtrl(parent = self.statusbar, id = wx.ID_ANY,
  185. value = "", style = wx.TE_PROCESS_ENTER,
  186. size = (300, -1))
  187. self.statusbarWin['goto'].Hide()
  188. self.statusbar.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo, self.statusbarWin['goto'])
  189. # projection
  190. self.statusbarWin['projection'] = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
  191. label = _("Use defined projection"))
  192. self.statusbarWin['projection'].SetValue(False)
  193. size = self.statusbarWin['projection'].GetSize()
  194. self.statusbarWin['projection'].SetMinSize((size[0] + 150, size[1]))
  195. self.statusbarWin['projection'].SetToolTip(wx.ToolTip (_("Reproject coordinates displayed "
  196. "in the statusbar. Projection can be "
  197. "defined in GUI preferences dialog "
  198. "(tab 'Display')")))
  199. self.statusbarWin['projection'].Hide()
  200. # mask
  201. self.statusbarWin['mask'] = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY,
  202. label = '')
  203. self.statusbarWin['mask'].SetForegroundColour(wx.Colour(255, 0, 0))
  204. # on-render gauge
  205. self.statusbarWin['progress'] = wx.Gauge(parent = self.statusbar, id = wx.ID_ANY,
  206. range = 0, style = wx.GA_HORIZONTAL)
  207. self.statusbarWin['progress'].Hide()
  208. self.StatusbarReposition() # reposition statusbar
  209. #
  210. # Init map display (buffered DC & set default cursor)
  211. #
  212. self.MapWindow2D = BufferedWindow(self, id = wx.ID_ANY,
  213. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  214. # default is 2D display mode
  215. self.MapWindow = self.MapWindow2D
  216. self.MapWindow.SetCursor(self.cursors["default"])
  217. # used by Nviz (3D display mode)
  218. self.MapWindow3D = None
  219. #
  220. # initialize region values
  221. #
  222. self.__InitDisplay()
  223. #
  224. # Bind various events
  225. #
  226. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  227. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  228. self.Bind(render.EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  229. #
  230. # Update fancy gui style
  231. #
  232. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  233. Dockable(False).BestSize((-1,-1)).
  234. CloseButton(False).DestroyOnClose(True).
  235. Layer(0))
  236. self._mgr.Update()
  237. #
  238. # Init print module and classes
  239. #
  240. self.printopt = disp_print.PrintOptions(self, self.MapWindow)
  241. #
  242. # Initialization of digitization tool
  243. #
  244. self.digit = None
  245. #
  246. # Init zoom history
  247. #
  248. self.MapWindow.ZoomHistory(self.Map.region['n'],
  249. self.Map.region['s'],
  250. self.Map.region['e'],
  251. self.Map.region['w'])
  252. #
  253. # Re-use dialogs
  254. #
  255. self.dialogs = {}
  256. self.dialogs['attributes'] = None
  257. self.dialogs['category'] = None
  258. self.dialogs['barscale'] = None
  259. self.dialogs['legend'] = None
  260. self.decorationDialog = None # decoration/overlays
  261. def AddToolbar(self, name):
  262. """!Add defined toolbar to the window
  263. Currently known toolbars are:
  264. - 'map' - basic map toolbar
  265. - 'vdigit' - vector digitizer
  266. - 'gcpdisp' - GCP Manager Display
  267. - 'georect' - georectifier
  268. - 'nviz' - 3D view mode
  269. """
  270. # default toolbar
  271. if name == "map":
  272. self.toolbars['map'] = toolbars.MapToolbar(self, self.Map)
  273. self._mgr.AddPane(self.toolbars['map'],
  274. wx.aui.AuiPaneInfo().
  275. Name("maptoolbar").Caption(_("Map toolbar")).
  276. ToolbarPane().Top().
  277. LeftDockable(False).RightDockable(False).
  278. BottomDockable(False).TopDockable(True).
  279. CloseButton(False).Layer(2).
  280. BestSize((self.toolbars['map'].GetSize())))
  281. # vector digitizer
  282. elif name == "vdigit":
  283. from vdigit import haveVDigit
  284. if not haveVDigit:
  285. from vdigit import errorMsg
  286. msg = _("Unable to start wxGUI vector digitizer.\nDo you want to start "
  287. "TCL/TK digitizer (v.digit) instead?\n\n"
  288. "Details: %s" % errorMsg)
  289. self.mapdisplay.toolbars['map'].combo.SetValue (_("2D view"))
  290. dlg = wx.MessageDialog(parent = self.mapdisplay,
  291. message = msg,
  292. caption=_("Vector digitizer failed"),
  293. style = wx.YES_NO | wx.CENTRE)
  294. if dlg.ShowModal() == wx.ID_YES:
  295. self.lmgr.goutput.RunCmd(['v.digit', 'map=%s' % maplayer.GetName()],
  296. switchPage=False)
  297. dlg.Destroy()
  298. self.toolbars['map'].combo.SetValue (_("2D view"))
  299. return
  300. if self._layerManager:
  301. log = self._layerManager.goutput
  302. else:
  303. log = None
  304. self.toolbars['vdigit'] = toolbars.VDigitToolbar(parent = self, mapcontent = self.Map,
  305. layerTree = self.tree,
  306. log = log)
  307. self._mgr.AddPane(self.toolbars['vdigit'],
  308. wx.aui.AuiPaneInfo().
  309. Name("vdigittoolbar").Caption(_("Vector digitizer toolbar")).
  310. ToolbarPane().Top().Row(1).
  311. LeftDockable(False).RightDockable(False).
  312. BottomDockable(False).TopDockable(True).
  313. CloseButton(False).Layer(2).
  314. BestSize((self.toolbars['vdigit'].GetSize())))
  315. # change mouse to draw digitized line
  316. self.MapWindow.mouse['box'] = "point"
  317. self.MapWindow.zoomtype = 0
  318. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  319. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  320. # georectifier
  321. elif name == "georect":
  322. self.toolbars['georect'] = toolbars.GRToolbar(self, self.Map)
  323. self._mgr.AddPane(self.toolbars['georect'],
  324. wx.aui.AuiPaneInfo().
  325. Name("georecttoolbar").Caption(_("Georectification toolbar")).
  326. ToolbarPane().Top().
  327. LeftDockable(False).RightDockable(False).
  328. BottomDockable(False).TopDockable(True).
  329. CloseButton(False).Layer(2))
  330. # nviz
  331. elif name == "nviz":
  332. import nviz
  333. # check for GLCanvas and OpenGL
  334. if not nviz.haveNviz:
  335. self.toolbars['map'].combo.SetValue (_("2D view"))
  336. wx.MessageBox(parent = self,
  337. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  338. "was not found or loaded properly.\n"
  339. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg),
  340. caption = _("Error"),
  341. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  342. return
  343. # add Nviz toolbar and disable 2D display mode tools
  344. self.toolbars['nviz'] = toolbars.NvizToolbar(self, self.Map)
  345. self.toolbars['map'].Enable2D(False)
  346. # update status bar
  347. self.statusbarWin['toggle'].Enable(False)
  348. # erase map window
  349. self.MapWindow.EraseMap()
  350. self._layerManager.goutput.WriteCmdLog(_("Starting 3D view mode..."))
  351. self.statusbar.SetStatusText(_("Please wait, loading data..."), 0)
  352. # create GL window & NVIZ toolbar
  353. if not self.MapWindow3D:
  354. self.MapWindow3D = nviz.GLWindow(self, id = wx.ID_ANY,
  355. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  356. self.MapWindow = self.MapWindow3D
  357. self.MapWindow.SetCursor(self.cursors["default"])
  358. # add Nviz notebookpage
  359. self._layerManager.AddNviz()
  360. self.MapWindow3D.DoPaint() # -> LoadData
  361. self.MapWindow3D.Show()
  362. self.MapWindow3D.UpdateView(None)
  363. else:
  364. self.MapWindow = self.MapWindow3D
  365. # add Nviz notebookpage
  366. self._layerManager.AddNviz()
  367. # switch from MapWindow to MapWindowGL
  368. # add nviz toolbar
  369. self._mgr.DetachPane(self.MapWindow2D)
  370. self.MapWindow2D.Hide()
  371. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  372. Dockable(False).BestSize((-1,-1)).
  373. CloseButton(False).DestroyOnClose(True).
  374. Layer(0))
  375. self._mgr.AddPane(self.toolbars['nviz'],
  376. wx.aui.AuiPaneInfo().
  377. Name("nviztoolbar").Caption(_("3D view toolbar")).
  378. ToolbarPane().Top().Row(1).
  379. LeftDockable(False).RightDockable(False).
  380. BottomDockable(False).TopDockable(True).
  381. CloseButton(False).Layer(2))
  382. self.SetStatusText("", 0)
  383. self._mgr.Update()
  384. def RemoveToolbar (self, name):
  385. """!Removes toolbar from the window
  386. @todo Only hide, activate by calling AddToolbar()
  387. """
  388. # cannot hide main toolbar
  389. if name == "map":
  390. return
  391. elif name == "vdigit":
  392. # TODO: not destroy only hide
  393. self._mgr.DetachPane(self.toolbars['vdigit'])
  394. self.toolbars['vdigit'].Destroy()
  395. else:
  396. self._mgr.DetachPane (self.toolbars[name])
  397. self.toolbars[name].Destroy()
  398. self.toolbars[name] = None
  399. if name == 'nviz':
  400. # unload data
  401. # self.MapWindow3D.Reset()
  402. # switch from MapWindowGL to MapWindow
  403. self._mgr.DetachPane(self.MapWindow3D)
  404. self.MapWindow3D.Hide()
  405. self.MapWindow2D.Show()
  406. self._mgr.AddPane(self.MapWindow2D, wx.aui.AuiPaneInfo().CentrePane().
  407. Dockable(False).BestSize((-1,-1)).
  408. CloseButton(False).DestroyOnClose(True).
  409. Layer(0))
  410. self.MapWindow = self.MapWindow2D
  411. # remove nviz notebook page
  412. self._layerManager.RemoveNviz()
  413. self.MapWindow.UpdateMap()
  414. self.toolbars['map'].combo.SetValue (_("2D view"))
  415. self.toolbars['map'].Enable2D(True)
  416. self.statusbarWin['toggle'].Enable(True)
  417. self._mgr.Update()
  418. def __InitDisplay(self):
  419. """
  420. Initialize map display, set dimensions and map region
  421. """
  422. self.width, self.height = self.GetClientSize()
  423. Debug.msg(2, "MapFrame.__InitDisplay():")
  424. self.Map.ChangeMapSize(self.GetClientSize())
  425. self.Map.region = self.Map.GetRegion() # g.region -upgc
  426. # self.Map.SetRegion() # adjust region to match display window
  427. def OnUpdateProgress(self, event):
  428. """
  429. Update progress bar info
  430. """
  431. self.statusbarWin['progress'].SetValue(event.value)
  432. event.Skip()
  433. def OnFocus(self, event):
  434. """
  435. Change choicebook page to match display.
  436. Or set display for georectifying
  437. """
  438. if self._layerManager and \
  439. self._layerManager.georectifying:
  440. # in georectifying session; display used to get geographic
  441. # coordinates for GCPs
  442. self.OnPointer(event)
  443. else:
  444. # change bookcontrol page to page associated with display
  445. if self.page:
  446. pgnum = self.layerbook.GetPageIndex(self.page)
  447. if pgnum > -1:
  448. self.layerbook.SetSelection(pgnum)
  449. event.Skip()
  450. def OnDraw(self, event):
  451. """!Re-display current map composition
  452. """
  453. self.MapWindow.UpdateMap(render = False)
  454. def OnRender(self, event):
  455. """!Re-render map composition (each map layer)
  456. """
  457. # delete tmp map layers (queries)
  458. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  459. for layer in qlayer:
  460. self.Map.DeleteLayer(layer)
  461. # delete tmp lines
  462. if self.MapWindow.mouse["use"] in ("measure",
  463. "profile"):
  464. self.MapWindow.polycoords = []
  465. self.MapWindow.ClearLines()
  466. # deselect features in vdigit
  467. if self.toolbars['vdigit'] and self.digit:
  468. self.digit.GetDisplay().SetSelected([])
  469. self.MapWindow.UpdateMap(render = True, renderVector = True)
  470. else:
  471. self.MapWindow.UpdateMap(render = True)
  472. # update statusbar
  473. self.StatusbarUpdate()
  474. def OnPointer(self, event):
  475. """!Pointer button clicked
  476. """
  477. if self.toolbars['map']:
  478. if event:
  479. self.toolbars['map'].OnTool(event)
  480. self.toolbars['map'].action['desc'] = ''
  481. self.MapWindow.mouse['use'] = "pointer"
  482. self.MapWindow.mouse['box'] = "point"
  483. # change the cursor
  484. if self.toolbars['vdigit']:
  485. # digitization tool activated
  486. self.MapWindow.SetCursor(self.cursors["cross"])
  487. # reset mouse['box'] if needed
  488. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  489. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  490. self.MapWindow.mouse['box'] = 'point'
  491. else: # line, boundary
  492. self.MapWindow.mouse['box'] = 'line'
  493. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  494. 'editLine', 'displayCats', 'displayAttrs',
  495. 'copyCats']:
  496. self.MapWindow.mouse['box'] = 'point'
  497. else: # moveLine, deleteLine
  498. self.MapWindow.mouse['box'] = 'box'
  499. elif self._layerManager and self._layerManager.georectifying:
  500. self.MapWindow.SetCursor(self.cursors["cross"])
  501. else:
  502. self.MapWindow.SetCursor(self.cursors["default"])
  503. def OnZoomIn(self, event):
  504. """
  505. Zoom in the map.
  506. Set mouse cursor, zoombox attributes, and zoom direction
  507. """
  508. if self.toolbars['map']:
  509. self.toolbars['map'].OnTool(event)
  510. self.toolbars['map'].action['desc'] = ''
  511. self.MapWindow.mouse['use'] = "zoom"
  512. self.MapWindow.mouse['box'] = "box"
  513. self.MapWindow.zoomtype = 1
  514. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  515. # change the cursor
  516. self.MapWindow.SetCursor(self.cursors["cross"])
  517. def OnZoomOut(self, event):
  518. """
  519. Zoom out the map.
  520. Set mouse cursor, zoombox attributes, and zoom direction
  521. """
  522. if self.toolbars['map']:
  523. self.toolbars['map'].OnTool(event)
  524. self.toolbars['map'].action['desc'] = ''
  525. self.MapWindow.mouse['use'] = "zoom"
  526. self.MapWindow.mouse['box'] = "box"
  527. self.MapWindow.zoomtype = -1
  528. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  529. # change the cursor
  530. self.MapWindow.SetCursor(self.cursors["cross"])
  531. def OnZoomBack(self, event):
  532. """
  533. Zoom last (previously stored position)
  534. """
  535. self.MapWindow.ZoomBack()
  536. def OnPan(self, event):
  537. """
  538. Panning, set mouse to drag
  539. """
  540. if self.toolbars['map']:
  541. self.toolbars['map'].OnTool(event)
  542. self.toolbars['map'].action['desc'] = ''
  543. self.MapWindow.mouse['use'] = "pan"
  544. self.MapWindow.mouse['box'] = "pan"
  545. self.MapWindow.zoomtype = 0
  546. # change the cursor
  547. self.MapWindow.SetCursor(self.cursors["hand"])
  548. def OnErase(self, event):
  549. """
  550. Erase the canvas
  551. """
  552. self.MapWindow.EraseMap()
  553. def OnZoomRegion(self, event):
  554. """
  555. Zoom to region
  556. """
  557. self.Map.getRegion()
  558. self.Map.getResolution()
  559. self.UpdateMap()
  560. # event.Skip()
  561. def OnAlignRegion(self, event):
  562. """
  563. Align region
  564. """
  565. if not self.Map.alignRegion:
  566. self.Map.alignRegion = True
  567. else:
  568. self.Map.alignRegion = False
  569. # event.Skip()
  570. def OnToggleRender(self, event):
  571. """!Enable/disable auto-rendering
  572. """
  573. if self.statusbarWin['render'].GetValue():
  574. self.OnRender(None)
  575. def IsAutoRendered(self):
  576. """!Check if auto-rendering is enabled"""
  577. return self.statusbarWin['render'].IsChecked()
  578. def OnToggleShowRegion(self, event):
  579. """!Show/Hide extent in map canvas
  580. """
  581. if self.statusbarWin['region'].GetValue():
  582. # show extent
  583. self.MapWindow.regionCoords = []
  584. else:
  585. del self.MapWindow.regionCoords
  586. # redraw map if auto-rendering is enabled
  587. if self.statusbarWin['render'].GetValue():
  588. self.OnRender(None)
  589. def OnToggleResolution(self, event):
  590. """
  591. Use resolution of computation region settings
  592. for redering image instead of display resolution
  593. """
  594. # redraw map if auto-rendering is enabled
  595. if self.statusbarWin['render'].GetValue():
  596. self.OnRender(None)
  597. def OnToggleStatus(self, event):
  598. """
  599. Toggle status text
  600. """
  601. self.StatusbarUpdate()
  602. def OnChangeMapScale(self, event):
  603. """
  604. Map scale changed by user
  605. """
  606. scale = event.GetString()
  607. try:
  608. if scale[:2] != '1:':
  609. raise ValueError
  610. value = int(scale[2:])
  611. except ValueError:
  612. self.statusbarWin['mapscale'].SetValue('1:%ld' % int(self.mapScaleValue))
  613. return
  614. dEW = value * (self.Map.region['cols'] / self.ppm[0])
  615. dNS = value * (self.Map.region['rows'] / self.ppm[1])
  616. self.Map.region['n'] = self.Map.region['center_northing'] + dNS / 2.
  617. self.Map.region['s'] = self.Map.region['center_northing'] - dNS / 2.
  618. self.Map.region['w'] = self.Map.region['center_easting'] - dEW / 2.
  619. self.Map.region['e'] = self.Map.region['center_easting'] + dEW / 2.
  620. # add to zoom history
  621. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  622. self.Map.region['e'], self.Map.region['w'])
  623. # redraw a map
  624. self.MapWindow.UpdateMap()
  625. self.statusbarWin['mapscale'].SetFocus()
  626. def OnGoTo(self, event):
  627. """
  628. Go to position
  629. """
  630. try:
  631. if self.statusbarWin['projection'].IsChecked():
  632. if not UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4'):
  633. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  634. else:
  635. # reproject values
  636. projIn = UserSettings.Get(group = 'projection',
  637. key = 'statusbar',
  638. subkey = 'proj4')
  639. projOut = gcmd.RunCommand('g.proj',
  640. flags = 'jf',
  641. read = True)
  642. proj = projIn.split(' ')[0].split('=')[1]
  643. if proj in ('ll', 'latlong', 'longlat'):
  644. e, n = self.statusbarWin['goto'].GetValue().split(';')
  645. e, n = utils.DMS2Deg(e, n)
  646. proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
  647. projIn = projIn,
  648. projOut = projOut, flags = 'd')
  649. e, n = coord1
  650. else:
  651. e, n = map(float, self.statusbarWin['goto'].GetValue().split(';'))
  652. proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
  653. projIn = projIn,
  654. projOut = projOut, flags = 'd')
  655. e, n = coord1
  656. else:
  657. if self.Map.projinfo['proj'] == 'll':
  658. e, n = self.statusbarWin['goto'].GetValue().split(';')
  659. else:
  660. e, n = map(float, self.statusbarWin['goto'].GetValue().split(';'))
  661. region = self.Map.GetCurrentRegion()
  662. if self.statusbarWin['projection'].IsChecked():
  663. if not UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4'):
  664. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  665. else:
  666. region['center_easting'], region['center_northing'] = e, n
  667. else:
  668. if self.Map.projinfo['proj'] == 'll':
  669. region['center_easting'], region['center_northing'] = utils.DMS2Deg(e, n)
  670. else:
  671. region['center_easting'], region['center_northing'] = e, n
  672. except ValueError:
  673. region = self.Map.GetCurrentRegion()
  674. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  675. subkey = 'precision'))
  676. format = UserSettings.Get(group = 'projection', key = 'format',
  677. subkey = 'll')
  678. if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
  679. self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(region['center_easting'],
  680. region['center_northing'],
  681. precision = precision))
  682. else:
  683. self.statusbarWin['goto'].SetValue("%.*f; %.*f" % \
  684. (precision, region['center_easting'],
  685. precision, region['center_northing']))
  686. return
  687. dn = (region['nsres'] * region['rows']) / 2.
  688. region['n'] = region['center_northing'] + dn
  689. region['s'] = region['center_northing'] - dn
  690. de = (region['ewres'] * region['cols']) / 2.
  691. region['e'] = region['center_easting'] + de
  692. region['w'] = region['center_easting'] - de
  693. self.Map.AdjustRegion()
  694. # add to zoom history
  695. self.MapWindow.ZoomHistory(region['n'], region['s'],
  696. region['e'], region['w'])
  697. # redraw a map
  698. self.MapWindow.UpdateMap()
  699. self.statusbarWin['goto'].SetFocus()
  700. def StatusbarUpdate(self):
  701. """!Update statusbar content"""
  702. self.statusbarWin['region'].Hide()
  703. self.statusbarWin['resolution'].Hide()
  704. self.statusbarWin['mapscale'].Hide()
  705. self.statusbarWin['goto'].Hide()
  706. self.statusbarWin['projection'].Hide()
  707. self.mapScaleValue = self.ppm = None
  708. if self.statusbarWin['toggle'].GetSelection() == 0: # Coordinates
  709. self.statusbar.SetStatusText("", 0)
  710. # enable long help
  711. self.StatusbarEnableLongHelp()
  712. elif self.statusbarWin['toggle'].GetSelection() in (1, 2): # Extent
  713. sel = self.statusbarWin['toggle'].GetSelection()
  714. if sel == 1:
  715. region = self.Map.region
  716. else:
  717. region = self.Map.GetRegion() # computation region
  718. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  719. subkey = 'precision'))
  720. format = UserSettings.Get(group = 'projection', key = 'format',
  721. subkey = 'll')
  722. if self.statusbarWin['projection'].IsChecked():
  723. if not UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4'):
  724. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  725. else:
  726. projOut = UserSettings.Get(group = 'projection',
  727. key = 'statusbar',
  728. subkey = 'proj4')
  729. proj, coord1 = utils.ReprojectCoordinates(coord = (region["w"], region["s"]),
  730. projOut = projOut, flags = 'd')
  731. proj, coord2 = utils.ReprojectCoordinates(coord = (region["e"], region["n"]),
  732. projOut = projOut, flags = 'd')
  733. if sel == 2:
  734. proj, coord3 = utils.ReprojectCoordinates(coord = (0.0, 0.0),
  735. projOut = projOut, flags = 'd')
  736. proj, coord4 = utils.ReprojectCoordinates(coord = (region["ewres"], region["nsres"]),
  737. projOut = projOut, flags = 'd')
  738. if coord1 and coord2:
  739. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  740. w, s = utils.Deg2DMS(coord1[0], coord1[1], string = False,
  741. precision = precision)
  742. e, n = utils.Deg2DMS(coord2[0], coord2[1], string = False,
  743. precision = precision)
  744. if sel == 1:
  745. self.statusbar.SetStatusText("%s - %s, %s - %s" %
  746. (w, e, s, n), 0)
  747. else:
  748. ewres, nsres = utils.Deg2DMS(abs(coord3[0]) - abs(coord4[0]),
  749. abs(coord3[1]) - abs(coord4[1]),
  750. string = False, hemisphere = False,
  751. precision = precision)
  752. self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
  753. (w, e, s, n, ewres, nsres), 0)
  754. else:
  755. w, s = coord1
  756. e, n = coord2
  757. if sel == 1:
  758. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f" %
  759. (precision, w, precision, e,
  760. precision, s, precision, n), 0)
  761. else:
  762. ewres, nsres = coord3
  763. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" %
  764. (precision, w, precision, e,
  765. precision, s, precision, n,
  766. precision, ewres, precision, nsres), 0)
  767. else:
  768. self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
  769. else:
  770. if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
  771. w, s = utils.Deg2DMS(region["w"], region["s"],
  772. string = False, precision = precision)
  773. e, n = utils.Deg2DMS(region["e"], region["n"],
  774. string = False, precision = precision)
  775. if sel == 1:
  776. self.statusbar.SetStatusText("%s - %s, %s - %s" %
  777. (w, e, s, n), 0)
  778. else:
  779. ewres, nsres = utils.Deg2DMS(region['ewres'], region['nsres'],
  780. string = False, precision = precision)
  781. self.statusbar.SetStatusText("%s - %s, %s - %s (%s, %s)" %
  782. (w, e, s, n, ewres, nsres), 0)
  783. else:
  784. w, s = region["w"], region["s"]
  785. e, n = region["e"], region["n"]
  786. if sel == 1:
  787. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f" %
  788. (precision, w, precision, e,
  789. precision, s, precision, n), 0)
  790. else:
  791. ewres, nsres = region['ewres'], region['nsres']
  792. self.statusbar.SetStatusText("%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" %
  793. (precision, w, precision, e,
  794. precision, s, precision, n,
  795. precision, ewres, precision, nsres), 0)
  796. # enable long help
  797. self.StatusbarEnableLongHelp()
  798. elif self.statusbarWin['toggle'].GetSelection() == 3: # Show comp. extent
  799. self.statusbar.SetStatusText("", 0)
  800. self.statusbarWin['region'].Show()
  801. # disable long help
  802. self.StatusbarEnableLongHelp(False)
  803. elif self.statusbarWin['toggle'].GetSelection() == 4: # Display mode
  804. self.statusbar.SetStatusText("", 0)
  805. self.statusbarWin['resolution'].Show()
  806. # disable long help
  807. self.StatusbarEnableLongHelp(False)
  808. elif self.statusbarWin['toggle'].GetSelection() == 5: # Display geometry
  809. self.statusbar.SetStatusText("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
  810. (self.Map.region["rows"], self.Map.region["cols"],
  811. self.Map.region["nsres"], self.Map.region["ewres"]), 0)
  812. # enable long help
  813. self.StatusbarEnableLongHelp()
  814. elif self.statusbarWin['toggle'].GetSelection() == 6: # Map scale
  815. # TODO: need to be fixed...
  816. ### screen X region problem
  817. ### user should specify ppm
  818. dc = wx.ScreenDC()
  819. dpSizePx = wx.DisplaySize() # display size in pixels
  820. dpSizeMM = wx.DisplaySizeMM() # display size in mm (system)
  821. dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4) # inches
  822. sysPpi = dc.GetPPI()
  823. comPpi = (dpSizePx[0] / dpSizeIn[0],
  824. dpSizePx[1] / dpSizeIn[1])
  825. ppi = comPpi # pixel per inch
  826. self.ppm = ((ppi[0] / 2.54) * 100, # pixel per meter
  827. (ppi[1] / 2.54) * 100)
  828. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): size: px=%d,%d mm=%f,%f "
  829. "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" % \
  830. (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
  831. dpSizeIn[0], dpSizeIn[1],
  832. sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
  833. self.ppm[0], self.ppm[1]))
  834. region = self.Map.region
  835. heightCm = region['rows'] / self.ppm[1] * 100
  836. widthCm = region['cols'] / self.ppm[0] * 100
  837. Debug.msg(4, "MapFrame.StatusbarUpdate(mapscale): width_cm=%f, height_cm=%f" %
  838. (widthCm, heightCm))
  839. xscale = (region['e'] - region['w']) / (region['cols'] / self.ppm[0])
  840. yscale = (region['n'] - region['s']) / (region['rows'] / self.ppm[1])
  841. scale = (xscale + yscale) / 2.
  842. Debug.msg(3, "MapFrame.StatusbarUpdate(mapscale): xscale=%f, yscale=%f -> scale=%f" % \
  843. (xscale, yscale, scale))
  844. self.statusbar.SetStatusText("")
  845. try:
  846. self.statusbarWin['mapscale'].SetValue("1:%ld" % (scale + 0.5))
  847. except TypeError:
  848. pass
  849. self.mapScaleValue = scale
  850. self.statusbarWin['mapscale'].Show()
  851. # disable long help
  852. self.StatusbarEnableLongHelp(False)
  853. elif self.statusbarWin['toggle'].GetSelection() == 7: # go to
  854. self.statusbar.SetStatusText("")
  855. region = self.Map.GetCurrentRegion()
  856. precision = int(UserSettings.Get(group = 'projection', key = 'format',
  857. subkey = 'precision'))
  858. format = UserSettings.Get(group = 'projection', key = 'format',
  859. subkey = 'll')
  860. if self.statusbarWin['projection'].IsChecked():
  861. if not UserSettings.Get(group='projection', key='statusbar', subkey='proj4'):
  862. self.statusbar.SetStatusText(_("Projection not defined (check the settings)"), 0)
  863. else:
  864. proj, coord = utils.ReprojectCoordinates(coord = (region['center_easting'],
  865. region['center_northing']),
  866. projOut = UserSettings.Get(group = 'projection',
  867. key = 'statusbar',
  868. subkey = 'proj4'),
  869. flags = 'd')
  870. if coord:
  871. if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
  872. self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(coord[0],
  873. coord[1],
  874. precision = precision))
  875. else:
  876. self.statusbarWin['goto'].SetValue("%.*f; %.*f" % (precision, coord[0],
  877. precision, coord[1]))
  878. else:
  879. self.statusbar.SetStatusText(_("Error in projection (check the settings)"), 0)
  880. else:
  881. if self.Map.projinfo['proj'] == 'll' and format == 'DMS':
  882. self.statusbarWin['goto'].SetValue("%s" % utils.Deg2DMS(region['center_easting'],
  883. region['center_northing'],
  884. precision = precision))
  885. else:
  886. self.statusbarWin['goto'].SetValue("%.*f; %.*f" % (precision, region['center_easting'],
  887. precision, region['center_northing']))
  888. self.statusbarWin['goto'].Show()
  889. # disable long help
  890. self.StatusbarEnableLongHelp(False)
  891. elif self.statusbarWin['toggle'].GetSelection() == 8: # projection
  892. self.statusbar.SetStatusText("")
  893. epsg = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'epsg')
  894. if epsg:
  895. label = '%s (EPSG: %s)' % (_("Use defined projection"), epsg)
  896. self.statusbarWin['projection'].SetLabel(label)
  897. else:
  898. self.statusbarWin['projection'].SetLabel(_("Use defined projection"))
  899. self.statusbarWin['projection'].Show()
  900. # disable long help
  901. self.StatusbarEnableLongHelp(False)
  902. else:
  903. self.statusbar.SetStatusText("", 1)
  904. def StatusbarEnableLongHelp(self, enable = True):
  905. """!Enable/disable toolbars long help"""
  906. for toolbar in self.toolbars.itervalues():
  907. if toolbar:
  908. toolbar.EnableLongHelp(enable)
  909. def StatusbarReposition(self):
  910. """!Reposition checkbox in statusbar"""
  911. # reposition checkbox
  912. widgets = [(0, self.statusbarWin['region']),
  913. (0, self.statusbarWin['resolution']),
  914. (0, self.statusbarWin['mapscale']),
  915. (0, self.statusbarWin['progress']),
  916. (0, self.statusbarWin['projection']),
  917. (1, self.statusbarWin['toggle']),
  918. (2, self.statusbarWin['mask']),
  919. (3, self.statusbarWin['render'])]
  920. for idx, win in widgets:
  921. rect = self.statusbar.GetFieldRect(idx)
  922. if idx == 0: # show region / mapscale / process bar
  923. # -> size
  924. wWin, hWin = win.GetBestSize()
  925. if win == self.statusbarWin['progress']:
  926. wWin = rect.width - 6
  927. # -> position
  928. # if win == self.statusbarWin['region']:
  929. # x, y = rect.x + rect.width - wWin, rect.y - 1
  930. # align left
  931. # else:
  932. x, y = rect.x + 3, rect.y - 1
  933. w, h = wWin, rect.height + 2
  934. else: # choice || auto-rendering
  935. x, y = rect.x, rect.y - 1
  936. w, h = rect.width, rect.height + 2
  937. if idx == 2: # mask
  938. x += 5
  939. y += 4
  940. elif idx == 3: # render
  941. x += 5
  942. win.SetPosition((x, y))
  943. win.SetSize((w, h))
  944. def SaveToFile(self, event):
  945. """!Save map to image
  946. """
  947. if self.toolbars['nviz']:
  948. filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
  949. ltype = [{ 'ext' : 'ppm', 'type' : -1 },
  950. { 'ext' : 'tif', 'type' : wx.BITMAP_TYPE_TIF }]
  951. else:
  952. img = self.MapWindow.img
  953. if not img:
  954. gcmd.GMessage(parent = self,
  955. message = _("Nothing to render (empty map). Operation canceled."))
  956. return
  957. filetype, ltype = gdialogs.GetImageHandlers(img)
  958. # get size
  959. dlg = gdialogs.ImageSizeDialog(self)
  960. dlg.CentreOnParent()
  961. if dlg.ShowModal() != wx.ID_OK:
  962. dlg.Destroy()
  963. return
  964. width, height = dlg.GetValues()
  965. dlg.Destroy()
  966. # get filename
  967. dlg = wx.FileDialog(parent = self,
  968. message = _("Choose a file name to save the image "
  969. "(no need to add extension)"),
  970. wildcard = filetype,
  971. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  972. if dlg.ShowModal() == wx.ID_OK:
  973. path = dlg.GetPath()
  974. if not path:
  975. dlg.Destroy()
  976. return
  977. base, ext = os.path.splitext(path)
  978. fileType = ltype[dlg.GetFilterIndex()]['type']
  979. extType = ltype[dlg.GetFilterIndex()]['ext']
  980. if ext != extType:
  981. path = base + '.' + extType
  982. self.MapWindow.SaveToFile(path, fileType,
  983. width, height)
  984. dlg.Destroy()
  985. def PrintMenu(self, event):
  986. """
  987. Print options and output menu for map display
  988. """
  989. point = wx.GetMousePosition()
  990. printmenu = wx.Menu()
  991. # Add items to the menu
  992. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  993. printmenu.AppendItem(setup)
  994. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  995. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  996. printmenu.AppendItem(preview)
  997. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  998. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  999. printmenu.AppendItem(doprint)
  1000. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  1001. # Popup the menu. If an item is selected then its handler
  1002. # will be called before PopupMenu returns.
  1003. self.PopupMenu(printmenu)
  1004. printmenu.Destroy()
  1005. def OnCloseWindow(self, event):
  1006. """!Window closed.
  1007. Also close associated layer tree page
  1008. """
  1009. pgnum = None
  1010. self.Map.Clean()
  1011. # close edited map and 3D tools properly
  1012. if self.toolbars['vdigit']:
  1013. maplayer = self.toolbars['vdigit'].GetLayer()
  1014. if maplayer:
  1015. self.toolbars['vdigit'].OnExit()
  1016. if self.toolbars['nviz']:
  1017. self.toolbars['nviz'].OnExit()
  1018. if not self._layerManager:
  1019. self.Destroy()
  1020. elif self.page:
  1021. pgnum = self.layerbook.GetPageIndex(self.page)
  1022. if pgnum > -1:
  1023. self.layerbook.DeletePage(pgnum)
  1024. def GetRender(self):
  1025. """!Returns current instance of render.Map()
  1026. """
  1027. return self.Map
  1028. def GetWindow(self):
  1029. """!Get map window"""
  1030. return self.MapWindow
  1031. def _OnQuery(self):
  1032. """!Internal method used by OnQuery*() methods"""
  1033. if self.toolbars['map'].GetAction() == 'displayAttrb':
  1034. # switch to output console to show query results
  1035. self._layerManager.notebook.SetSelection(1)
  1036. self.MapWindow.mouse['box'] = "point"
  1037. self.MapWindow.zoomtype = 0
  1038. # change the cursor
  1039. self.MapWindow.SetCursor(self.cursors["cross"])
  1040. def OnQueryDisplay(self, event):
  1041. """!Query currrent raster/vector map layers (display mode) -
  1042. 2D view mode
  1043. """
  1044. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  1045. self.toolbars['map'].SelectDefault(event)
  1046. return
  1047. self.toolbars['map'].action['desc'] = 'displayAttrb'
  1048. self.MapWindow.mouse['use'] = "query"
  1049. self._OnQuery()
  1050. def OnQueryModify(self, event):
  1051. """!Query vector map layer (edit mode) - 2D view mode
  1052. """
  1053. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  1054. self.toolbars['map'].SelectDefault(event)
  1055. return
  1056. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  1057. self.MapWindow.mouse['use'] = "queryVector"
  1058. self.MapWindow.pen = wx.Pen(colour = 'Red', width = 2, style = wx.SHORT_DASH)
  1059. self._OnQuery()
  1060. def OnNvizQuerySurface(self, event):
  1061. """!Query current surface in 3D view mode"""
  1062. if self.toolbars['map'].GetAction() == 'nvizQuerySurface':
  1063. self.toolbars['map'].SelectDefault(event)
  1064. return
  1065. self.toolbars['map'].action['desc'] = 'nvizQuerySurface'
  1066. self.MapWindow.mouse['use'] = "nvizQuerySurface"
  1067. self._OnQuery()
  1068. def OnNvizQueryVector(self, event):
  1069. """!Query current vector in 3D view mode"""
  1070. if self.toolbars['map'].GetAction() == 'nvizQueryVector':
  1071. self.toolbars['map'].SelectDefault(event)
  1072. return
  1073. self.toolbars['map'].action['desc'] = 'nvizQueryVector'
  1074. self.MapWindow.mouse['use'] = "nvizQueryVector"
  1075. self._OnQuery()
  1076. def QueryMap(self, x, y):
  1077. """!Query map layer features
  1078. Currently only raster and vector map layers are supported.
  1079. @param x,y coordinates
  1080. """
  1081. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  1082. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  1083. east, north = self.MapWindow.Pixel2Cell((x, y))
  1084. num = 0
  1085. for layer in self.tree.GetSelections():
  1086. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1087. if type in ('raster', 'rgb', 'his',
  1088. 'vector', 'thememap', 'themechart'):
  1089. num += 1
  1090. if num < 1:
  1091. dlg = wx.MessageDialog(parent = self,
  1092. message = _('No raster or vector map layer selected for querying.'),
  1093. caption = _('No map layer selected'),
  1094. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1095. dlg.ShowModal()
  1096. dlg.Destroy()
  1097. return
  1098. mapname = None
  1099. raststr = ''
  1100. vectstr = ''
  1101. rcmd = ['r.what', '--v']
  1102. vcmd = ['v.what', '--v']
  1103. for layer in self.tree.GetSelections():
  1104. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1105. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  1106. name = utils.GetLayerNameFromCmd(dcmd)
  1107. if name == '':
  1108. continue
  1109. if type in ('raster', 'rgb', 'his'):
  1110. raststr += "%s," % name
  1111. elif type in ('vector', 'thememap', 'themechart'):
  1112. vectstr += "%s," % name
  1113. # use display region settings instead of computation region settings
  1114. self.tmpreg = os.getenv("GRASS_REGION")
  1115. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  1116. # build query commands for any selected rasters and vectors
  1117. if raststr != '':
  1118. rcmd.append('-f')
  1119. rcmd.append('input=%s' % raststr.rstrip(','))
  1120. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1121. if vectstr != '':
  1122. # check for vector maps open to be edited
  1123. digitToolbar = self.toolbars['vdigit']
  1124. if digitToolbar:
  1125. map = digitToolbar.GetLayer().GetName()
  1126. vect = []
  1127. for vector in vectstr.split(','):
  1128. if map == vector:
  1129. self._layerManager.goutput.WriteWarning("Vector map <%s> "
  1130. "opened for editing - skipped." % map)
  1131. continue
  1132. vect.append(vector)
  1133. vectstr = ','.join(vect)
  1134. if len(vectstr) <= 1:
  1135. self._layerManager.goutput.WriteCmdLog("Nothing to query.")
  1136. return
  1137. vcmd.append('-a')
  1138. vcmd.append('map=%s' % vectstr.rstrip(','))
  1139. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  1140. vcmd.append('distance=%f' % float(qdist))
  1141. # parse query command(s)
  1142. if self._layerManager:
  1143. if raststr:
  1144. self._layerManager.goutput.RunCmd(rcmd,
  1145. compReg = False,
  1146. onDone = self._QueryMapDone)
  1147. if vectstr:
  1148. self._layerManager.goutput.RunCmd(vcmd,
  1149. onDone = self._QueryMapDone)
  1150. else:
  1151. if raststr:
  1152. gcmd.RunCommand(rcmd)
  1153. if vectstr:
  1154. gcmd.RunCommand(vcmd)
  1155. def _QueryMapDone(self, cmd, returncode):
  1156. """!Restore settings after querying (restore GRASS_REGION)
  1157. @param returncode command return code
  1158. """
  1159. if hasattr(self, "tmpreg"):
  1160. if self.tmpreg:
  1161. os.environ["GRASS_REGION"] = self.tmpreg
  1162. elif os.environ.has_key('GRASS_REGION'):
  1163. del os.environ["GRASS_REGION"]
  1164. elif os.environ.has_key('GRASS_REGION'):
  1165. del os.environ["GRASS_REGION"]
  1166. if hasattr(self, "tmpreg"):
  1167. del self.tmpreg
  1168. def QueryVector(self, x, y):
  1169. """!Query vector map layer features
  1170. Attribute data of selected vector object are displayed in GUI dialog.
  1171. Data can be modified (On Submit)
  1172. """
  1173. if not self.tree.layer_selected or \
  1174. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  1175. wx.MessageBox(parent = self,
  1176. message = _("No vector map selected for querying."),
  1177. caption = _("Vector querying"),
  1178. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1179. return
  1180. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  1181. grass.gisenv()['MAPSET']:
  1182. wx.MessageBox(parent = self,
  1183. message = _("Only vector map from the current mapset can be modified."),
  1184. caption = _("Vector querying"),
  1185. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1186. return
  1187. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  1188. y + self.MapWindow.dialogOffset))
  1189. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  1190. self.Map.width)
  1191. east, north = self.MapWindow.Pixel2Cell((x, y))
  1192. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  1193. if self.dialogs['attributes'] is None:
  1194. self.dialogs['attributes'] = \
  1195. dbm_dialogs.DisplayAttributesDialog(parent = self.MapWindow,
  1196. map = mapName,
  1197. query = ((east, north), qdist),
  1198. pos = posWindow,
  1199. action = "update")
  1200. else:
  1201. # selection changed?
  1202. if not self.dialogs['attributes'].mapDBInfo or \
  1203. self.dialogs['attributes'].mapDBInfo.map != mapName:
  1204. self.dialogs['attributes'].UpdateDialog(map = mapName, query = ((east, north), qdist))
  1205. else:
  1206. self.dialogs['attributes'].UpdateDialog(query = ((east, north), qdist))
  1207. cats = self.dialogs['attributes'].GetCats()
  1208. try:
  1209. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)[0]
  1210. except IndexError:
  1211. qlayer = None
  1212. if self.dialogs['attributes'].mapDBInfo and cats:
  1213. # highlight feature & re-draw map
  1214. if qlayer:
  1215. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  1216. useId = False,
  1217. addLayer = False))
  1218. else:
  1219. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId = False)
  1220. # set opacity based on queried layer
  1221. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float = True)
  1222. qlayer.SetOpacity(opacity)
  1223. self.MapWindow.UpdateMap(render = False, renderVector = False)
  1224. if not self.dialogs['attributes'].IsShown():
  1225. self.dialogs['attributes'].Show()
  1226. else:
  1227. if qlayer:
  1228. self.Map.DeleteLayer(qlayer)
  1229. self.MapWindow.UpdateMap(render = False, renderVector = False)
  1230. if self.dialogs['attributes'].IsShown():
  1231. self.dialogs['attributes'].Hide()
  1232. def OnQuery(self, event):
  1233. """!Query tools menu"""
  1234. if self.toolbars['map']:
  1235. self.toolbars['map'].OnTool(event)
  1236. action = self.toolbars['map'].GetAction()
  1237. point = wx.GetMousePosition()
  1238. toolsmenu = wx.Menu()
  1239. # add items to the menu
  1240. if self.toolbars['nviz']:
  1241. raster = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1242. text = _("Query surface (raster map)"),
  1243. kind = wx.ITEM_CHECK)
  1244. toolsmenu.AppendItem(raster)
  1245. self.Bind(wx.EVT_MENU, self.OnNvizQuerySurface, raster)
  1246. if action == "nvizQuerySurface":
  1247. raster.Check(True)
  1248. vector = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1249. text = _("Query vector map"),
  1250. kind = wx.ITEM_CHECK)
  1251. toolsmenu.AppendItem(vector)
  1252. self.Bind(wx.EVT_MENU, self.OnNvizQueryVector, vector)
  1253. if action == "nvizQueryVector":
  1254. vector.Check(True)
  1255. else:
  1256. display = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1257. text = _("Query raster/vector map(s) (display mode)"),
  1258. kind = wx.ITEM_CHECK)
  1259. toolsmenu.AppendItem(display)
  1260. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  1261. numLayers = 0
  1262. for layer in self.tree.GetSelections():
  1263. type = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  1264. if type in ('raster', 'rgb', 'his',
  1265. 'vector', 'thememap', 'themechart'):
  1266. numLayers += 1
  1267. if numLayers < 1:
  1268. display.Enable(False)
  1269. if action == "displayAttrb":
  1270. display.Check(True)
  1271. modify = wx.MenuItem(parentMenu = toolsmenu, id = wx.ID_ANY,
  1272. text = _("Query vector map (edit mode)"),
  1273. kind = wx.ITEM_CHECK)
  1274. toolsmenu.AppendItem(modify)
  1275. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  1276. modify.Enable(False)
  1277. if action == "modifyAttrb":
  1278. modify.Check(True)
  1279. digitToolbar = self.toolbars['vdigit']
  1280. if self.tree.layer_selected:
  1281. mapLayer = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  1282. if mapLayer.GetType() == 'vector' and \
  1283. mapLayer.GetMapset() == grass.gisenv()['MAPSET'] and \
  1284. (not digitToolbar or (digitToolbar and \
  1285. digitToolbar.GetLayer() != mapLayer)):
  1286. modify.Enable(True)
  1287. else:
  1288. if action == "modifyAttrb":
  1289. modify.Check(True)
  1290. self.PopupMenu(toolsmenu)
  1291. toolsmenu.Destroy()
  1292. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  1293. """!Add temporal vector map layer to map composition
  1294. @param name name of map layer
  1295. @param useId use feature id instead of category
  1296. """
  1297. # color settings from ATM
  1298. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  1299. colorStr = str(color[0]) + ":" + \
  1300. str(color[1]) + ":" + \
  1301. str(color[2])
  1302. # icon used in vector display and its size
  1303. icon = ''
  1304. size = 0
  1305. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  1306. for p in vparam:
  1307. if '=' in p:
  1308. parg,pval = p.split('=')
  1309. if parg == 'icon': icon = pval
  1310. elif parg == 'size': size = int(pval)
  1311. pattern = ["d.vect",
  1312. "map=%s" % name,
  1313. "color=%s" % colorStr,
  1314. "fcolor=%s" % colorStr,
  1315. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  1316. if icon != '':
  1317. pattern.append('icon=%s' % icon)
  1318. if size > 0:
  1319. pattern.append('size=%i' % size)
  1320. if useId:
  1321. cmd = pattern
  1322. cmd.append('-i')
  1323. cmd.append('cats=%s' % str(cats))
  1324. else:
  1325. cmd = []
  1326. for layer in cats.keys():
  1327. cmd.append(copy.copy(pattern))
  1328. lcats = cats[layer]
  1329. cmd[-1].append("layer=%d" % layer)
  1330. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  1331. if addLayer:
  1332. if useId:
  1333. return self.Map.AddLayer(type = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  1334. l_active = True, l_hidden = True, l_opacity = 1.0)
  1335. else:
  1336. return self.Map.AddLayer(type = 'command', name = globalvar.QUERYLAYER, command = cmd,
  1337. l_active = True, l_hidden = True, l_opacity = 1.0)
  1338. else:
  1339. return cmd
  1340. def OnAnalyze(self, event):
  1341. """!Analysis tools menu
  1342. """
  1343. point = wx.GetMousePosition()
  1344. toolsmenu = wx.Menu()
  1345. # Add items to the menu
  1346. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  1347. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  1348. toolsmenu.AppendItem(measure)
  1349. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1350. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  1351. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  1352. toolsmenu.AppendItem(profile)
  1353. self.Bind(wx.EVT_MENU, self.Profile, profile)
  1354. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  1355. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  1356. toolsmenu.AppendItem(histogram)
  1357. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  1358. # Popup the menu. If an item is selected then its handler
  1359. # will be called before PopupMenu returns.
  1360. self.PopupMenu(toolsmenu)
  1361. toolsmenu.Destroy()
  1362. def OnMeasure(self, event):
  1363. """!Init measurement routine that calculates map distance
  1364. along transect drawn on map display
  1365. """
  1366. self.totaldist = 0.0 # total measured distance
  1367. # switch GIS Manager to output console to show measure results
  1368. self._layerManager.notebook.SetSelection(1)
  1369. # change mouse to draw line for measurement
  1370. self.MapWindow.mouse['use'] = "measure"
  1371. self.MapWindow.mouse['box'] = "line"
  1372. self.MapWindow.zoomtype = 0
  1373. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SHORT_DASH)
  1374. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SHORT_DASH)
  1375. # change the cursor
  1376. self.MapWindow.SetCursor(self.cursors["pencil"])
  1377. # initiating output
  1378. style = self._layerManager.goutput.cmd_output.StyleWarning
  1379. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  1380. 'to measure.%s'
  1381. 'Double click with left button to clear.') % \
  1382. (os.linesep), style)
  1383. if self.Map.projinfo['proj'] != 'xy':
  1384. units = self.Map.projinfo['units']
  1385. style = self._layerManager.goutput.cmd_output.StyleCommand
  1386. self._layerManager.goutput.WriteLog(_('Measuring distance') + ' ('
  1387. + units + '):',
  1388. style)
  1389. else:
  1390. self._layerManager.goutput.WriteLog(_('Measuring distance:'),
  1391. style)
  1392. def MeasureDist(self, beginpt, endpt):
  1393. """!Calculate map distance from screen distance
  1394. and print to output window
  1395. """
  1396. if self._layerManager.notebook.GetSelection() != 1:
  1397. self._layerManager.notebook.SetSelection(1)
  1398. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1399. dist = round(dist, 3)
  1400. d, dunits = self.FormatDist(dist)
  1401. self.totaldist += dist
  1402. td, tdunits = self.FormatDist(self.totaldist)
  1403. strdist = str(d)
  1404. strtotdist = str(td)
  1405. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1406. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1407. angle = 180 - angle
  1408. if angle < 0:
  1409. angle = 360+angle
  1410. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  1411. % (strdist,dunits,strtotdist,tdunits,angle)
  1412. else:
  1413. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  1414. % (strdist,dunits,strtotdist,tdunits)
  1415. self._layerManager.goutput.WriteLog(mstring)
  1416. return dist
  1417. def Profile(self, event):
  1418. """!Init profile canvas and tools
  1419. """
  1420. raster = []
  1421. if self.tree.layer_selected and \
  1422. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1423. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1424. self.profile = profile.ProfileFrame(self,
  1425. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (700,300),
  1426. style = wx.DEFAULT_FRAME_STYLE, rasterList = raster)
  1427. self.profile.Show()
  1428. # Open raster select dialog to make sure that a raster (and the desired raster)
  1429. # is selected to be profiled
  1430. self.profile.OnSelectRaster(None)
  1431. def FormatDist(self, dist):
  1432. """!Format length numbers and units in a nice way,
  1433. as a function of length. From code by Hamish Bowman
  1434. Grass Development Team 2006"""
  1435. mapunits = self.Map.projinfo['units']
  1436. if mapunits == 'metres': mapunits = 'meters'
  1437. outunits = mapunits
  1438. dist = float(dist)
  1439. divisor = 1.0
  1440. # figure out which units to use
  1441. if mapunits == 'meters':
  1442. if dist > 2500.0:
  1443. outunits = 'km'
  1444. divisor = 1000.0
  1445. else: outunits = 'm'
  1446. elif mapunits == 'feet':
  1447. # nano-bug: we match any "feet", but US Survey feet is really
  1448. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1449. # miles the tick markers are rounded to the nearest 10th of a
  1450. # mile (528'), the difference in foot flavours is ignored.
  1451. if dist > 5280.0:
  1452. outunits = 'miles'
  1453. divisor = 5280.0
  1454. else:
  1455. outunits = 'ft'
  1456. elif 'degree' in mapunits:
  1457. if dist < 1:
  1458. outunits = 'min'
  1459. divisor = (1/60.0)
  1460. else:
  1461. outunits = 'deg'
  1462. # format numbers in a nice way
  1463. if (dist/divisor) >= 2500.0:
  1464. outdist = round(dist/divisor)
  1465. elif (dist/divisor) >= 1000.0:
  1466. outdist = round(dist/divisor,1)
  1467. elif (dist/divisor) > 0.0:
  1468. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1469. else:
  1470. outdist = float(dist/divisor)
  1471. return (outdist, outunits)
  1472. def Histogram(self, event):
  1473. """!Init histogram display canvas and tools
  1474. """
  1475. self.histogram = histogram.HistFrame(self,
  1476. id = wx.ID_ANY, size = globalvar.HIST_WINDOW_SIZE,
  1477. style = wx.DEFAULT_FRAME_STYLE)
  1478. #show new display
  1479. self.histogram.Show()
  1480. self.histogram.Refresh()
  1481. self.histogram.Update()
  1482. def OnDecoration(self, event):
  1483. """!Decorations overlay menu
  1484. """
  1485. point = wx.GetMousePosition()
  1486. decmenu = wx.Menu()
  1487. # Add items to the menu
  1488. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  1489. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  1490. decmenu.AppendItem(AddScale)
  1491. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1492. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  1493. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  1494. decmenu.AppendItem(AddLegend)
  1495. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1496. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  1497. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  1498. decmenu.AppendItem(AddText)
  1499. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1500. # Popup the menu. If an item is selected then its handler
  1501. # will be called before PopupMenu returns.
  1502. self.PopupMenu(decmenu)
  1503. decmenu.Destroy()
  1504. def OnAddBarscale(self, event):
  1505. """!Handler for scale/arrow map decoration menu selection.
  1506. """
  1507. if self.dialogs['barscale']:
  1508. return
  1509. id = 0 # unique index for overlay layer
  1510. # If location is latlon, only display north arrow (scale won't work)
  1511. # proj = self.Map.projinfo['proj']
  1512. # if proj == 'll':
  1513. # barcmd = 'd.barscale -n'
  1514. # else:
  1515. # barcmd = 'd.barscale'
  1516. # decoration overlay control dialog
  1517. self.dialogs['barscale'] = \
  1518. gdialogs.DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1519. size = (350, 200),
  1520. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1521. cmd = ['d.barscale', 'at = 0,5'],
  1522. ovlId = id,
  1523. name = 'barscale',
  1524. checktxt = _("Show/hide scale and North arrow"),
  1525. ctrltxt = _("scale object"))
  1526. self.dialogs['barscale'].CentreOnParent()
  1527. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1528. ### self.dialogs['barscale'].ShowModal()
  1529. self.dialogs['barscale'].Show()
  1530. self.MapWindow.mouse['use'] = 'pointer'
  1531. def OnAddLegend(self, event):
  1532. """!Handler for legend map decoration menu selection.
  1533. """
  1534. if self.dialogs['legend']:
  1535. return
  1536. id = 1 # index for overlay layer in render
  1537. cmd = ['d.legend', 'at=5,50,2,5']
  1538. if self.tree.layer_selected and \
  1539. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1540. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1541. # Decoration overlay control dialog
  1542. self.dialogs['legend'] = \
  1543. gdialogs.DecorationDialog(parent = self, title = ('Legend'),
  1544. size = (350, 200),
  1545. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1546. cmd = cmd,
  1547. ovlId = id,
  1548. name = 'legend',
  1549. checktxt = _("Show/hide legend"),
  1550. ctrltxt = _("legend object"))
  1551. self.dialogs['legend'].CentreOnParent()
  1552. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1553. ### self.dialogs['legend'].ShowModal()
  1554. self.dialogs['legend'].Show()
  1555. self.MapWindow.mouse['use'] = 'pointer'
  1556. def OnAddText(self, event):
  1557. """!Handler for text decoration menu selection.
  1558. """
  1559. if self.MapWindow.dragid > -1:
  1560. id = self.MapWindow.dragid
  1561. else:
  1562. # index for overlay layer in render
  1563. if len(self.MapWindow.textdict.keys()) > 0:
  1564. id = self.MapWindow.textdict.keys()[-1] + 1
  1565. else:
  1566. id = 101
  1567. self.dialogs['text'] = gdialogs.TextLayerDialog(parent = self, ovlId = id,
  1568. title = _('Add text layer'),
  1569. size = (400, 200))
  1570. self.dialogs['text'].CenterOnParent()
  1571. # If OK button pressed in decoration control dialog
  1572. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1573. text = self.dialogs['text'].GetValues()['text']
  1574. active = self.dialogs['text'].GetValues()['active']
  1575. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1576. # delete object if it has no text or is not active
  1577. if text == '' or active == False:
  1578. try:
  1579. self.MapWindow.pdc.ClearId(id)
  1580. self.MapWindow.pdc.RemoveId(id)
  1581. del self.MapWindow.textdict[id]
  1582. except:
  1583. pass
  1584. return
  1585. self.MapWindow.pdc.ClearId(id)
  1586. self.MapWindow.pdc.SetId(id)
  1587. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1588. self.MapWindow.Draw(self.MapWindow.pdcDec, img = self.MapWindow.textdict[id],
  1589. drawid = id, pdctype = 'text', coords = coords)
  1590. self.MapWindow.UpdateMap(render = False, renderVector = False)
  1591. self.MapWindow.mouse['use'] = 'pointer'
  1592. def GetOptData(self, dcmd, type, params, propwin):
  1593. """!Callback method for decoration overlay command generated by
  1594. dialog created in menuform.py
  1595. """
  1596. # Reset comand and rendering options in render.Map. Always render decoration.
  1597. # Showing/hiding handled by PseudoDC
  1598. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1599. l_active = True, l_render = False)
  1600. self.params[type] = params
  1601. self.propwin[type] = propwin
  1602. def OnZoomToMap(self, event):
  1603. """!Set display extents to match selected raster (including
  1604. NULLs) or vector map.
  1605. """
  1606. self.MapWindow.ZoomToMap()
  1607. def OnZoomToRaster(self, event):
  1608. """!Set display extents to match selected raster map (ignore NULLs)
  1609. """
  1610. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1611. def OnZoomToWind(self, event):
  1612. """!Set display geometry to match computational region
  1613. settings (set with g.region)
  1614. """
  1615. self.MapWindow.ZoomToWind()
  1616. def OnZoomToDefault(self, event):
  1617. """!Set display geometry to match default region settings
  1618. """
  1619. self.MapWindow.ZoomToDefault()
  1620. def OnZoomToSaved(self, event):
  1621. """!Set display geometry to match extents in
  1622. saved region file
  1623. """
  1624. self.MapWindow.ZoomToSaved()
  1625. def OnDisplayToWind(self, event):
  1626. """!Set computational region (WIND file) to match display
  1627. extents
  1628. """
  1629. self.MapWindow.DisplayToWind()
  1630. def SaveDisplayRegion(self, event):
  1631. """!Save display extents to named region file.
  1632. """
  1633. self.MapWindow.SaveDisplayRegion()
  1634. def OnZoomMenu(self, event):
  1635. """!Popup Zoom menu
  1636. """
  1637. point = wx.GetMousePosition()
  1638. zoommenu = wx.Menu()
  1639. # Add items to the menu
  1640. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1641. zoommenu.AppendItem(zoomwind)
  1642. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1643. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1644. zoommenu.AppendItem(zoomdefault)
  1645. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1646. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1647. zoommenu.AppendItem(zoomsaved)
  1648. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1649. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1650. zoommenu.AppendItem(savewind)
  1651. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1652. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1653. zoommenu.AppendItem(savezoom)
  1654. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1655. # Popup the menu. If an item is selected then its handler
  1656. # will be called before PopupMenu returns.
  1657. self.PopupMenu(zoommenu)
  1658. zoommenu.Destroy()
  1659. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1660. constrainRes = False, projection = False):
  1661. """!Set properies of map display window"""
  1662. self.statusbarWin['render'].SetValue(render)
  1663. self.statusbarWin['toggle'].SetSelection(mode)
  1664. self.StatusbarUpdate()
  1665. self.statusbarWin['region'].SetValue(showCompExtent)
  1666. self.statusbarWin['resolution'].SetValue(constrainRes)
  1667. self.statusbarWin['projection'].SetValue(projection)
  1668. if showCompExtent:
  1669. self.MapWindow.regionCoords = []
  1670. def IsStandalone(self):
  1671. """!Check if Map display is standalone"""
  1672. if self._layerManager:
  1673. return False
  1674. return True
  1675. def GetLayerManager(self):
  1676. """!Get reference to Layer Manager
  1677. @return window reference
  1678. @return None (if standalone)
  1679. """
  1680. return self._layerManager
  1681. # end of class MapFrame
  1682. class MapApp(wx.App):
  1683. def OnInit(self):
  1684. wx.InitAllImageHandlers()
  1685. if __name__ == "__main__":
  1686. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  1687. else:
  1688. Map = None
  1689. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1690. size = globalvar.MAP_WINDOW_SIZE)
  1691. #self.SetTopWindow(Map)
  1692. self.mapFrm.Show()
  1693. if __name__ == "__main__":
  1694. # redraw map, if new command appears
  1695. self.redraw = False
  1696. status = Command(self, Map, cmdfilename)
  1697. status.start()
  1698. self.timer = wx.PyTimer(self.watcher)
  1699. # check each 0.1s
  1700. self.timer.Start(100)
  1701. return 1
  1702. def OnExit(self):
  1703. if __name__ == "__main__":
  1704. # stop the timer
  1705. self.timer.Stop()
  1706. # terminate thread (a bit ugly)
  1707. os.system("""!echo "quit" >> %s""" % (cmdfilename))
  1708. def watcher(self):
  1709. """!Redraw, if new layer appears"""
  1710. if self.redraw:
  1711. self.mapFrm.OnDraw(None)
  1712. self.redraw = False
  1713. return
  1714. # end of class MapApp
  1715. if __name__ == "__main__":
  1716. ###### SET command variable
  1717. if len(sys.argv) != 3:
  1718. print __doc__
  1719. sys.exit()
  1720. title = sys.argv[1]
  1721. cmdfilename = sys.argv[2]
  1722. import gettext
  1723. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1724. print >> sys.stderr, "\nStarting monitor <%s>...\n" % (title)
  1725. gm_map = MapApp(0)
  1726. # set title
  1727. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1728. title +
  1729. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1730. gm_map.MainLoop()
  1731. os.remove(cmdfilename)
  1732. os.system("""!g.gisenv set="GRASS_PYCMDFILE" """)
  1733. print >> sys.stderr, "\nStopping monitor <%s>...\n" % (title)
  1734. sys.exit(0)