mapdisp.py 84 KB

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