mapdisp.py 84 KB

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