frame.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. """!
  2. @package mapdisp.frame
  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. @author Vaclav Petras <wenzeslaus gmail.com> (MapFrameBase)
  19. @author Anna Kratochvilova <kratochanna gmail.com> (MapFrameBase)
  20. """
  21. import os
  22. import sys
  23. import math
  24. import copy
  25. from core 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. from core import globalvar
  31. from core.render import EVT_UPDATE_PRGBAR, Map
  32. from vdigit.toolbars import VDigitToolbar
  33. from mapdisp.toolbars import MapToolbar
  34. from mapdisp.gprint import PrintOptions
  35. from core.gcmd import GError, GMessage, RunCommand
  36. from dbm.dialogs import DisplayAttributesDialog
  37. from core.utils import ListOfCatsToRange, GetLayerNameFromCmd
  38. from gui_core.dialogs import GetImageHandlers, ImageSizeDialog, DecorationDialog, TextLayerDialog
  39. from core.debug import Debug
  40. from icon import Icons
  41. from core.settings import UserSettings
  42. from gui_core.mapdisp import MapFrameBase
  43. from mapdisp.mapwindow import BufferedWindow
  44. from modules.histogram import HistogramFrame
  45. from wxplot.histogram import Histogram2Frame
  46. from wxplot.profile import ProfileFrame
  47. from wxplot.scatter import ScatterFrame
  48. from nviz.main import haveNviz
  49. from nviz.mapwindow import GLWindow
  50. from mapdisp import statusbar as sb
  51. from grass.script import core as grass
  52. # for standalone app
  53. monFile = { 'cmd' : None,
  54. 'map' : None,
  55. 'env' : None,
  56. }
  57. monName = None
  58. monSize = list(globalvar.MAP_WINDOW_SIZE)
  59. haveCtypes = False
  60. class MapFrame(MapFrameBase):
  61. """!Main frame for map display window. Drawing takes place in
  62. child double buffered drawing window.
  63. """
  64. def __init__(self, parent = None, title = _("GRASS GIS - Map display"),
  65. toolbars = ["map"], tree = None, notebook = None, lmgr = None,
  66. page = None, Map = None, auimgr = None, name = 'MapWindow', **kwargs):
  67. """!Main map display window with toolbars, statusbar and
  68. BufferedWindow (map canvas)
  69. @param toolbars array of activated toolbars, e.g. ['map', 'digit']
  70. @param tree reference to layer tree
  71. @param notebook control book ID in Layer Manager
  72. @param lmgr Layer Manager
  73. @param page notebook page with layer tree
  74. @param Map instance of render.Map
  75. @param auimgs AUI manager
  76. @param name frame name
  77. @param kwargs wx.Frame attributes
  78. """
  79. MapFrameBase.__init__(self, parent = parent, title = title, toolbars = toolbars,
  80. Map = Map, auimgr = auimgr, name = name, **kwargs)
  81. self._layerManager = lmgr # Layer Manager object
  82. self.tree = tree # Layer Manager layer tree object
  83. self.page = page # Notebook page holding the layer tree
  84. self.layerbook = notebook # Layer Manager layer tree notebook
  85. #
  86. # Add toolbars
  87. #
  88. for toolb in toolbars:
  89. self.AddToolbar(toolb)
  90. #
  91. # Add statusbar
  92. #
  93. # items for choice
  94. self.statusbarItems = [sb.SbCoordinates,
  95. sb.SbRegionExtent,
  96. sb.SbCompRegionExtent,
  97. sb.SbShowRegion,
  98. sb.SbAlignExtent,
  99. sb.SbResolution,
  100. sb.SbDisplayGeometry,
  101. sb.SbMapScale,
  102. sb.SbGoTo,
  103. sb.SbProjection]
  104. self.statusbarItemsHiddenInNviz = (sb.SbAlignExtent,
  105. sb.SbDisplayGeometry,
  106. sb.SbShowRegion,
  107. sb.SbResolution,
  108. sb.SbMapScale)
  109. # create statusbar and its manager
  110. statusbar = self.CreateStatusBar(number = 4, style = 0)
  111. statusbar.SetStatusWidths([-5, -2, -1, -1])
  112. self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
  113. # fill statusbar manager
  114. self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
  115. self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
  116. self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
  117. self.statusbarManager.Update()
  118. #
  119. # Init map display (buffered DC & set default cursor)
  120. #
  121. self.MapWindow2D = BufferedWindow(self, id = wx.ID_ANY,
  122. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  123. # default is 2D display mode
  124. self.MapWindow = self.MapWindow2D
  125. self.MapWindow.SetCursor(self.cursors["default"])
  126. # used by vector digitizer
  127. self.MapWindowVDigit = None
  128. # used by Nviz (3D display mode)
  129. self.MapWindow3D = None
  130. #
  131. # initialize region values
  132. #
  133. self._initMap(map = self.Map)
  134. #
  135. # Bind various events
  136. #
  137. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  138. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  139. self.Bind(EVT_UPDATE_PRGBAR, self.OnUpdateProgress)
  140. #
  141. # Update fancy gui style
  142. #
  143. self._mgr.AddPane(self.MapWindow, wx.aui.AuiPaneInfo().CentrePane().
  144. Dockable(False).BestSize((-1,-1)).Name('2d').
  145. CloseButton(False).DestroyOnClose(True).
  146. Layer(0))
  147. self._mgr.Update()
  148. #
  149. # Init print module and classes
  150. #
  151. self.printopt = PrintOptions(self, self.MapWindow)
  152. #
  153. # Init zoom history
  154. #
  155. self.MapWindow.ZoomHistory(self.Map.region['n'],
  156. self.Map.region['s'],
  157. self.Map.region['e'],
  158. self.Map.region['w'])
  159. #
  160. # Re-use dialogs
  161. #
  162. self.dialogs = {}
  163. self.dialogs['attributes'] = None
  164. self.dialogs['category'] = None
  165. self.dialogs['barscale'] = None
  166. self.dialogs['legend'] = None
  167. self.decorationDialog = None # decoration/overlays
  168. def _addToolbarVDigit(self):
  169. """!Add vector digitizer toolbar
  170. """
  171. from vdigit.main import haveVDigit
  172. if not haveVDigit:
  173. from vdigit import errorMsg
  174. msg = _("Unable to start wxGUI vector digitizer.\nDo you want to start "
  175. "TCL/TK digitizer (v.digit) instead?\n\n"
  176. "Details: %s" % errorMsg)
  177. self.toolbars['map'].combo.SetValue(_("2D view"))
  178. dlg = wx.MessageDialog(parent = self,
  179. message = msg,
  180. caption=_("Vector digitizer failed"),
  181. style = wx.YES_NO | wx.CENTRE)
  182. if dlg.ShowModal() == wx.ID_YES:
  183. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetName()
  184. self._layerManager.goutput.RunCmd(['v.digit', 'map=%s' % mapName],
  185. switchPage = False)
  186. dlg.Destroy()
  187. self.toolbars['map'].combo.SetValue(_("2D view"))
  188. return
  189. if self._layerManager:
  190. log = self._layerManager.goutput
  191. else:
  192. log = None
  193. if not self.MapWindowVDigit:
  194. from vdigit.mapwindow import VDigitWindow
  195. self.MapWindowVDigit = VDigitWindow(self, id = wx.ID_ANY,
  196. Map = self.Map, tree = self.tree,
  197. lmgr = self._layerManager)
  198. self.MapWindowVDigit.Show()
  199. self._mgr.AddPane(self.MapWindowVDigit, wx.aui.AuiPaneInfo().CentrePane().
  200. Dockable(False).BestSize((-1,-1)).Name('vdigit').
  201. CloseButton(False).DestroyOnClose(True).
  202. Layer(0))
  203. self.MapWindow = self.MapWindowVDigit
  204. if self._mgr.GetPane('2d').IsShown():
  205. self._mgr.GetPane('2d').Hide()
  206. elif self._mgr.GetPane('3d').IsShown():
  207. self._mgr.GetPane('3d').Hide()
  208. self._mgr.GetPane('vdigit').Show()
  209. self.toolbars['vdigit'] = VDigitToolbar(parent = self, MapWindow = self.MapWindow,
  210. layerTree = self.tree,
  211. log = log)
  212. self.MapWindowVDigit.SetToolbar(self.toolbars['vdigit'])
  213. self._mgr.AddPane(self.toolbars['vdigit'],
  214. wx.aui.AuiPaneInfo().
  215. Name("vdigittoolbar").Caption(_("Vector Digitizer Toolbar")).
  216. ToolbarPane().Top().Row(1).
  217. LeftDockable(False).RightDockable(False).
  218. BottomDockable(False).TopDockable(True).
  219. CloseButton(False).Layer(2).
  220. BestSize((self.toolbars['vdigit'].GetBestSize())))
  221. # change mouse to draw digitized line
  222. self.MapWindow.mouse['box'] = "point"
  223. self.MapWindow.zoomtype = 0
  224. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SOLID)
  225. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SOLID)
  226. def AddNviz(self):
  227. """!Add 3D view mode window
  228. """
  229. import nviz
  230. # check for GLCanvas and OpenGL
  231. if not haveNviz:
  232. self.toolbars['map'].combo.SetValue(_("2D view"))
  233. GError(parent = self,
  234. message = _("Unable to switch to 3D display mode.\nThe Nviz python extension "
  235. "was not found or loaded properly.\n"
  236. "Switching back to 2D display mode.\n\nDetails: %s" % nviz.errorMsg))
  237. return
  238. # disable 3D mode for other displays
  239. for page in range(0, self._layerManager.gm_cb.GetPageCount()):
  240. if self._layerManager.gm_cb.GetPage(page) != self._layerManager.curr_page:
  241. if '3D' in self._layerManager.gm_cb.GetPage(page).maptree.mapdisplay.toolbars['map'].combo.GetString(1):
  242. self._layerManager.gm_cb.GetPage(page).maptree.mapdisplay.toolbars['map'].combo.Delete(1)
  243. self.toolbars['map'].Enable2D(False)
  244. # add rotate tool to map toolbar
  245. self.toolbars['map'].InsertTool((('rotate', Icons['nviz']['rotate'],
  246. self.OnRotate, wx.ITEM_CHECK, 7),)) # 7 is position
  247. self.toolbars['map'].InsertTool((('flyThrough', Icons['nviz']['flyThrough'],
  248. self.OnFlyThrough, wx.ITEM_CHECK, 8),))
  249. self.toolbars['map'].ChangeToolsDesc(mode2d = False)
  250. # update status bar
  251. self.statusbarManager.HideStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  252. self.statusbarManager.SetMode(0)
  253. # erase map window
  254. self.MapWindow.EraseMap()
  255. self._layerManager.goutput.WriteCmdLog(_("Starting 3D view mode..."),
  256. switchPage = False)
  257. self.SetStatusText(_("Please wait, loading data..."), 0)
  258. # create GL window
  259. if not self.MapWindow3D:
  260. self.MapWindow3D = GLWindow(self, id = wx.ID_ANY,
  261. Map = self.Map, tree = self.tree, lmgr = self._layerManager)
  262. self.MapWindow = self.MapWindow3D
  263. self.MapWindow.SetCursor(self.cursors["default"])
  264. # add Nviz notebookpage
  265. self._layerManager.AddNvizTools()
  266. # switch from MapWindow to MapWindowGL
  267. self._mgr.GetPane('2d').Hide()
  268. self._mgr.AddPane(self.MapWindow3D, wx.aui.AuiPaneInfo().CentrePane().
  269. Dockable(False).BestSize((-1,-1)).Name('3d').
  270. CloseButton(False).DestroyOnClose(True).
  271. Layer(0))
  272. self.MapWindow3D.OnPaint(None) # -> LoadData
  273. self.MapWindow3D.Show()
  274. self.MapWindow3D.ResetViewHistory()
  275. self.MapWindow3D.UpdateView(None)
  276. else:
  277. self.MapWindow = self.MapWindow3D
  278. os.environ['GRASS_REGION'] = self.Map.SetRegion(windres = True)
  279. self.MapWindow3D.GetDisplay().Init()
  280. del os.environ['GRASS_REGION']
  281. # switch from MapWindow to MapWindowGL
  282. self._mgr.GetPane('2d').Hide()
  283. self._mgr.GetPane('3d').Show()
  284. # add Nviz notebookpage
  285. self._layerManager.AddNvizTools()
  286. self.MapWindow3D.ResetViewHistory()
  287. for page in ('view', 'light', 'fringe', 'constant', 'cplane', 'animation'):
  288. self._layerManager.nviz.UpdatePage(page)
  289. self.MapWindow3D.overlays = self.MapWindow2D.overlays
  290. self.MapWindow3D.textdict = self.MapWindow2D.textdict
  291. # update overlays needs to be called after because getClientSize
  292. # is called during update and it must give reasonable values
  293. wx.CallAfter(self.MapWindow3D.UpdateOverlays)
  294. self.SetStatusText("", 0)
  295. self._mgr.Update()
  296. def RemoveNviz(self):
  297. """!Restore 2D view"""
  298. self.toolbars['map'].RemoveTool(self.toolbars['map'].rotate)
  299. self.toolbars['map'].RemoveTool(self.toolbars['map'].flyThrough)
  300. # update status bar
  301. self.statusbarManager.ShowStatusbarChoiceItemsByClass(self.statusbarItemsHiddenInNviz)
  302. self.statusbarManager.SetMode(UserSettings.Get(group = 'display',
  303. key = 'statusbarMode',
  304. subkey = 'selection'))
  305. self.SetStatusText(_("Please wait, unloading data..."), 0)
  306. self._layerManager.goutput.WriteCmdLog(_("Switching back to 2D view mode..."),
  307. switchPage = False)
  308. self.MapWindow3D.OnClose(event = None)
  309. # switch from MapWindowGL to MapWindow
  310. self._mgr.GetPane('2d').Show()
  311. self._mgr.GetPane('3d').Hide()
  312. self.MapWindow = self.MapWindow2D
  313. # remove nviz notebook page
  314. self._layerManager.RemoveNvizTools()
  315. self.MapWindow2D.overlays = self.MapWindow3D.overlays
  316. self.MapWindow2D.textdict = self.MapWindow3D.textdict
  317. self.MapWindow.UpdateMap()
  318. self._mgr.Update()
  319. def AddToolbar(self, name):
  320. """!Add defined toolbar to the window
  321. Currently known toolbars are:
  322. - 'map' - basic map toolbar
  323. - 'vdigit' - vector digitizer
  324. - 'gcpdisp' - GCP Manager Display
  325. """
  326. # default toolbar
  327. if name == "map":
  328. self.toolbars['map'] = MapToolbar(self, self.Map)
  329. self._mgr.AddPane(self.toolbars['map'],
  330. wx.aui.AuiPaneInfo().
  331. Name("maptoolbar").Caption(_("Map Toolbar")).
  332. ToolbarPane().Top().Name('mapToolbar').
  333. LeftDockable(False).RightDockable(False).
  334. BottomDockable(False).TopDockable(True).
  335. CloseButton(False).Layer(2).
  336. BestSize((self.toolbars['map'].GetBestSize())))
  337. # vector digitizer
  338. elif name == "vdigit":
  339. self._addToolbarVDigit()
  340. self._mgr.Update()
  341. def RemoveToolbar (self, name):
  342. """!Removes defined toolbar from the window
  343. @todo Only hide, activate by calling AddToolbar()
  344. """
  345. # cannot hide main toolbar
  346. if name == "map":
  347. return
  348. self._mgr.DetachPane(self.toolbars[name])
  349. self.toolbars[name].Destroy()
  350. self.toolbars.pop(name)
  351. if name == 'vdigit':
  352. self._mgr.GetPane('vdigit').Hide()
  353. self._mgr.GetPane('2d').Show()
  354. self.MapWindow = self.MapWindow2D
  355. self.toolbars['map'].combo.SetValue(_("2D view"))
  356. self.toolbars['map'].Enable2D(True)
  357. self._mgr.Update()
  358. def IsPaneShown(self, name):
  359. """!Check if pane (toolbar, mapWindow ...) of given name is currently shown"""
  360. if self._mgr.GetPane(name).IsOk():
  361. return self._mgr.GetPane(name).IsShown()
  362. return False
  363. def OnUpdateProgress(self, event):
  364. """!Update progress bar info
  365. """
  366. self.GetProgressBar().SetValue(event.value)
  367. event.Skip()
  368. def OnFocus(self, event):
  369. """!Change choicebook page to match display.
  370. """
  371. # change bookcontrol page to page associated with display
  372. if self.page:
  373. pgnum = self.layerbook.GetPageIndex(self.page)
  374. if pgnum > -1:
  375. self.layerbook.SetSelection(pgnum)
  376. self._layerManager.curr_page = self.layerbook.GetCurrentPage()
  377. event.Skip()
  378. def OnRender(self, event):
  379. """!Re-render map composition (each map layer)
  380. """
  381. # delete tmp map layers (queries)
  382. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)
  383. for layer in qlayer:
  384. self.Map.DeleteLayer(layer)
  385. # delete tmp lines
  386. if self.MapWindow.mouse["use"] in ("measure",
  387. "profile"):
  388. self.MapWindow.polycoords = []
  389. self.MapWindow.ClearLines()
  390. # deselect features in vdigit
  391. if self.GetToolbar('vdigit'):
  392. self.MapWindow.digit.GetDisplay().SetSelected([])
  393. self.MapWindow.UpdateMap(render = True, renderVector = True)
  394. else:
  395. self.MapWindow.UpdateMap(render = True)
  396. # update statusbar
  397. self.StatusbarUpdate()
  398. def OnPointer(self, event):
  399. """!Pointer button clicked
  400. """
  401. if self.GetMapToolbar():
  402. if event:
  403. self.toolbars['map'].OnTool(event)
  404. self.toolbars['map'].action['desc'] = ''
  405. self.MapWindow.mouse['use'] = "pointer"
  406. self.MapWindow.mouse['box'] = "point"
  407. # change the cursor
  408. if self.GetToolbar('vdigit'):
  409. # digitization tool activated
  410. self.MapWindow.SetCursor(self.cursors["cross"])
  411. # reset mouse['box'] if needed
  412. if self.toolbars['vdigit'].GetAction() in ['addLine']:
  413. if self.toolbars['vdigit'].GetAction('type') in ['point', 'centroid']:
  414. self.MapWindow.mouse['box'] = 'point'
  415. else: # line, boundary
  416. self.MapWindow.mouse['box'] = 'line'
  417. elif self.toolbars['vdigit'].GetAction() in ['addVertex', 'removeVertex', 'splitLine',
  418. 'editLine', 'displayCats', 'queryMap',
  419. 'copyCats']:
  420. self.MapWindow.mouse['box'] = 'point'
  421. else: # moveLine, deleteLine
  422. self.MapWindow.mouse['box'] = 'box'
  423. else:
  424. self.MapWindow.SetCursor(self.cursors["default"])
  425. def OnRotate(self, event):
  426. """!Rotate 3D view
  427. """
  428. if self.GetMapToolbar():
  429. self.toolbars['map'].OnTool(event)
  430. self.toolbars['map'].action['desc'] = ''
  431. self.MapWindow.mouse['use'] = "rotate"
  432. # change the cursor
  433. self.MapWindow.SetCursor(self.cursors["hand"])
  434. def OnFlyThrough(self, event):
  435. """!Fly-through mode
  436. """
  437. if self.GetMapToolbar():
  438. self.toolbars['map'].OnTool(event)
  439. self.toolbars['map'].action['desc'] = ''
  440. self.MapWindow.mouse['use'] = "fly"
  441. # change the cursor
  442. self.MapWindow.SetCursor(self.cursors["hand"])
  443. self.MapWindow.SetFocus()
  444. def OnZoomRegion(self, event):
  445. """!Zoom to region
  446. """
  447. self.Map.getRegion()
  448. self.Map.getResolution()
  449. self.UpdateMap()
  450. # event.Skip()
  451. def OnAlignRegion(self, event):
  452. """!Align region
  453. """
  454. if not self.Map.alignRegion:
  455. self.Map.alignRegion = True
  456. else:
  457. self.Map.alignRegion = False
  458. # event.Skip()
  459. def SaveToFile(self, event):
  460. """!Save map to image
  461. """
  462. if self.IsPaneShown('3d'):
  463. filetype = "PPM file (*.ppm)|*.ppm|TIF file (*.tif)|*.tif"
  464. ltype = [{ 'ext' : 'ppm', 'type' : 'ppm' },
  465. { 'ext' : 'tif', 'type' : 'tif' }]
  466. else:
  467. img = self.MapWindow.img
  468. if not img:
  469. GMessage(parent = self,
  470. message = _("Nothing to render (empty map). Operation canceled."))
  471. return
  472. filetype, ltype = GetImageHandlers(img)
  473. # get size
  474. dlg = ImageSizeDialog(self)
  475. dlg.CentreOnParent()
  476. if dlg.ShowModal() != wx.ID_OK:
  477. dlg.Destroy()
  478. return
  479. width, height = dlg.GetValues()
  480. dlg.Destroy()
  481. # get filename
  482. dlg = wx.FileDialog(parent = self,
  483. message = _("Choose a file name to save the image "
  484. "(no need to add extension)"),
  485. wildcard = filetype,
  486. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  487. if dlg.ShowModal() == wx.ID_OK:
  488. path = dlg.GetPath()
  489. if not path:
  490. dlg.Destroy()
  491. return
  492. base, ext = os.path.splitext(path)
  493. fileType = ltype[dlg.GetFilterIndex()]['type']
  494. extType = ltype[dlg.GetFilterIndex()]['ext']
  495. if ext != extType:
  496. path = base + '.' + extType
  497. self.MapWindow.SaveToFile(path, fileType,
  498. width, height)
  499. dlg.Destroy()
  500. def PrintMenu(self, event):
  501. """
  502. Print options and output menu for map display
  503. """
  504. point = wx.GetMousePosition()
  505. printmenu = wx.Menu()
  506. # Add items to the menu
  507. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  508. printmenu.AppendItem(setup)
  509. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  510. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  511. printmenu.AppendItem(preview)
  512. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  513. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  514. printmenu.AppendItem(doprint)
  515. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  516. # Popup the menu. If an item is selected then its handler
  517. # will be called before PopupMenu returns.
  518. self.PopupMenu(printmenu)
  519. printmenu.Destroy()
  520. def OnCloseWindow(self, event):
  521. """!Window closed.
  522. Also close associated layer tree page
  523. """
  524. pgnum = None
  525. self.Map.Clean()
  526. # close edited map and 3D tools properly
  527. if self.GetToolbar('vdigit'):
  528. maplayer = self.toolbars['vdigit'].GetLayer()
  529. if maplayer:
  530. self.toolbars['vdigit'].OnExit()
  531. if self.IsPaneShown('3d'):
  532. self.RemoveNviz()
  533. if not self._layerManager:
  534. self.Destroy()
  535. elif self.page:
  536. pgnum = self.layerbook.GetPageIndex(self.page)
  537. if pgnum > -1:
  538. self.layerbook.DeletePage(pgnum)
  539. def QueryMap(self, x, y):
  540. """!Query raster or vector map layers by r/v.what
  541. @param x,y coordinates
  542. """
  543. # set query snap distance for v.what at map unit equivalent of 10 pixels
  544. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  545. east, north = self.MapWindow.Pixel2Cell((x, y))
  546. if not self.IsStandalone():
  547. num = 0
  548. for layer in self.tree.GetSelections():
  549. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  550. if ltype in ('raster', 'rgb', 'his',
  551. 'vector', 'thememap', 'themechart'):
  552. num += 1
  553. if num < 1:
  554. GMessage(parent = self,
  555. message = _('No raster or vector map layer selected for querying.'))
  556. return
  557. rast = list()
  558. vect = list()
  559. rcmd = ['r.what', '--v']
  560. vcmd = ['v.what', '--v']
  561. if self.IsStandalone():
  562. pass
  563. else:
  564. for layer in self.tree.GetSelections():
  565. ltype = self.tree.GetPyData(layer)[0]['maplayer'].GetType()
  566. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  567. name, found = GetLayerNameFromCmd(dcmd)
  568. if not found:
  569. continue
  570. if ltype == 'raster':
  571. rast.append(name)
  572. elif ltype in ('rgb', 'his'):
  573. for iname in name.split('\n'):
  574. rast.append(iname)
  575. elif ltype in ('vector', 'thememap', 'themechart'):
  576. vect.append(name)
  577. # rasters are not queried this way in 3D, we don't want them now
  578. if self.IsPaneShown('3d'):
  579. rast = list()
  580. # use display region settings instead of computation region settings
  581. self.tmpreg = os.getenv("GRASS_REGION")
  582. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres = False)
  583. # build query commands for any selected rasters and vectors
  584. if rast:
  585. rcmd.append('-f')
  586. rcmd.append('-n')
  587. rcmd.append('input=%s' % ','.join(rast))
  588. rcmd.append('east_north=%f,%f' % (float(east), float(north)))
  589. if vect:
  590. # check for vector maps open to be edited
  591. digitToolbar = self.toolbars['vdigit']
  592. if digitToolbar:
  593. lmap = digitToolbar.GetLayer().GetName()
  594. for name in vect:
  595. if lmap == name:
  596. self._layerManager.goutput.WriteWarning(_("Vector map <%s> "
  597. "opened for editing - skipped.") % map)
  598. vect.remove(name)
  599. if len(vect) < 1:
  600. self._layerManager.goutput.WriteCmdLog(_("Nothing to query."))
  601. return
  602. vcmd.append('-a')
  603. vcmd.append('map=%s' % ','.join(vect))
  604. vcmd.append('layer=%s' % ','.join(['-1'] * len(vect)))
  605. vcmd.append('east_north=%f,%f' % (float(east), float(north)))
  606. vcmd.append('distance=%f' % float(qdist))
  607. Debug.msg(1, "QueryMap(): raster=%s vector=%s" % (','.join(rast),
  608. ','.join(vect)))
  609. # parse query command(s)
  610. if not self.IsStandalone():
  611. if rast:
  612. self._layerManager.goutput.RunCmd(rcmd,
  613. compReg = False,
  614. onDone = self._QueryMapDone)
  615. if vect:
  616. self._layerManager.goutput.RunCmd(vcmd,
  617. onDone = self._QueryMapDone)
  618. else:
  619. if rast:
  620. RunCommand(rcmd)
  621. if vect:
  622. RunCommand(vcmd)
  623. def _QueryMapDone(self, cmd, returncode):
  624. """!Restore settings after querying (restore GRASS_REGION)
  625. @param returncode command return code
  626. """
  627. if hasattr(self, "tmpreg"):
  628. if self.tmpreg:
  629. os.environ["GRASS_REGION"] = self.tmpreg
  630. elif 'GRASS_REGION' in os.environ:
  631. del os.environ["GRASS_REGION"]
  632. elif 'GRASS_REGION' in os.environ:
  633. del os.environ["GRASS_REGION"]
  634. if hasattr(self, "tmpreg"):
  635. del self.tmpreg
  636. def QueryVector(self, x, y):
  637. """!Query vector map layer features
  638. Attribute data of selected vector object are displayed in GUI dialog.
  639. Data can be modified (On Submit)
  640. """
  641. if not self.tree.layer_selected or \
  642. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  643. GMessage(parent = self,
  644. message = _("No map layer selected for querying."))
  645. return
  646. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  647. y + self.MapWindow.dialogOffset))
  648. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) /
  649. self.Map.width)
  650. east, north = self.MapWindow.Pixel2Cell((x, y))
  651. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  652. if self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetMapset() != \
  653. grass.gisenv()['MAPSET']:
  654. mode = 'display'
  655. else:
  656. mode = 'update'
  657. if self.dialogs['attributes'] is None:
  658. dlg = DisplayAttributesDialog(parent = self.MapWindow,
  659. map = mapName,
  660. query = ((east, north), qdist),
  661. pos = posWindow,
  662. action = mode)
  663. self.dialogs['attributes'] = dlg
  664. else:
  665. # selection changed?
  666. if not self.dialogs['attributes'].mapDBInfo or \
  667. self.dialogs['attributes'].mapDBInfo.map != mapName:
  668. self.dialogs['attributes'].UpdateDialog(map = mapName, query = ((east, north), qdist),
  669. action = mode)
  670. else:
  671. self.dialogs['attributes'].UpdateDialog(query = ((east, north), qdist),
  672. action = mode)
  673. if not self.dialogs['attributes'].IsFound():
  674. self._layerManager.goutput.WriteLog(_('Nothing found.'))
  675. cats = self.dialogs['attributes'].GetCats()
  676. qlayer = None
  677. if not self.IsPaneShown('3d'):
  678. try:
  679. qlayer = self.Map.GetListOfLayers(l_name = globalvar.QUERYLAYER)[0]
  680. except IndexError:
  681. pass
  682. if self.dialogs['attributes'].mapDBInfo and cats:
  683. if not self.IsPaneShown('3d'):
  684. # highlight feature & re-draw map
  685. if qlayer:
  686. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  687. useId = False,
  688. addLayer = False))
  689. else:
  690. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId = False)
  691. # set opacity based on queried layer
  692. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float = True)
  693. qlayer.SetOpacity(opacity)
  694. self.MapWindow.UpdateMap(render = False, renderVector = False)
  695. if not self.dialogs['attributes'].IsShown():
  696. self.dialogs['attributes'].Show()
  697. else:
  698. if qlayer:
  699. self.Map.DeleteLayer(qlayer)
  700. self.MapWindow.UpdateMap(render = False, renderVector = False)
  701. if self.dialogs['attributes'].IsShown():
  702. self.dialogs['attributes'].Hide()
  703. def OnQuery(self, event):
  704. """!Query tools menu"""
  705. if self.GetMapToolbar():
  706. self.toolbars['map'].OnTool(event)
  707. action = self.toolbars['map'].GetAction()
  708. self.toolbars['map'].action['desc'] = 'queryMap'
  709. self.MapWindow.mouse['use'] = "query"
  710. if not self.IsStandalone():
  711. # switch to output console to show query results
  712. self._layerManager.notebook.SetSelectionByName('output')
  713. self.MapWindow.mouse['box'] = "point"
  714. self.MapWindow.zoomtype = 0
  715. # change the cursor
  716. self.MapWindow.SetCursor(self.cursors["cross"])
  717. def AddTmpVectorMapLayer(self, name, cats, useId = False, addLayer = True):
  718. """!Add temporal vector map layer to map composition
  719. @param name name of map layer
  720. @param useId use feature id instead of category
  721. """
  722. # color settings from ATM
  723. color = UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'color')
  724. colorStr = str(color[0]) + ":" + \
  725. str(color[1]) + ":" + \
  726. str(color[2])
  727. # icon used in vector display and its size
  728. icon = ''
  729. size = 0
  730. vparam = self.tree.GetPyData(self.tree.layer_selected)[0]['cmd']
  731. for p in vparam:
  732. if '=' in p:
  733. parg,pval = p.split('=')
  734. if parg == 'icon': icon = pval
  735. elif parg == 'size': size = int(pval)
  736. pattern = ["d.vect",
  737. "map=%s" % name,
  738. "color=%s" % colorStr,
  739. "fcolor=%s" % colorStr,
  740. "width=%d" % UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'width')]
  741. if icon != '':
  742. pattern.append('icon=%s' % icon)
  743. if size > 0:
  744. pattern.append('size=%i' % size)
  745. if useId:
  746. cmd = pattern
  747. cmd.append('-i')
  748. cmd.append('cats=%s' % str(cats))
  749. else:
  750. cmd = []
  751. for layer in cats.keys():
  752. cmd.append(copy.copy(pattern))
  753. lcats = cats[layer]
  754. cmd[-1].append("layer=%d" % layer)
  755. cmd[-1].append("cats=%s" % ListOfCatsToRange(lcats))
  756. if addLayer:
  757. if useId:
  758. return self.Map.AddLayer(type = 'vector', name = globalvar.QUERYLAYER, command = cmd,
  759. l_active = True, l_hidden = True, l_opacity = 1.0)
  760. else:
  761. return self.Map.AddLayer(type = 'command', name = globalvar.QUERYLAYER, command = cmd,
  762. l_active = True, l_hidden = True, l_opacity = 1.0)
  763. else:
  764. return cmd
  765. def OnAnalyze(self, event):
  766. """!Analysis tools menu
  767. """
  768. point = wx.GetMousePosition()
  769. toolsmenu = wx.Menu()
  770. icons = Icons['displayWindow']
  771. # Add items to the menu
  772. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["measure"].GetLabel())
  773. measure.SetBitmap(icons["measure"].GetBitmap(self.iconsize))
  774. toolsmenu.AppendItem(measure)
  775. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  776. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["profile"].GetLabel())
  777. profile.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  778. toolsmenu.AppendItem(profile)
  779. self.Bind(wx.EVT_MENU, self.OnProfile, profile)
  780. scatterplot = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create bivariate scatterplot of raster maps"))
  781. scatterplot.SetBitmap(icons["profile"].GetBitmap(self.iconsize))
  782. toolsmenu.AppendItem(scatterplot)
  783. self.Bind(wx.EVT_MENU, self.OnScatterplot, scatterplot)
  784. histogram2 = wx.MenuItem(toolsmenu, wx.ID_ANY, icons["histogram"].GetLabel())
  785. histogram2.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  786. toolsmenu.AppendItem(histogram2)
  787. self.Bind(wx.EVT_MENU, self.OnHistogramPyPlot, histogram2)
  788. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, _("Create histogram with d.histogram"))
  789. histogram.SetBitmap(icons["histogram"].GetBitmap(self.iconsize))
  790. toolsmenu.AppendItem(histogram)
  791. self.Bind(wx.EVT_MENU, self.OnHistogram, histogram)
  792. # Popup the menu. If an item is selected then its handler
  793. # will be called before PopupMenu returns.
  794. self.PopupMenu(toolsmenu)
  795. toolsmenu.Destroy()
  796. def OnMeasure(self, event):
  797. """!Init measurement routine that calculates map distance
  798. along transect drawn on map display
  799. """
  800. self.totaldist = 0.0 # total measured distance
  801. # switch Layer Manager to output console to show measure results
  802. self._layerManager.notebook.SetSelectionByName('output')
  803. # change mouse to draw line for measurement
  804. self.MapWindow.mouse['use'] = "measure"
  805. self.MapWindow.mouse['box'] = "line"
  806. self.MapWindow.zoomtype = 0
  807. self.MapWindow.pen = wx.Pen(colour = 'red', width = 2, style = wx.SHORT_DASH)
  808. self.MapWindow.polypen = wx.Pen(colour = 'green', width = 2, style = wx.SHORT_DASH)
  809. # change the cursor
  810. self.MapWindow.SetCursor(self.cursors["pencil"])
  811. # initiating output
  812. style = self._layerManager.goutput.cmdOutput.StyleWarning
  813. self._layerManager.goutput.WriteLog(_('Click and drag with left mouse button '
  814. 'to measure.%s'
  815. 'Double click with left button to clear.') % \
  816. (os.linesep), style)
  817. if self.Map.projinfo['proj'] != 'xy':
  818. units = self.Map.projinfo['units']
  819. self._layerManager.goutput.WriteCmdLog(_('Measuring distance') + ' ('
  820. + units + '):')
  821. else:
  822. self._layerManager.goutput.WriteCmdLog(_('Measuring distance:'))
  823. if self.Map.projinfo['proj'] == 'll':
  824. try:
  825. import grass.lib.gis as gislib
  826. global haveCtypes
  827. haveCtypes = True
  828. gislib.G_begin_distance_calculations()
  829. except ImportError, e:
  830. self._layerManager.goutput.WriteWarning(_('Geodesic distance is not yet '
  831. 'supported by this tool.\n'
  832. 'Reason: %s' % e))
  833. def MeasureDist(self, beginpt, endpt):
  834. """!Calculate map distance from screen distance
  835. and print to output window
  836. """
  837. self._layerManager.notebook.SetSelectionByName('output')
  838. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  839. dist = round(dist, 3)
  840. d, dunits = self.FormatDist(dist)
  841. self.totaldist += dist
  842. td, tdunits = self.FormatDist(self.totaldist)
  843. strdist = str(d)
  844. strtotdist = str(td)
  845. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  846. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  847. angle = 180 - angle
  848. if angle < 0:
  849. angle = 360 + angle
  850. mstring = '%s = %s %s\n%s = %s %s\n%s = %d %s\n%s' \
  851. % (_('segment'), strdist, dunits,
  852. _('total distance'), strtotdist, tdunits,
  853. _('bearing'), angle, _('deg'),
  854. '-' * 60)
  855. else:
  856. mstring = '%s = %s %s\n%s = %s %s\n%s' \
  857. % (_('segment'), strdist, dunits,
  858. _('total distance'), strtotdist, tdunits,
  859. '-' * 60)
  860. self._layerManager.goutput.WriteLog(mstring)
  861. return dist
  862. def OnProfile(self, event):
  863. """!Init profile canvas and tools
  864. """
  865. raster = []
  866. if self.tree.layer_selected and \
  867. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  868. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  869. self.profile = ProfileFrame(self, size = wx.Size(700, 300),
  870. rasterList = raster)
  871. self.profile.Show()
  872. # Open raster select dialog to make sure that a raster (and the desired raster)
  873. # is selected to be profiled
  874. self.profile.OnSelectRaster(None)
  875. def FormatDist(self, dist):
  876. """!Format length numbers and units in a nice way,
  877. as a function of length. From code by Hamish Bowman
  878. Grass Development Team 2006"""
  879. mapunits = self.Map.projinfo['units']
  880. if mapunits == 'metres':
  881. mapunits = 'meters'
  882. outunits = mapunits
  883. dist = float(dist)
  884. divisor = 1.0
  885. # figure out which units to use
  886. if mapunits == 'meters':
  887. if dist > 2500.0:
  888. outunits = 'km'
  889. divisor = 1000.0
  890. else: outunits = 'm'
  891. elif mapunits == 'feet':
  892. # nano-bug: we match any "feet", but US Survey feet is really
  893. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  894. # miles the tick markers are rounded to the nearest 10th of a
  895. # mile (528'), the difference in foot flavours is ignored.
  896. if dist > 5280.0:
  897. outunits = 'miles'
  898. divisor = 5280.0
  899. else:
  900. outunits = 'ft'
  901. elif 'degree' in mapunits and \
  902. not haveCtypes:
  903. if dist < 1:
  904. outunits = 'min'
  905. divisor = (1/60.0)
  906. else:
  907. outunits = 'deg'
  908. else:
  909. outunits = 'meters'
  910. # format numbers in a nice way
  911. if (dist/divisor) >= 2500.0:
  912. outdist = round(dist/divisor)
  913. elif (dist/divisor) >= 1000.0:
  914. outdist = round(dist/divisor,1)
  915. elif (dist/divisor) > 0.0:
  916. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  917. else:
  918. outdist = float(dist/divisor)
  919. return (outdist, outunits)
  920. def OnHistogramPyPlot(self, event):
  921. """!Init PyPlot histogram display canvas and tools
  922. """
  923. raster = []
  924. for layer in self.tree.GetSelections():
  925. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  926. continue
  927. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  928. self.histogramPyPlot = Histogram2Frame(self, id = wx.ID_ANY,
  929. pos = wx.DefaultPosition, size = (700,300),
  930. style = wx.DEFAULT_FRAME_STYLE,
  931. rasterList = raster)
  932. self.histogramPyPlot.Show()
  933. # Open raster select dialog to make sure that a raster (and the desired raster)
  934. # is selected to be histogrammed
  935. self.histogramPyPlot.OnSelectRaster(None)
  936. def OnScatterplot(self, event):
  937. """!Init PyPlot scatterplot display canvas and tools
  938. """
  939. raster = []
  940. for layer in self.tree.GetSelections():
  941. if self.tree.GetPyData(layer)[0]['maplayer'].GetType() != 'raster':
  942. continue
  943. raster.append(self.tree.GetPyData(layer)[0]['maplayer'].GetName())
  944. self.scatterplot = ScatterFrame(self, id = wx.ID_ANY,
  945. pos = wx.DefaultPosition, size = (700,300),
  946. style = wx.DEFAULT_FRAME_STYLE,
  947. rasterList = raster)
  948. self.scatterplot.Show()
  949. # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters)
  950. # are selected to be plotted
  951. self.scatterplot.OnSelectRaster(None)
  952. def OnHistogram(self, event):
  953. """!Init histogram display canvas and tools
  954. """
  955. self.histogram = HistogramFrame(parent = self, id = wx.ID_ANY, size = globalvar.HIST_WINDOW_SIZE,
  956. style = wx.DEFAULT_FRAME_STYLE)
  957. # show new display
  958. self.histogram.Show()
  959. self.histogram.Refresh()
  960. self.histogram.Update()
  961. def OnDecoration(self, event):
  962. """!Decorations overlay menu
  963. """
  964. point = wx.GetMousePosition()
  965. decmenu = wx.Menu()
  966. icons = Icons['displayWindow']
  967. # Add items to the menu
  968. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, icons["addBarscale"].GetLabel())
  969. AddScale.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  970. decmenu.AppendItem(AddScale)
  971. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  972. # temporary
  973. if self.IsPaneShown('3d'):
  974. AddScale.Enable(False)
  975. AddArrow = wx.MenuItem(decmenu, wx.ID_ANY, _("Add north arrow"))
  976. AddArrow.SetBitmap(icons["addBarscale"].GetBitmap(self.iconsize))
  977. decmenu.AppendItem(AddArrow)
  978. self.Bind(wx.EVT_MENU, self.OnAddArrow, AddArrow)
  979. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, icons["addLegend"].GetLabel())
  980. AddLegend.SetBitmap(icons["addLegend"].GetBitmap(self.iconsize))
  981. decmenu.AppendItem(AddLegend)
  982. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  983. AddText = wx.MenuItem(decmenu, wx.ID_ANY, icons["addText"].GetLabel())
  984. AddText.SetBitmap(icons["addText"].GetBitmap(self.iconsize))
  985. decmenu.AppendItem(AddText)
  986. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  987. # Popup the menu. If an item is selected then its handler
  988. # will be called before PopupMenu returns.
  989. self.PopupMenu(decmenu)
  990. decmenu.Destroy()
  991. def OnAddBarscale(self, event):
  992. """!Handler for scale/arrow map decoration menu selection.
  993. """
  994. if self.dialogs['barscale']:
  995. return
  996. id = 0 # unique index for overlay layer
  997. # If location is latlon, only display north arrow (scale won't work)
  998. # proj = self.Map.projinfo['proj']
  999. # if proj == 'll':
  1000. # barcmd = 'd.barscale -n'
  1001. # else:
  1002. # barcmd = 'd.barscale'
  1003. # decoration overlay control dialog
  1004. self.dialogs['barscale'] = \
  1005. DecorationDialog(parent = self, title = _('Scale and North arrow'),
  1006. size = (350, 200),
  1007. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1008. cmd = ['d.barscale', 'at=0,95'],
  1009. ovlId = id,
  1010. name = 'barscale',
  1011. checktxt = _("Show/hide scale and North arrow"),
  1012. ctrltxt = _("scale object"))
  1013. self.dialogs['barscale'].CentreOnParent()
  1014. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1015. ### self.dialogs['barscale'].ShowModal()
  1016. self.dialogs['barscale'].Show()
  1017. self.MapWindow.mouse['use'] = 'pointer'
  1018. def OnAddLegend(self, event):
  1019. """!Handler for legend map decoration menu selection.
  1020. """
  1021. if self.dialogs['legend']:
  1022. return
  1023. id = 1 # index for overlay layer in render
  1024. cmd = ['d.legend', 'at=5,50,2,5']
  1025. if self.tree and self.tree.layer_selected and \
  1026. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1027. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1028. # Decoration overlay control dialog
  1029. self.dialogs['legend'] = \
  1030. DecorationDialog(parent = self, title = ('Legend'),
  1031. size = (350, 200),
  1032. style = wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1033. cmd = cmd,
  1034. ovlId = id,
  1035. name = 'legend',
  1036. checktxt = _("Show/hide legend"),
  1037. ctrltxt = _("legend object"))
  1038. self.dialogs['legend'].CentreOnParent()
  1039. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1040. ### self.dialogs['legend'].ShowModal()
  1041. self.dialogs['legend'].Show()
  1042. self.MapWindow.mouse['use'] = 'pointer'
  1043. def OnAddText(self, event):
  1044. """!Handler for text decoration menu selection.
  1045. """
  1046. if self.MapWindow.dragid > -1:
  1047. id = self.MapWindow.dragid
  1048. self.MapWindow.dragid = -1
  1049. else:
  1050. # index for overlay layer in render
  1051. if len(self.MapWindow.textdict.keys()) > 0:
  1052. id = max(self.MapWindow.textdict.keys()) + 1
  1053. else:
  1054. id = 101
  1055. self.dialogs['text'] = TextLayerDialog(parent = self, ovlId = id,
  1056. title = _('Add text layer'),
  1057. size = (400, 200))
  1058. self.dialogs['text'].CenterOnParent()
  1059. # If OK button pressed in decoration control dialog
  1060. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1061. text = self.dialogs['text'].GetValues()['text']
  1062. active = self.dialogs['text'].GetValues()['active']
  1063. # delete object if it has no text or is not active
  1064. if text == '' or active == False:
  1065. try:
  1066. self.MapWindow2D.pdc.ClearId(id)
  1067. self.MapWindow2D.pdc.RemoveId(id)
  1068. del self.MapWindow.textdict[id]
  1069. if self.IsPaneShown('3d'):
  1070. self.MapWindow3D.UpdateOverlays()
  1071. self.MapWindow.UpdateMap()
  1072. else:
  1073. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1074. except:
  1075. pass
  1076. return
  1077. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1078. if self.IsPaneShown('3d'):
  1079. self.MapWindow3D.UpdateOverlays()
  1080. self.MapWindow3D.UpdateMap()
  1081. else:
  1082. self.MapWindow2D.pdc.ClearId(id)
  1083. self.MapWindow2D.pdc.SetId(id)
  1084. self.MapWindow2D.UpdateMap(render = False, renderVector = False)
  1085. self.MapWindow.mouse['use'] = 'pointer'
  1086. def OnAddArrow(self, event):
  1087. """!Handler for north arrow menu selection.
  1088. Opens Appearance page of nviz notebook.
  1089. """
  1090. self._layerManager.nviz.SetPage('decoration')
  1091. self.MapWindow3D.SetDrawArrow((70, 70))
  1092. def GetOptData(self, dcmd, type, params, propwin):
  1093. """!Callback method for decoration overlay command generated by
  1094. dialog created in menuform.py
  1095. """
  1096. # Reset comand and rendering options in render.Map. Always render decoration.
  1097. # Showing/hiding handled by PseudoDC
  1098. self.Map.ChangeOverlay(ovltype = type, type = 'overlay', name = '', command = dcmd,
  1099. l_active = True, l_render = False)
  1100. self.params[type] = params
  1101. self.propwin[type] = propwin
  1102. def OnZoomToMap(self, event):
  1103. """!Set display extents to match selected raster (including
  1104. NULLs) or vector map.
  1105. """
  1106. layers = None
  1107. if self.IsStandalone():
  1108. layers = self.MapWindow.GetMap().GetListOfLayers(l_active = False)
  1109. self.MapWindow.ZoomToMap(layers = layers)
  1110. def OnZoomToRaster(self, event):
  1111. """!Set display extents to match selected raster map (ignore NULLs)
  1112. """
  1113. self.MapWindow.ZoomToMap(ignoreNulls = True)
  1114. def OnZoomToSaved(self, event):
  1115. """!Set display geometry to match extents in
  1116. saved region file
  1117. """
  1118. self.MapWindow.ZoomToSaved()
  1119. def OnDisplayToWind(self, event):
  1120. """!Set computational region (WIND file) to match display
  1121. extents
  1122. """
  1123. self.MapWindow.DisplayToWind()
  1124. def SaveDisplayRegion(self, event):
  1125. """!Save display extents to named region file.
  1126. """
  1127. self.MapWindow.SaveDisplayRegion()
  1128. def OnZoomMenu(self, event):
  1129. """!Popup Zoom menu
  1130. """
  1131. point = wx.GetMousePosition()
  1132. zoommenu = wx.Menu()
  1133. # Add items to the menu
  1134. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region'))
  1135. zoommenu.AppendItem(zoomwind)
  1136. self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
  1137. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1138. zoommenu.AppendItem(zoomdefault)
  1139. self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
  1140. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1141. zoommenu.AppendItem(zoomsaved)
  1142. self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
  1143. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display extent'))
  1144. zoommenu.AppendItem(savewind)
  1145. self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
  1146. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1147. zoommenu.AppendItem(savezoom)
  1148. self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
  1149. # Popup the menu. If an item is selected then its handler
  1150. # will be called before PopupMenu returns.
  1151. self.PopupMenu(zoommenu)
  1152. zoommenu.Destroy()
  1153. def SetProperties(self, render = False, mode = 0, showCompExtent = False,
  1154. constrainRes = False, projection = False, alignExtent = True):
  1155. """!Set properies of map display window"""
  1156. self.SetProperty('render', render)
  1157. self.statusbarManager.SetMode(mode)
  1158. self.StatusbarUpdate()
  1159. self.SetProperty('region', showCompExtent)
  1160. self.SetProperty('alignExtent', alignExtent)
  1161. self.SetProperty('resolution', constrainRes)
  1162. self.SetProperty('projection', projection)
  1163. def IsStandalone(self):
  1164. """!Check if Map display is standalone"""
  1165. if self._layerManager:
  1166. return False
  1167. return True
  1168. def GetLayerManager(self):
  1169. """!Get reference to Layer Manager
  1170. @return window reference
  1171. @return None (if standalone)
  1172. """
  1173. return self._layerManager
  1174. def GetMapToolbar(self):
  1175. """!Returns toolbar with zooming tools"""
  1176. return self.toolbars['map']
  1177. class MapApp(wx.App):
  1178. def OnInit(self):
  1179. wx.InitAllImageHandlers()
  1180. if __name__ == "__main__":
  1181. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1182. Map = Map(cmdfile = monFile['cmd'], mapfile = monFile['map'],
  1183. envfile = monFile['env'], monitor = monName)
  1184. else:
  1185. Map = None
  1186. self.mapFrm = MapFrame(parent = None, id = wx.ID_ANY, Map = Map,
  1187. size = monSize)
  1188. # self.SetTopWindow(Map)
  1189. self.mapFrm.Show()
  1190. if __name__ == "__main__":
  1191. self.timer = wx.PyTimer(self.watcher)
  1192. #check each 0.5s
  1193. global mtime
  1194. mtime = 500
  1195. self.timer.Start(mtime)
  1196. return True
  1197. def OnExit(self):
  1198. if __name__ == "__main__":
  1199. # stop the timer
  1200. # self.timer.Stop()
  1201. # terminate thread
  1202. for f in monFile.itervalues():
  1203. grass.try_remove(f)
  1204. def watcher(self):
  1205. """!Redraw, if new layer appears (check's timestamp of
  1206. cmdfile)
  1207. """
  1208. # todo: events
  1209. if os.path.getmtime(monFile['cmd']) > self.cmdTimeStamp:
  1210. self.timer.Stop()
  1211. self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
  1212. self.mapFrm.OnDraw(None)
  1213. self.mapFrm.GetMap().GetLayersFromCmdFile()
  1214. self.timer.Start(mtime)
  1215. if __name__ == "__main__":
  1216. # set command variable
  1217. if len(sys.argv) < 5:
  1218. print __doc__
  1219. sys.exit(1)
  1220. monName = sys.argv[1]
  1221. monFile = { 'map' : sys.argv[2],
  1222. 'cmd' : sys.argv[3],
  1223. 'env' : sys.argv[4],
  1224. }
  1225. if len(sys.argv) >= 6:
  1226. try:
  1227. monSize[0] = int(sys.argv[5])
  1228. except ValueError:
  1229. pass
  1230. if len(sys.argv) == 7:
  1231. try:
  1232. monSize[1] = int(sys.argv[6])
  1233. except ValueError:
  1234. pass
  1235. import gettext
  1236. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1237. grass.verbose(_("Starting map display <%s>...") % (monName))
  1238. RunCommand('g.gisenv',
  1239. set = 'MONITOR_%s_PID=%d' % (monName, os.getpid()))
  1240. gm_map = MapApp(0)
  1241. # set title
  1242. gm_map.mapFrm.SetTitle(_("GRASS GIS Map Display: " +
  1243. monName +
  1244. " - Location: " + grass.gisenv()["LOCATION_NAME"]))
  1245. gm_map.MainLoop()
  1246. grass.verbose(_("Stopping map display <%s>...") % (monName))
  1247. # clean up GRASS env variables
  1248. env = grass.gisenv()
  1249. env_name = 'MONITOR_%s' % monName
  1250. for key in env.keys():
  1251. if key.find(env_name) == 0:
  1252. RunCommand('g.gisenv',
  1253. set = '%s=' % key)
  1254. if key == 'MONITOR' and env[key] == monName:
  1255. RunCommand('g.gisenv',
  1256. set = '%s=' % key)
  1257. sys.exit(0)