mapdisp.py 84 KB

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