mapdisp.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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 = "BMP file (*.bmp)|*.bmp|"\
  738. "GIF file (*.gif)|*.gif|"\
  739. "JPG file (*.jpg)|*.jpg|"\
  740. "PCX file (*.pcx)|*.pcx|"\
  741. "PNG file (*.png)|*.png|"\
  742. "PNM file (*.pnm)|*.pnm|"\
  743. "TIF file (*.tif)|*.tif|"\
  744. "XPM file (*.xpm)|*.xpm"
  745. dlg = wx.FileDialog(self, "Choose a file name to save the image (no need to add extension)",
  746. defaultDir = "",
  747. defaultFile = "",
  748. wildcard = filetype,
  749. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  750. if dlg.ShowModal() == wx.ID_OK:
  751. path = dlg.GetPath()
  752. if path == None: return
  753. base = os.path.splitext(dlg.GetPath())[0]
  754. ext = os.path.splitext(dlg.GetPath())[1]
  755. if dlg.GetFilterIndex() == 0:
  756. type = wx.BITMAP_TYPE_BMP
  757. if ext != '.bmp': path = base+'.bmp'
  758. if dlg.GetFilterIndex() == 1:
  759. type = wx.BITMAP_TYPE_GIF
  760. if ext != '.gif': path = base+'.gif'
  761. elif dlg.GetFilterIndex() == 2:
  762. type = wx.BITMAP_TYPE_JPEG
  763. if ext != '.jpg': path = base+'.jpg'
  764. elif dlg.GetFilterIndex() == 3:
  765. type = wx.BITMAP_TYPE_GIF
  766. if ext != '.pcx': path = base+'.pcx'
  767. elif dlg.GetFilterIndex() == 4:
  768. type = wx.BITMAP_TYPE_PNG
  769. if ext != '.png': path = base+'.png'
  770. elif dlg.GetFilterIndex() == 5:
  771. type = wx.BITMAP_TYPE_PNM
  772. if ext != '.pnm': path = base+'.pnm'
  773. elif dlg.GetFilterIndex() == 6:
  774. type = wx.BITMAP_TYPE_TIF
  775. if ext != '.tif': path = base+'.tif'
  776. elif dlg.GetFilterIndex() == 7:
  777. type = wx.BITMAP_TYPE_XPM
  778. if ext != '.xpm': path = base+'.xpm'
  779. self.MapWindow.SaveToFile(path, type)
  780. dlg.Destroy()
  781. def PrintMenu(self, event):
  782. """
  783. Print options and output menu for map display
  784. """
  785. point = wx.GetMousePosition()
  786. printmenu = wx.Menu()
  787. # Add items to the menu
  788. setup = wx.MenuItem(printmenu, wx.ID_ANY, _('Page setup'))
  789. printmenu.AppendItem(setup)
  790. self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)
  791. preview = wx.MenuItem(printmenu, wx.ID_ANY, _('Print preview'))
  792. printmenu.AppendItem(preview)
  793. self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)
  794. doprint = wx.MenuItem(printmenu, wx.ID_ANY, _('Print display'))
  795. printmenu.AppendItem(doprint)
  796. self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)
  797. # Popup the menu. If an item is selected then its handler
  798. # will be called before PopupMenu returns.
  799. self.PopupMenu(printmenu)
  800. printmenu.Destroy()
  801. def OnCloseWindow(self, event):
  802. """
  803. Window closed.
  804. Also close associated layer tree page
  805. """
  806. pgnum = None
  807. self.Map.Clean()
  808. # close edited map and 3D tools properly
  809. if self.toolbars['vdigit']:
  810. maplayer = self.toolbars['vdigit'].GetLayer()
  811. if maplayer:
  812. self.toolbars['vdigit'].OnExit()
  813. self.imgVectorMap = None
  814. if self.toolbars['nviz']:
  815. self.toolbars['nviz'].OnExit()
  816. if self.page:
  817. pgnum = self.layerbook.GetPageIndex(self.page)
  818. if pgnum > -1:
  819. self.layerbook.DeletePage(pgnum)
  820. ### self.Destroy()
  821. # if event:
  822. # event.Skip() <- causes application crash
  823. def GetRender(self):
  824. """
  825. Returns the current instance of render.Map()
  826. """
  827. return self.Map
  828. def OnQueryDisplay(self, event):
  829. """
  830. Query currrent raster/vector map layers (display mode)
  831. """
  832. if self.toolbars['map'].GetAction() == 'displayAttrb': # select previous action
  833. self.toolbars['map'].SelectDefault(event)
  834. return
  835. self.toolbars['map'].action['desc'] = 'displayAttrb'
  836. # switch GIS Manager to output console to show query results
  837. self.gismanager.notebook.SetSelection(1)
  838. self.MapWindow.mouse['use'] = "query"
  839. self.MapWindow.mouse['box'] = "point"
  840. self.MapWindow.zoomtype = 0
  841. # change the cursor
  842. self.MapWindow.SetCursor(self.cursors["cross"])
  843. def OnQueryModify(self, event):
  844. """
  845. Query vector map layer (edit mode)
  846. """
  847. if self.toolbars['map'].GetAction() == 'modifyAttrb': # select previous action
  848. self.toolbars['map'].SelectDefault(event)
  849. return
  850. self.toolbars['map'].action['desc'] = 'modifyAttrb'
  851. self.MapWindow.mouse['use'] = "queryVector"
  852. self.MapWindow.mouse['box'] = "point"
  853. self.MapWindow.pen = wx.Pen(colour='Red', width=2, style=wx.SHORT_DASH)
  854. self.MapWindow.zoomtype = 0
  855. # change the cursor
  856. self.MapWindow.SetCursor(self.cursors["cross"])
  857. def QueryMap(self, x, y):
  858. """
  859. Query map layer features
  860. Currently only raster and vector map layers are supported
  861. """
  862. #set query snap distance for v.what at mapunit equivalent of 10 pixels
  863. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / self.Map.width)
  864. east, north = self.MapWindow.Pixel2Cell((x, y))
  865. if not self.tree.layer_selected:
  866. dlg = wx.MessageDialog(parent=self,
  867. message=_('No map layer selected for querying.'),
  868. caption=_('Message'),
  869. style=wx.OK | wx.ICON_INFORMATION)
  870. dlg.ShowModal()
  871. dlg.Destroy()
  872. return
  873. mapname = None
  874. raststr = ''
  875. vectstr = ''
  876. rcmd = []
  877. vcmd = []
  878. for layer in self.tree.GetSelections():
  879. type = self.tree.GetPyData(layer)[0]['maplayer'].type
  880. dcmd = self.tree.GetPyData(layer)[0]['cmd']
  881. name = utils.GetLayerNameFromCmd(dcmd)
  882. if name == '':
  883. continue
  884. if type in ('raster', 'rgb', 'his'):
  885. raststr += "%s," % name
  886. elif type in ('vector', 'thememap', 'themechart'):
  887. vectstr += "%s," % name
  888. # use display region settings instead of computation region settings
  889. tmpreg = os.getenv("GRASS_REGION")
  890. os.environ["GRASS_REGION"] = self.Map.SetRegion(windres=False)
  891. # build query commands for any selected rasters and vectors
  892. if raststr != '':
  893. rcmd = ['r.what', '--q',
  894. '-f',
  895. 'input=%s' % raststr.rstrip(','),
  896. 'east_north=%f,%f' % (float(east), float(north))]
  897. if vectstr != '':
  898. # check for vector maps open to be edited
  899. digitToolbar = self.toolbars['vdigit']
  900. if digitToolbar:
  901. map = digitToolbar.GetLayer().GetName()
  902. vect = []
  903. for vector in vectstr.split(','):
  904. if map == vector:
  905. self.gismanager.goutput.WriteWarning("Vector map <%s> "
  906. "opened for editing - skipped." % map)
  907. continue
  908. vect.append(vector)
  909. vectstr = ','.join(vect)
  910. if len(vectstr) <= 1:
  911. self.gismanager.goutput.WriteCmdLog("Nothing to query.")
  912. return
  913. vcmd = ['v.what', '--q',
  914. '-a',
  915. 'map=%s' % vectstr.rstrip(','),
  916. 'east_north=%f,%f' % (float(east), float(north)),
  917. 'distance=%f' % qdist]
  918. # parse query command(s)
  919. if self.gismanager:
  920. if rcmd:
  921. self.gismanager.goutput.RunCmd(rcmd, compReg=False)
  922. if vcmd:
  923. self.gismanager.goutput.RunCmd(vcmd)
  924. else:
  925. if rcmd:
  926. gcmd.Command(rcmd) # TODO: -> grass.run_command
  927. if vcmd:
  928. gcmd.Command(vcmd) # TODO: -> grass.run_command
  929. # restore GRASS_REGION
  930. if tmpreg:
  931. os.environ["GRASS_REGION"] = tmpreg
  932. def QueryVector(self, x, y):
  933. """
  934. Query vector map layer features
  935. Attribute data of selected vector object are displayed in GUI dialog.
  936. Data can be modified (On Submit)
  937. """
  938. if not self.tree.layer_selected or \
  939. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] != 'vector':
  940. wx.MessageBox(parent=self,
  941. message=_("No vector map selected for querying."),
  942. caption=_("Message"),
  943. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  944. return
  945. posWindow = self.ClientToScreen((x + self.MapWindow.dialogOffset,
  946. y + self.MapWindow.dialogOffset))
  947. qdist = 10.0 * ((self.Map.region['e'] - self.Map.region['w']) / \
  948. self.Map.width)
  949. east, north = self.MapWindow.Pixel2Cell((x, y))
  950. mapName = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name
  951. if self.dialogs['attributes'] is None:
  952. self.dialogs['attributes'] = dbm.DisplayAttributesDialog(parent=self.MapWindow,
  953. map=mapName,
  954. query=((east, north), qdist),
  955. pos=posWindow,
  956. action="update")
  957. else:
  958. # selection changed?
  959. if not self.dialogs['attributes'].mapDBInfo or \
  960. self.dialogs['attributes'].mapDBInfo.map != mapName:
  961. self.dialogs['attributes'].UpdateDialog(map=mapName, query=((east, north), qdist))
  962. else:
  963. self.dialogs['attributes'].UpdateDialog(query=((east, north), qdist))
  964. cats = self.dialogs['attributes'].GetCats()
  965. try:
  966. qlayer = self.Map.GetListOfLayers(l_name=globalvar.QUERYLAYER)[0]
  967. except IndexError:
  968. qlayer = None
  969. if self.dialogs['attributes'].mapDBInfo and cats:
  970. # highlight feature & re-draw map
  971. if qlayer:
  972. qlayer.SetCmd(self.AddTmpVectorMapLayer(mapName, cats,
  973. useId=False,
  974. addLayer=False))
  975. else:
  976. qlayer = self.AddTmpVectorMapLayer(mapName, cats, useId=False)
  977. # set opacity based on queried layer
  978. opacity = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].GetOpacity(float=True)
  979. qlayer.SetOpacity(opacity)
  980. self.MapWindow.UpdateMap(render=False, renderVector=False)
  981. if not self.dialogs['attributes'].IsShown():
  982. self.dialogs['attributes'].Show()
  983. else:
  984. if qlayer:
  985. self.Map.DeleteLayer(qlayer)
  986. self.MapWindow.UpdateMap(render=False, renderVector=False)
  987. if self.dialogs['attributes'].IsShown():
  988. self.dialogs['attributes'].Hide()
  989. def OnQuery(self, event):
  990. """Query tools menu"""
  991. if self.toolbars['map']:
  992. self.toolbars['map'].OnTool(event)
  993. action = self.toolbars['map'].GetAction()
  994. point = wx.GetMousePosition()
  995. toolsmenu = wx.Menu()
  996. # Add items to the menu
  997. display = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  998. text=_("Query raster/vector map(s) (display mode)"),
  999. kind=wx.ITEM_CHECK)
  1000. toolsmenu.AppendItem(display)
  1001. self.Bind(wx.EVT_MENU, self.OnQueryDisplay, display)
  1002. if action == "displayAttrb":
  1003. display.Check(True)
  1004. modify = wx.MenuItem(parentMenu=toolsmenu, id=wx.ID_ANY,
  1005. text=_("Query vector map (edit mode)"),
  1006. kind=wx.ITEM_CHECK)
  1007. toolsmenu.AppendItem(modify)
  1008. self.Bind(wx.EVT_MENU, self.OnQueryModify, modify)
  1009. digitToolbar = self.toolbars['vdigit']
  1010. if self.tree.layer_selected:
  1011. layer_selected = self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer']
  1012. if digitToolbar and \
  1013. digitToolbar.GetLayer() == layer_selected:
  1014. modify.Enable(False)
  1015. else:
  1016. if action == "modifyAttrb":
  1017. modify.Check(True)
  1018. self.PopupMenu(toolsmenu)
  1019. toolsmenu.Destroy()
  1020. def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True):
  1021. """
  1022. Add temporal vector map layer to map composition
  1023. @param name name of map layer
  1024. @param useId use feature id instead of category
  1025. """
  1026. # color settings from ATM
  1027. color = UserSettings.Get(group='atm', key='highlight', subkey='color')
  1028. colorStr = str(color[0]) + ":" + \
  1029. str(color[1]) + ":" + \
  1030. str(color[2])
  1031. pattern = ["d.vect",
  1032. "map=%s" % name,
  1033. "color=%s" % colorStr,
  1034. "fcolor=%s" % colorStr,
  1035. "width=%d" % UserSettings.Get(group='atm', key='highlight', subkey='width')]
  1036. if useId:
  1037. cmd = pattern
  1038. cmd.append('-i')
  1039. cmd.append('cats=%s' % str(cats))
  1040. else:
  1041. cmd = []
  1042. for layer in cats.keys():
  1043. cmd.append(copy.copy(pattern))
  1044. lcats = cats[layer]
  1045. cmd[-1].append("layer=%d" % layer)
  1046. cmd[-1].append("cats=%s" % utils.ListOfCatsToRange(lcats))
  1047. # if self.icon:
  1048. # cmd.append("icon=%s" % (self.icon))
  1049. # if self.pointsize:
  1050. # cmd.append("size=%s" % (self.pointsize))
  1051. if addLayer:
  1052. if useId:
  1053. return self.Map.AddLayer(type='vector', name=globalvar.QUERYLAYER, command=cmd,
  1054. l_active=True, l_hidden=True, l_opacity=1.0)
  1055. else:
  1056. return self.Map.AddLayer(type='command', name=globalvar.QUERYLAYER, command=cmd,
  1057. l_active=True, l_hidden=True, l_opacity=1.0)
  1058. else:
  1059. return cmd
  1060. def OnAnalyze(self, event):
  1061. """
  1062. Analysis tools menu
  1063. """
  1064. point = wx.GetMousePosition()
  1065. toolsmenu = wx.Menu()
  1066. # Add items to the menu
  1067. measure = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["measure"].GetLabel())
  1068. measure.SetBitmap(Icons["measure"].GetBitmap(self.iconsize))
  1069. toolsmenu.AppendItem(measure)
  1070. self.Bind(wx.EVT_MENU, self.OnMeasure, measure)
  1071. profile = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["profile"].GetLabel())
  1072. profile.SetBitmap(Icons["profile"].GetBitmap(self.iconsize))
  1073. toolsmenu.AppendItem(profile)
  1074. self.Bind(wx.EVT_MENU, self.Profile, profile)
  1075. histogram = wx.MenuItem(toolsmenu, wx.ID_ANY, Icons["histogram"].GetLabel())
  1076. histogram.SetBitmap(Icons["histogram"].GetBitmap(self.iconsize))
  1077. toolsmenu.AppendItem(histogram)
  1078. self.Bind(wx.EVT_MENU, self.Histogram, histogram)
  1079. # Popup the menu. If an item is selected then its handler
  1080. # will be called before PopupMenu returns.
  1081. self.PopupMenu(toolsmenu)
  1082. toolsmenu.Destroy()
  1083. def OnMeasure(self, event):
  1084. """
  1085. Init measurement routine that calculates
  1086. map distance along transect drawn on
  1087. map display
  1088. """
  1089. self.totaldist = 0.0 # total measured distance
  1090. # switch GIS Manager to output console to show measure results
  1091. self.gismanager.notebook.SetSelection(1)
  1092. # change mouse to draw line for measurement
  1093. self.MapWindow.mouse['use'] = "measure"
  1094. self.MapWindow.mouse['box'] = "line"
  1095. self.MapWindow.zoomtype = 0
  1096. self.MapWindow.pen = wx.Pen(colour='red', width=2, style=wx.SHORT_DASH)
  1097. self.MapWindow.polypen = wx.Pen(colour='green', width=2, style=wx.SHORT_DASH)
  1098. # change the cursor
  1099. self.MapWindow.SetCursor(self.cursors["pencil"])
  1100. # initiating output
  1101. style = self.gismanager.goutput.cmd_output.StyleWarning
  1102. self.gismanager.goutput.WriteLog(_('Click and drag with left mouse button '
  1103. 'to measure.%s'
  1104. 'Double click with left button to clear.') % \
  1105. (os.linesep), style)
  1106. if self.Map.projinfo['proj'] != 'xy':
  1107. units = self.Map.projinfo['units']
  1108. style = self.gismanager.goutput.cmd_output.StyleCommand
  1109. self.gismanager.goutput.WriteLog(_('Measuring distance') + ' ('
  1110. + units + '):',
  1111. style)
  1112. else:
  1113. self.gismanager.goutput.WriteLog(_('Measuring distance:'),
  1114. style)
  1115. def MeasureDist(self, beginpt, endpt):
  1116. """
  1117. Calculate map distance from screen distance
  1118. and print to output window
  1119. """
  1120. if self.gismanager.notebook.GetSelection() != 1:
  1121. self.gismanager.notebook.SetSelection(1)
  1122. dist, (north, east) = self.MapWindow.Distance(beginpt, endpt)
  1123. dist = round(dist, 3)
  1124. d, dunits = self.FormatDist(dist)
  1125. self.totaldist += dist
  1126. td, tdunits = self.FormatDist(self.totaldist)
  1127. strdist = str(d)
  1128. strtotdist = str(td)
  1129. if self.Map.projinfo['proj'] == 'xy' or 'degree' not in self.Map.projinfo['unit']:
  1130. angle = int(math.degrees(math.atan2(north,east)) + 0.5)
  1131. angle = angle+90
  1132. if angle < 0: angle = 360+angle
  1133. mstring = 'segment = %s %s\ttotal distance = %s %s\tbearing = %d deg' \
  1134. % (strdist,dunits,strtotdist,tdunits,angle)
  1135. else:
  1136. mstring = 'segment = %s %s\ttotal distance = %s %s' \
  1137. % (strdist,dunits,strtotdist,tdunits)
  1138. self.gismanager.goutput.WriteLog(mstring)
  1139. return dist
  1140. def Profile(self, event):
  1141. """
  1142. Init profile canvas and tools
  1143. """
  1144. raster = []
  1145. if self.tree.layer_selected and \
  1146. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1147. raster.append(self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1148. self.profile = profile.ProfileFrame(self,
  1149. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(700,300),
  1150. style=wx.DEFAULT_FRAME_STYLE, rasterList=raster)
  1151. self.profile.Show()
  1152. # Open raster select dialog to make sure that a raster (and the desired raster)
  1153. # is selected to be profiled
  1154. self.profile.OnSelectRaster(None)
  1155. def FormatDist(self, dist):
  1156. """Format length numbers and units in a nice way,
  1157. as a function of length. From code by Hamish Bowman
  1158. Grass Development Team 2006"""
  1159. mapunits = self.Map.projinfo['units']
  1160. if mapunits == 'metres': mapunits = 'meters'
  1161. outunits = mapunits
  1162. dist = float(dist)
  1163. divisor = 1.0
  1164. # figure out which units to use
  1165. if mapunits == 'meters':
  1166. if dist > 2500.0:
  1167. outunits = 'km'
  1168. divisor = 1000.0
  1169. else: outunits = 'm'
  1170. elif mapunits == 'feet':
  1171. # nano-bug: we match any "feet", but US Survey feet is really
  1172. # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
  1173. # miles the tick markers are rounded to the nearest 10th of a
  1174. # mile (528'), the difference in foot flavours is ignored.
  1175. if dist > 5280.0:
  1176. outunits = 'miles'
  1177. divisor = 5280.0
  1178. else:
  1179. outunits = 'ft'
  1180. elif 'degree' in mapunits:
  1181. if dist < 1:
  1182. outunits = 'min'
  1183. divisor = (1/60.0)
  1184. else:
  1185. outunits = 'deg'
  1186. # format numbers in a nice way
  1187. if (dist/divisor) >= 2500.0:
  1188. outdist = round(dist/divisor)
  1189. elif (dist/divisor) >= 1000.0:
  1190. outdist = round(dist/divisor,1)
  1191. elif (dist/divisor) > 0.0:
  1192. outdist = round(dist/divisor,int(math.ceil(3-math.log10(dist/divisor))))
  1193. else:
  1194. outdist = float(dist/divisor)
  1195. return (outdist, outunits)
  1196. def Histogram(self, event):
  1197. """
  1198. Init histogram display canvas and tools
  1199. """
  1200. self.histogram = histogram.HistFrame(self,
  1201. id=wx.ID_ANY, size=globalvar.HIST_WINDOW_SIZE,
  1202. style=wx.DEFAULT_FRAME_STYLE)
  1203. #show new display
  1204. self.histogram.Show()
  1205. self.histogram.Refresh()
  1206. self.histogram.Update()
  1207. def OnDecoration(self, event):
  1208. """
  1209. Decorations overlay menu
  1210. """
  1211. point = wx.GetMousePosition()
  1212. decmenu = wx.Menu()
  1213. # Add items to the menu
  1214. AddScale = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addbarscale"].GetLabel())
  1215. AddScale.SetBitmap(Icons["addbarscale"].GetBitmap(self.iconsize))
  1216. decmenu.AppendItem(AddScale)
  1217. self.Bind(wx.EVT_MENU, self.OnAddBarscale, AddScale)
  1218. AddLegend = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addlegend"].GetLabel())
  1219. AddLegend.SetBitmap(Icons["addlegend"].GetBitmap(self.iconsize))
  1220. decmenu.AppendItem(AddLegend)
  1221. self.Bind(wx.EVT_MENU, self.OnAddLegend, AddLegend)
  1222. AddText = wx.MenuItem(decmenu, wx.ID_ANY, Icons["addtext"].GetLabel())
  1223. AddText.SetBitmap(Icons["addtext"].GetBitmap(self.iconsize))
  1224. decmenu.AppendItem(AddText)
  1225. self.Bind(wx.EVT_MENU, self.OnAddText, AddText)
  1226. # Popup the menu. If an item is selected then its handler
  1227. # will be called before PopupMenu returns.
  1228. self.PopupMenu(decmenu)
  1229. decmenu.Destroy()
  1230. def OnAddBarscale(self, event):
  1231. """
  1232. Handler for scale/arrow map decoration menu selection.
  1233. """
  1234. if self.dialogs['barscale']:
  1235. return
  1236. id = 0 # unique index for overlay layer
  1237. # If location is latlon, only display north arrow (scale won't work)
  1238. # proj = self.Map.projinfo['proj']
  1239. # if proj == 'll':
  1240. # barcmd = 'd.barscale -n'
  1241. # else:
  1242. # barcmd = 'd.barscale'
  1243. # decoration overlay control dialog
  1244. self.dialogs['barscale'] = \
  1245. gdialogs.DecorationDialog(parent=self, title=_('Scale and North arrow'),
  1246. size=(350, 200),
  1247. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1248. cmd=['d.barscale', 'at=0,5'],
  1249. ovlId=id,
  1250. name='barscale',
  1251. checktxt = _("Show/hide scale and North arrow"),
  1252. ctrltxt = _("scale object"))
  1253. self.dialogs['barscale'].CentreOnParent()
  1254. ### dialog cannot be show as modal - in the result d.barscale is not selectable
  1255. ### self.dialogs['barscale'].ShowModal()
  1256. self.dialogs['barscale'].Show()
  1257. self.MapWindow.mouse['use'] = 'pointer'
  1258. def OnAddLegend(self, event):
  1259. """
  1260. Handler for legend map decoration menu selection.
  1261. """
  1262. if self.dialogs['legend']:
  1263. return
  1264. id = 1 # index for overlay layer in render
  1265. cmd = ['d.legend']
  1266. if self.tree.layer_selected and \
  1267. self.tree.GetPyData(self.tree.layer_selected)[0]['type'] == 'raster':
  1268. cmd.append('map=%s' % self.tree.GetPyData(self.tree.layer_selected)[0]['maplayer'].name)
  1269. # Decoration overlay control dialog
  1270. self.dialogs['legend'] = \
  1271. gdialogs.DecorationDialog(parent=self, title=('Legend'),
  1272. size=(350, 200),
  1273. style=wx.DEFAULT_DIALOG_STYLE | wx.CENTRE,
  1274. cmd=cmd,
  1275. ovlId=id,
  1276. name='legend',
  1277. checktxt = _("Show/hide legend"),
  1278. ctrltxt = _("legend object"))
  1279. self.dialogs['legend'].CentreOnParent()
  1280. ### dialog cannot be show as modal - in the result d.legend is not selectable
  1281. ### self.dialogs['legend'].ShowModal()
  1282. self.dialogs['legend'].Show()
  1283. self.MapWindow.mouse['use'] = 'pointer'
  1284. def OnAddText(self, event):
  1285. """
  1286. Handler for text decoration menu selection.
  1287. """
  1288. if self.MapWindow.dragid > -1:
  1289. id = self.MapWindow.dragid
  1290. else:
  1291. # index for overlay layer in render
  1292. if len(self.MapWindow.textdict.keys()) > 0:
  1293. id = self.MapWindow.textdict.keys()[-1] + 1
  1294. else:
  1295. id = 101
  1296. self.dialogs['text'] = gdialogs.TextLayerDialog(parent=self, ovlId=id,
  1297. title=_('Add text layer'),
  1298. size=(400, 200))
  1299. self.dialogs['text'].CenterOnParent()
  1300. # If OK button pressed in decoration control dialog
  1301. if self.dialogs['text'].ShowModal() == wx.ID_OK:
  1302. text = self.dialogs['text'].GetValues()['text']
  1303. active = self.dialogs['text'].GetValues()['active']
  1304. coords, w, h = self.MapWindow.TextBounds(self.dialogs['text'].GetValues())
  1305. # delete object if it has no text or is not active
  1306. if text == '' or active == False:
  1307. try:
  1308. self.MapWindow.pdc.ClearId(id)
  1309. self.MapWindow.pdc.RemoveId(id)
  1310. del self.MapWindow.textdict[id]
  1311. except:
  1312. pass
  1313. return
  1314. self.MapWindow.pdc.ClearId(id)
  1315. self.MapWindow.pdc.SetId(id)
  1316. self.MapWindow.textdict[id] = self.dialogs['text'].GetValues()
  1317. self.MapWindow.Draw(self.MapWindow.pdcDec, img=self.MapWindow.textdict[id],
  1318. drawid=id, pdctype='text', coords=coords)
  1319. self.MapWindow.UpdateMap(render=False, renderVector=False)
  1320. self.MapWindow.mouse['use'] = 'pointer'
  1321. def GetOptData(self, dcmd, type, params, propwin):
  1322. """
  1323. Callback method for decoration overlay command generated by
  1324. dialog created in menuform.py
  1325. """
  1326. # Reset comand and rendering options in render.Map. Always render decoration.
  1327. # Showing/hiding handled by PseudoDC
  1328. self.Map.ChangeOverlay(ovltype=type, type='overlay', name='', command=dcmd,
  1329. l_active=True, l_render=False)
  1330. self.params[type] = params
  1331. self.propwin[type] = propwin
  1332. def OnZoomMenu(self, event):
  1333. """
  1334. Zoom menu
  1335. """
  1336. point = wx.GetMousePosition()
  1337. zoommenu = wx.Menu()
  1338. # Add items to the menu
  1339. zoommap = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to selected map'))
  1340. zoommenu.AppendItem(zoommap)
  1341. self.Bind(wx.EVT_MENU, self.MapWindow.OnZoomToMap, zoommap)
  1342. zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
  1343. zoommenu.AppendItem(zoomwind)
  1344. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToWind, zoomwind)
  1345. zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
  1346. zoommenu.AppendItem(zoomdefault)
  1347. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToDefault, zoomdefault)
  1348. zoomsaved = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to saved region'))
  1349. zoommenu.AppendItem(zoomsaved)
  1350. self.Bind(wx.EVT_MENU, self.MapWindow.ZoomToSaved, zoomsaved)
  1351. savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
  1352. zoommenu.AppendItem(savewind)
  1353. self.Bind(wx.EVT_MENU, self.MapWindow.DisplayToWind, savewind)
  1354. savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
  1355. zoommenu.AppendItem(savezoom)
  1356. self.Bind(wx.EVT_MENU, self.MapWindow.SaveDisplayRegion, savezoom)
  1357. # Popup the menu. If an item is selected then its handler
  1358. # will be called before PopupMenu returns.
  1359. self.PopupMenu(zoommenu)
  1360. zoommenu.Destroy()
  1361. def SetProperties(self, render=False, mode=0, showCompExtent=False,
  1362. constrainRes=False):
  1363. """Set properies of map display window"""
  1364. self.autoRender.SetValue(render)
  1365. self.toggleStatus.SetSelection(mode)
  1366. self.StatusbarUpdate()
  1367. self.showRegion.SetValue(showCompExtent)
  1368. self.compResolution.SetValue(constrainRes)
  1369. if showCompExtent:
  1370. self.MapWindow.regionCoords = []
  1371. # end of class MapFrame
  1372. class MapApp(wx.App):
  1373. """
  1374. MapApp class
  1375. """
  1376. def OnInit(self):
  1377. wx.InitAllImageHandlers()
  1378. if __name__ == "__main__":
  1379. Map = render.Map() # instance of Map class to render GRASS display output to PPM file
  1380. else:
  1381. Map = None
  1382. self.mapFrm = MapFrame(parent=None, id=wx.ID_ANY, Map=Map, size=(640,480))
  1383. #self.SetTopWindow(Map)
  1384. self.mapFrm.Show()
  1385. if __name__ == "__main__":
  1386. # redraw map, if new command appears
  1387. self.redraw = False
  1388. status = Command(self, Map)
  1389. status.start()
  1390. self.timer = wx.PyTimer(self.watcher)
  1391. # check each 0.1s
  1392. self.timer.Start(100)
  1393. return 1
  1394. def OnExit(self):
  1395. if __name__ == "__main__":
  1396. # stop the timer
  1397. self.timer.Stop()
  1398. # terminate thread (a bit ugly)
  1399. os.system("""echo "quit" >> %s""" % (cmdfilename))
  1400. def watcher(self):
  1401. """Redraw, if new layer appears"""
  1402. if self.redraw:
  1403. self.mapFrm.OnDraw(None)
  1404. self.redraw = False
  1405. return
  1406. # end of class MapApp
  1407. if __name__ == "__main__":
  1408. ###### SET command variable
  1409. if len(sys.argv) != 3:
  1410. print __doc__
  1411. sys.exit()
  1412. title = sys.argv[1]
  1413. cmdfilename = sys.argv[2]
  1414. import gettext
  1415. gettext.install("gm_map") # replace with the appropriate catalog name
  1416. print "Starting monitor <%s>" % (title)
  1417. gm_map = MapApp(0)
  1418. # set title
  1419. gm_map.mapFrm.SetTitle ("GRASS GIS - Map Display: " + title + " - Location: " + \
  1420. grass.gisenv()['LOCATION_NAME'])
  1421. gm_map.MainLoop()
  1422. os.remove(cmdfilename)
  1423. os.system("""g.gisenv set="GRASS_PYCMDFILE" """)
  1424. print "Stoping monitor <%s>" % (title)
  1425. sys.exit()