mapdisp.py 63 KB

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