mapdisp.py 62 KB

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