mapdisp.py 62 KB

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