wxgui.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. """!
  2. @package wxgui.py
  3. @brief Main Python app for GRASS wxPython GUI. Main menu, layer management
  4. toolbar, notebook control for display management and access to
  5. command console.
  6. Classes:
  7. - GMFrame
  8. - GMApp
  9. (C) 2006-2009 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Jachym Cepicky (Mendel University of Agriculture)
  15. @author Martin Landa <landa.martin gmail.com>
  16. """
  17. import sys
  18. import os
  19. import time
  20. import traceback
  21. import re
  22. import string
  23. import getopt
  24. import platform
  25. import signal
  26. ### XML
  27. try:
  28. import xml.etree.ElementTree as etree
  29. except ImportError:
  30. import elementtree.ElementTree as etree # Python <= 2.4
  31. ### i18N
  32. import gettext
  33. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  34. import gui_modules
  35. gmpath = gui_modules.__path__[0]
  36. sys.path.append(gmpath)
  37. import images
  38. imagepath = images.__path__[0]
  39. sys.path.append(imagepath)
  40. import icons
  41. gmpath = icons.__path__[0]
  42. sys.path.append(gmpath)
  43. import gui_modules.globalvar as globalvar
  44. if not os.getenv("GRASS_WXBUNDLED"):
  45. globalvar.CheckForWx()
  46. import wx
  47. import wx.aui
  48. import wx.combo
  49. import wx.html
  50. import wx.stc
  51. import wx.lib.customtreectrl as CT
  52. import wx.lib.flatnotebook as FN
  53. grassPath = os.path.join(globalvar.ETCDIR, "python")
  54. sys.path.append(grassPath)
  55. from grass.script import core as grass
  56. import gui_modules.utils as utils
  57. import gui_modules.preferences as preferences
  58. import gui_modules.wxgui_utils as wxgui_utils
  59. import gui_modules.mapdisp as mapdisp
  60. import gui_modules.menudata as menudata
  61. import gui_modules.menuform as menuform
  62. import gui_modules.histogram as histogram
  63. import gui_modules.profile as profile
  64. import gui_modules.rules as rules
  65. import gui_modules.mcalc_builder as mapcalculator
  66. import gui_modules.gcmd as gcmd
  67. import gui_modules.georect as georect
  68. import gui_modules.dbm as dbm
  69. import gui_modules.workspace as workspace
  70. import gui_modules.goutput as goutput
  71. import gui_modules.gdialogs as gdialogs
  72. import gui_modules.colorrules as colorrules
  73. import gui_modules.ogc_services as ogc_services
  74. import gui_modules.prompt as prompt
  75. from gui_modules.debug import Debug
  76. from gui_modules.help import MenuTreeWindow
  77. from gui_modules.help import AboutWindow
  78. from icons.icon import Icons
  79. UserSettings = preferences.globalSettings
  80. class GMFrame(wx.Frame):
  81. """!
  82. GIS Manager frame with notebook widget for controlling
  83. GRASS GIS. Includes command console page for typing GRASS
  84. (and other) commands, tree widget page for managing map layers.
  85. """
  86. def __init__(self, parent, id=wx.ID_ANY, title=_("GRASS GIS Layer Manager"),
  87. workspace=None):
  88. self.parent = parent
  89. self.baseTitle = title
  90. self.iconsize = (16, 16)
  91. wx.Frame.__init__(self, parent=parent, id=id, size=(550, 450),
  92. style=wx.DEFAULT_FRAME_STYLE)
  93. self.SetTitle(self.baseTitle)
  94. self.SetName("LayerManager")
  95. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  96. self._auimgr = wx.aui.AuiManager(self)
  97. # initialize variables
  98. self.disp_idx = 0 # index value for map displays and layer trees
  99. self.curr_page = '' # currently selected page for layer tree notebook
  100. self.curr_pagenum = '' # currently selected page number for layer tree notebook
  101. self.workspaceFile = workspace # workspace file
  102. self.menucmd = dict() # menuId / cmd
  103. self.georectifying = None # reference to GCP class or None
  104. # list of open dialogs
  105. self.dialogs = dict()
  106. self.dialogs['preferences'] = None
  107. self.dialogs['atm'] = list()
  108. # creating widgets
  109. # -> self.notebook, self.goutput, self.outpage
  110. self.menubar, self.menudata = self.__createMenuBar()
  111. self.statusbar = self.CreateStatusBar(number=1)
  112. self.notebook = self.__createNoteBook()
  113. self.toolbar = self.__createToolBar()
  114. # bindings
  115. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  116. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  117. # minimal frame size
  118. self.SetMinSize((500, 400))
  119. # AUI stuff
  120. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  121. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  122. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  123. self._auimgr.Update()
  124. wx.CallAfter(self.notebook.SetSelection, 0)
  125. wx.CallAfter(self.goutput.cmd_prompt.SetFocus)
  126. # use default window layout ?
  127. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  128. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  129. try:
  130. x, y = map(int, dim.split(',')[0:2])
  131. w, h = map(int, dim.split(',')[2:4])
  132. self.SetPosition((x, y))
  133. self.SetSize((w, h))
  134. except:
  135. pass
  136. self.Show()
  137. # load workspace file if requested
  138. if (self.workspaceFile):
  139. # load given workspace file
  140. if self.LoadWorkspaceFile(self.workspaceFile):
  141. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  142. else:
  143. self.workspaceFile = None
  144. else:
  145. # start default initial display
  146. self.NewDisplay(show=False)
  147. # show map display widnow
  148. # -> OnSize() -> UpdateMap()
  149. if self.curr_page and not self.curr_page.maptree.mapdisplay.IsShown():
  150. self.curr_page.maptree.mapdisplay.Show()
  151. # redirect stderr to log area
  152. self.goutput.Redirect()
  153. # fix goutput's pane size
  154. self.goutput.SetSashPosition(int(self.GetSize()[1] * .45))
  155. # start with layer manager on top
  156. self.curr_page.maptree.mapdisplay.Raise()
  157. self.Raise()
  158. def __createMenuBar(self):
  159. """!Creates menubar"""
  160. self.menubar = wx.MenuBar()
  161. self.menudata = menudata.Data()
  162. for eachMenuData in self.menudata.GetMenu():
  163. for eachHeading in eachMenuData:
  164. menuLabel = eachHeading[0]
  165. menuItems = eachHeading[1]
  166. self.menubar.Append(self.__createMenu(menuItems), menuLabel)
  167. self.SetMenuBar(self.menubar)
  168. return (self.menubar, self.menudata)
  169. def __createMenu(self, menuData):
  170. """!Creates menu"""
  171. menu = wx.Menu()
  172. for eachItem in menuData:
  173. if len(eachItem) == 2:
  174. label = eachItem[0]
  175. subMenu = self.__createMenu(eachItem[1])
  176. menu.AppendMenu(wx.ID_ANY, label, subMenu)
  177. else:
  178. self.__createMenuItem(menu, *eachItem)
  179. self.Bind(wx.EVT_MENU_HIGHLIGHT_ALL, self.OnMenuHighlight)
  180. return menu
  181. def __createMenuItem(self, menu, label, help, handler, gcmd, keywords, shortcut = '', kind = wx.ITEM_NORMAL):
  182. """!Creates menu items"""
  183. if not label:
  184. menu.AppendSeparator()
  185. return
  186. if len(gcmd) > 0:
  187. helpString = gcmd + ' -- ' + help
  188. else:
  189. helpString = help
  190. if shortcut:
  191. label += '\t' + shortcut
  192. menuItem = menu.Append(wx.ID_ANY, label, helpString, kind)
  193. self.menucmd[menuItem.GetId()] = gcmd
  194. if len(gcmd) > 0 and \
  195. gcmd.split()[0] not in globalvar.grassCmd['all']:
  196. menuItem.Enable (False)
  197. rhandler = eval(handler)
  198. self.Bind(wx.EVT_MENU, rhandler, menuItem)
  199. def __createNoteBook(self):
  200. """!Creates notebook widgets"""
  201. #create main notebook widget
  202. nbStyle = FN.FNB_FANCY_TABS | \
  203. FN.FNB_BOTTOM | \
  204. FN.FNB_NO_NAV_BUTTONS | \
  205. FN.FNB_NO_X_BUTTON
  206. self.notebook = FN.FlatNotebook(parent=self, id=wx.ID_ANY, style=nbStyle)
  207. #self.notebook = wx.aui.AuiNotebook(parent=self, id=wx.ID_ANY, style=wx.aui.AUI_NB_BOTTOM)
  208. #self.notebook.SetFont(wx.Font(pointSize=11, family=wx.FONTFAMILY_DEFAULT, style=wx.NORMAL, weight=0))
  209. # create displays notebook widget and add it to main notebook page
  210. cbStyle = globalvar.FNPageStyle
  211. self.gm_cb = FN.FlatNotebook(self, id=wx.ID_ANY, style=cbStyle)
  212. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  213. self.notebook.AddPage(self.gm_cb, text=_("Map layers for each display"))
  214. # create command output text area and add it to main notebook page
  215. self.goutput = goutput.GMConsole(self, pageid=1)
  216. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command console"))
  217. # bindings
  218. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  219. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  220. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  221. sizer = wx.BoxSizer(wx.VERTICAL)
  222. sizer.Add(item=self.goutput, proportion=1,
  223. flag=wx.EXPAND | wx.ALL, border=1)
  224. self.SetSizer(sizer)
  225. # self.out_sizer.Fit(self.outpage)
  226. self.Layout()
  227. self.Centre()
  228. return self.notebook
  229. def __createToolBar(self):
  230. """!Creates toolbar"""
  231. self.toolbar = self.CreateToolBar()
  232. self.toolbar.SetToolBitmapSize(globalvar.toolbarSize)
  233. for each in self.ToolbarData():
  234. self.AddToolbarButton(self.toolbar, *each)
  235. self.toolbar.Realize()
  236. return self.toolbar
  237. def OnMenuHighlight(self, event):
  238. """
  239. Default menu help handler
  240. """
  241. # Show how to get menu item info from this event handler
  242. id = event.GetMenuId()
  243. item = self.GetMenuBar().FindItemById(id)
  244. if item:
  245. text = item.GetText()
  246. help = item.GetHelp()
  247. # but in this case just call Skip so the default is done
  248. event.Skip()
  249. def OnGeorectify(self, event):
  250. """
  251. Launch georectifier module
  252. """
  253. georect.GeorectWizard(self)
  254. def OnMapsets(self, event):
  255. """
  256. Launch mapset access dialog
  257. """
  258. dlg = preferences.MapsetAccess(parent=self, id=wx.ID_ANY)
  259. dlg.CenterOnScreen()
  260. # if OK is pressed...
  261. if dlg.ShowModal() == wx.ID_OK:
  262. ms = dlg.GetMapsets()
  263. # run g.mapsets with string of accessible mapsets
  264. gcmd.RunCommand('g.mapsets',
  265. parent = self,
  266. mapset = '%s' % ','.join(ms))
  267. def OnRDigit(self, event):
  268. """
  269. Launch raster digitizing module
  270. """
  271. pass
  272. def OnCBPageChanged(self, event):
  273. """!Page in notebook (display) changed"""
  274. old_pgnum = event.GetOldSelection()
  275. new_pgnum = event.GetSelection()
  276. self.curr_page = self.gm_cb.GetCurrentPage()
  277. self.curr_pagenum = self.gm_cb.GetSelection()
  278. try:
  279. self.curr_page.maptree.mapdisplay.SetFocus()
  280. self.curr_page.maptree.mapdisplay.Raise()
  281. except:
  282. pass
  283. event.Skip()
  284. def OnPageChanged(self, event):
  285. """!Page in notebook changed"""
  286. page = event.GetSelection()
  287. if page == self.goutput.pageid:
  288. # remove '(...)'
  289. self.notebook.SetPageText(page, _("Command console"))
  290. event.Skip()
  291. def OnCBPageClosed(self, event):
  292. """
  293. Page of notebook closed
  294. Also close associated map display
  295. """
  296. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  297. maptree = self.curr_page.maptree
  298. if self.workspaceFile:
  299. message = _("Do you want to save changes in the workspace?")
  300. else:
  301. message = _("Do you want to store current settings "
  302. "to workspace file?")
  303. # ask user to save current settings
  304. if maptree.GetCount() > 0:
  305. dlg = wx.MessageDialog(self,
  306. message=message,
  307. caption=_("Close Map Display %d") % (self.curr_pagenum + 1),
  308. style=wx.YES_NO | wx.YES_DEFAULT |
  309. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  310. ret = dlg.ShowModal()
  311. if ret == wx.ID_YES:
  312. if not self.workspaceFile:
  313. self.OnWorkspaceSaveAs()
  314. else:
  315. self.SaveToWorkspaceFile(self.workspaceFile)
  316. elif ret == wx.ID_CANCEL:
  317. event.Veto()
  318. dlg.Destroy()
  319. return
  320. dlg.Destroy()
  321. self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
  322. self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
  323. self.curr_page = None
  324. event.Skip()
  325. def GetLogWindow(self):
  326. """!Get widget for command output"""
  327. return self.goutput
  328. def GetMenuCmd(self, event):
  329. """!Get GRASS command from menu item
  330. Return command as a list"""
  331. layer = None
  332. if event:
  333. cmd = self.menucmd[event.GetId()]
  334. try:
  335. cmdlist = cmd.split(' ')
  336. except: # already list?
  337. cmdlist = cmd
  338. # check list of dummy commands for GUI modules that do not have GRASS
  339. # bin modules or scripts.
  340. if cmd in ['vcolors']:
  341. return cmdlist
  342. try:
  343. layer = self.curr_page.maptree.layer_selected
  344. name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
  345. type = self.curr_page.maptree.GetPyData(layer)[0]['type']
  346. except:
  347. layer = None
  348. if layer and len(cmdlist) == 1: # only if no paramaters given
  349. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  350. (type == 'vector' and cmdlist[0][0] == 'v'):
  351. input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
  352. if input:
  353. cmdlist.append("%s=%s" % (input, name))
  354. return cmdlist
  355. def RunMenuCmd(self, event, cmd = ''):
  356. """!Run command selected from menu"""
  357. if event:
  358. cmd = self.GetMenuCmd(event)
  359. self.goutput.RunCmd(cmd, switchPage=False)
  360. def OnMenuCmd(self, event, cmd = ''):
  361. """!Parse command selected from menu"""
  362. if event:
  363. cmd = self.GetMenuCmd(event)
  364. menuform.GUI().ParseCommand(cmd, parentframe=self)
  365. def OnRunScript(self, event):
  366. """!Run script"""
  367. # open dialog and choose script file
  368. dlg = wx.FileDialog(parent = self, message = _("Choose script file"),
  369. defaultDir = os.getcwd(), wildcard = _("Bash script (*.sh)|*.sh|Python script (*.py)|*.py"))
  370. filename = None
  371. if dlg.ShowModal() == wx.ID_OK:
  372. filename = dlg.GetPath()
  373. if not filename:
  374. return False
  375. if not os.path.exists(filename):
  376. wx.MessageBox(parent = self,
  377. message = _("Script file '%s' doesn't exist. Operation cancelled.") % filename,
  378. caption = _("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  379. return
  380. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  381. self.goutput.RunCmd(filename, switchPage = True)
  382. def OnChangeLocation(self, event):
  383. """Change current location"""
  384. dlg = gdialogs.LocationDialog(parent = self)
  385. if dlg.ShowModal() == wx.ID_OK:
  386. location, mapset = dlg.GetValues()
  387. if location and mapset:
  388. ret = gcmd.RunCommand("g.gisenv",
  389. set = "LOCATION_NAME=%s" % location)
  390. ret += gcmd.RunCommand("g.gisenv",
  391. set = "MAPSET=%s" % mapset)
  392. if ret > 0:
  393. wx.MessageBox(parent = self,
  394. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  395. { 'loc' : location, 'mapset' : mapset },
  396. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  397. else:
  398. # close workspace
  399. self.OnWorkspaceClose()
  400. self.OnWorkspaceNew()
  401. wx.MessageBox(parent = self,
  402. message = _("Current location is <%(loc)s>.\n"
  403. "Current mapset is <%(mapset)s>.") % \
  404. { 'loc' : location, 'mapset' : mapset },
  405. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  406. def OnChangeMapset(self, event):
  407. """Change current mapset"""
  408. dlg = gdialogs.MapsetDialog(parent = self)
  409. if dlg.ShowModal() == wx.ID_OK:
  410. mapset = dlg.GetMapset()
  411. if mapset:
  412. if gcmd.RunCommand("g.gisenv",
  413. set = "MAPSET=%s" % mapset) != 0:
  414. wx.MessageBox(parent = self,
  415. message = _("Unable to switch to mapset <%s>.") % mapset,
  416. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  417. else:
  418. wx.MessageBox(parent = self,
  419. message = _("Current mapset is <%s>.") % mapset,
  420. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  421. def OnNewVector(self, event):
  422. """!Create new vector map layer"""
  423. name, add = gdialogs.CreateNewVector(self, log = self.goutput,
  424. cmd = (('v.edit',
  425. { 'tool' : 'create' },
  426. 'map')))
  427. if name and add:
  428. # add layer to map layer tree
  429. self.curr_page.maptree.AddLayer(ltype='vector',
  430. lname=name,
  431. lchecked=True,
  432. lopacity=1.0,
  433. lcmd=['d.vect', 'map=%s' % name])
  434. def OnMenuTree(self, event):
  435. """!Show dialog with menu tree"""
  436. dlg = MenuTreeWindow(self)
  437. dlg.CentreOnScreen()
  438. dlg.Show()
  439. def OnAboutGRASS(self, event):
  440. """!Display 'About GRASS' dialog"""
  441. win = AboutWindow(self)
  442. win.CentreOnScreen()
  443. win.Show(True)
  444. def OnWorkspace(self, event):
  445. """!Workspace menu (new, load)"""
  446. point = wx.GetMousePosition()
  447. menu = wx.Menu()
  448. # Add items to the menu
  449. new = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceNew"].GetLabel())
  450. new.SetBitmap(Icons["workspaceNew"].GetBitmap(self.iconsize))
  451. menu.AppendItem(new)
  452. self.Bind(wx.EVT_MENU, self.OnWorkspaceNew, new)
  453. load = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceLoad"].GetLabel())
  454. load.SetBitmap(Icons["workspaceLoad"].GetBitmap(self.iconsize))
  455. menu.AppendItem(load)
  456. self.Bind(wx.EVT_MENU, self.OnWorkspaceLoad, load)
  457. # create menu
  458. self.PopupMenu(menu)
  459. menu.Destroy()
  460. def OnWorkspaceNew(self, event=None):
  461. """!Create new workspace file
  462. Erase current workspace settings first"""
  463. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  464. # start new map display if no display is available
  465. if not self.curr_page:
  466. self.NewDisplay()
  467. maptree = self.curr_page.maptree
  468. # ask user to save current settings
  469. if maptree.GetCount() > 0:
  470. dlg = wx.MessageDialog(self, message=_("Current workspace is not empty. "
  471. "Do you want to store current settings "
  472. "to workspace file?"),
  473. caption=_("Create new workspace?"),
  474. style=wx.YES_NO | wx.YES_DEFAULT | \
  475. wx.CANCEL | wx.ICON_QUESTION)
  476. ret = dlg.ShowModal()
  477. if ret == wx.ID_YES:
  478. self.OnWorkspaceSaveAs()
  479. elif ret == wx.ID_CANCEL:
  480. dlg.Destroy()
  481. return
  482. dlg.Destroy()
  483. # delete all items
  484. maptree.DeleteAllItems()
  485. # add new root element
  486. maptree.root = maptree.AddRoot("Map Layers")
  487. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  488. # no workspace file loaded
  489. self.workspaceFile = None
  490. self.SetTitle(self.baseTitle)
  491. def OnWorkspaceOpen(self, event=None):
  492. """!Open file with workspace definition"""
  493. dlg = wx.FileDialog(parent=self, message=_("Choose workspace file"),
  494. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"))
  495. filename = ''
  496. if dlg.ShowModal() == wx.ID_OK:
  497. filename = dlg.GetPath()
  498. if filename == '':
  499. return
  500. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  501. # delete current layer tree content
  502. self.OnWorkspaceClose()
  503. self.LoadWorkspaceFile(filename)
  504. self.workspaceFile = filename
  505. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  506. def LoadWorkspaceFile(self, filename):
  507. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  508. @todo Validate against DTD
  509. @return True on success
  510. @return False on error
  511. """
  512. # dtd
  513. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  514. # parse workspace file
  515. try:
  516. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  517. except Exception, err:
  518. raise gcmd.GStdError(_("Reading workspace file <%(file)s> failed.\n"
  519. "Invalid file, unable to parse XML document."
  520. "\n\n%(err)s") % { 'file' : filename, 'err': err},
  521. parent = self)
  522. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  523. parent=self)
  524. wx.Yield()
  525. #
  526. # load layer manager window properties
  527. #
  528. if UserSettings.Get(group='workspace', key='posManager', subkey='enabled') is False:
  529. if gxwXml.layerManager['pos']:
  530. self.SetPosition(gxwXml.layerManager['pos'])
  531. if gxwXml.layerManager['size']:
  532. self.SetSize(gxwXml.layerManager['size'])
  533. #
  534. # start map displays first (list of layers can be empty)
  535. #
  536. displayId = 0
  537. mapdisplay = []
  538. for display in gxwXml.displays:
  539. mapdisplay.append(self.NewDisplay(show=False))
  540. maptree = self.gm_cb.GetPage(displayId).maptree
  541. # set windows properties
  542. mapdisplay[-1].SetProperties(render=display['render'],
  543. mode=display['mode'],
  544. showCompExtent=display['showCompExtent'],
  545. constrainRes=display['constrainRes'],
  546. projection=display['projection']['enabled'])
  547. if display['projection']['enabled']:
  548. if display['projection']['epsg']:
  549. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  550. value = display['projection']['epsg'])
  551. if display['projection']['proj']:
  552. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  553. value = display['projection']['proj'])
  554. # set position and size of map display
  555. if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
  556. if display['pos']:
  557. mapdisplay[-1].SetPosition(display['pos'])
  558. if display['size']:
  559. mapdisplay[-1].SetSize(display['size'])
  560. # set extent if defined
  561. if display['extent']:
  562. w, s, e, n = display['extent']
  563. maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
  564. mapdisplay[-1].Show()
  565. displayId += 1
  566. maptree = None
  567. selected = [] # list of selected layers
  568. #
  569. # load list of map layers
  570. #
  571. for layer in gxwXml.layers:
  572. display = layer['display']
  573. maptree = self.gm_cb.GetPage(display).maptree
  574. newItem = maptree.AddLayer(ltype=layer['type'],
  575. lname=layer['name'],
  576. lchecked=layer['checked'],
  577. lopacity=layer['opacity'],
  578. lcmd=layer['cmd'],
  579. lgroup=layer['group'],
  580. lnviz=layer['nviz'],
  581. lvdigit=layer['vdigit'])
  582. if layer.has_key('selected'):
  583. if layer['selected']:
  584. selected.append((maptree, newItem))
  585. else:
  586. maptree.SelectItem(newItem, select=False)
  587. for maptree, layer in selected:
  588. if not maptree.IsSelected(layer):
  589. maptree.SelectItem(layer, select=True)
  590. maptree.layer_selected = layer
  591. busy.Destroy()
  592. if maptree:
  593. # reverse list of map layers
  594. maptree.Map.ReverseListOfLayers()
  595. for mdisp in mapdisplay:
  596. mdisp.MapWindow2D.UpdateMap()
  597. return True
  598. def OnWorkspaceLoad(self, event=None):
  599. """!Load given map layers into layer tree"""
  600. dialog = gdialogs.LoadMapLayersDialog(parent=self, title=_("Load map layers into layer tree"))
  601. if dialog.ShowModal() == wx.ID_OK:
  602. # start new map display if no display is available
  603. if not self.curr_page:
  604. self.NewDisplay()
  605. maptree = self.curr_page.maptree
  606. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  607. parent=self)
  608. wx.Yield()
  609. for layerName in dialog.GetMapLayers():
  610. if dialog.GetLayerType() == 'raster':
  611. cmd = ['d.rast', 'map=%s' % layerName]
  612. elif dialog.GetLayerType() == 'vector':
  613. cmd = ['d.vect', 'map=%s' % layerName]
  614. newItem = maptree.AddLayer(ltype=dialog.GetLayerType(),
  615. lname=layerName,
  616. lchecked=True,
  617. lopacity=1.0,
  618. lcmd=cmd,
  619. lgroup=None)
  620. busy.Destroy()
  621. def OnWorkspaceLoadGrcFile(self, event):
  622. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  623. dlg = wx.FileDialog(parent=self, message=_("Choose GRC file to load"),
  624. defaultDir=os.getcwd(), wildcard=_("Old GRASS Workspace File (*.grc)|*.grc"))
  625. filename = ''
  626. if dlg.ShowModal() == wx.ID_OK:
  627. filename = dlg.GetPath()
  628. if filename == '':
  629. return
  630. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  631. # start new map display if no display is available
  632. if not self.curr_page:
  633. self.NewDisplay()
  634. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  635. parent=self)
  636. wx.Yield()
  637. maptree = None
  638. for layer in workspace.ProcessGrcFile(filename).read(self):
  639. maptree = self.gm_cb.GetPage(layer['display']).maptree
  640. newItem = maptree.AddLayer(ltype=layer['type'],
  641. lname=layer['name'],
  642. lchecked=layer['checked'],
  643. lopacity=layer['opacity'],
  644. lcmd=layer['cmd'],
  645. lgroup=layer['group'])
  646. busy.Destroy()
  647. if maptree:
  648. # reverse list of map layers
  649. maptree.Map.ReverseListOfLayers()
  650. def OnWorkspaceSaveAs(self, event=None):
  651. """!Save workspace definition to selected file"""
  652. dlg = wx.FileDialog(parent=self, message=_("Choose file to save current workspace"),
  653. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), style=wx.FD_SAVE)
  654. filename = ''
  655. if dlg.ShowModal() == wx.ID_OK:
  656. filename = dlg.GetPath()
  657. if filename == '':
  658. return False
  659. # check for extension
  660. if filename[-4:] != ".gxw":
  661. filename += ".gxw"
  662. if os.path.exists(filename):
  663. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  664. "Do you want to overwrite this file?") % filename,
  665. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  666. if dlg.ShowModal() != wx.ID_YES:
  667. dlg.Destroy()
  668. return False
  669. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  670. self.SaveToWorkspaceFile(filename)
  671. self.workspaceFile = filename
  672. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  673. def OnWorkspaceSave(self, event=None):
  674. """!Save file with workspace definition"""
  675. if self.workspaceFile:
  676. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  677. "Do you want to overwrite this file?") % \
  678. self.workspaceFile,
  679. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  680. if dlg.ShowModal() == wx.ID_NO:
  681. dlg.Destroy()
  682. else:
  683. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  684. self.SaveToWorkspaceFile(self.workspaceFile)
  685. else:
  686. self.OnWorkspaceSaveAs()
  687. def SaveToWorkspaceFile(self, filename):
  688. """!Save layer tree layout to workspace file
  689. Return True on success, False on error
  690. """
  691. try:
  692. file = open(filename, "w")
  693. except IOError:
  694. wx.MessageBox(parent=self,
  695. message=_("Unable to open workspace file <%s> for writing.") % filename,
  696. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  697. return False
  698. try:
  699. workspace.WriteWorkspaceFile(lmgr=self, file=file)
  700. except StandardError, e:
  701. file.close()
  702. wx.MessageBox(parent=self,
  703. message=_("Writing current settings to workspace file failed (%s)." % e),
  704. caption=_("Error"),
  705. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  706. return False
  707. file.close()
  708. return True
  709. def OnWorkspaceClose(self, event=None):
  710. """!Close file with workspace definition
  711. If workspace has been modified ask user to save the changes.
  712. """
  713. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  714. self.workspaceFile = None
  715. self.SetTitle(self.baseTitle)
  716. displays = []
  717. for page in range(0, self.gm_cb.GetPageCount()):
  718. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  719. for display in displays:
  720. display.OnCloseWindow(event)
  721. self.disp_idx = 0
  722. self.curr_page = None
  723. def RulesCmd(self, event, cmd = ''):
  724. """
  725. Launches dialog for commands that need rules
  726. input and processes rules
  727. """
  728. if event:
  729. cmd = self.GetMenuCmd(event)
  730. if cmd[0] == 'r.colors' or cmd[0] == 'vcolors':
  731. ctable = colorrules.ColorTable(self, cmd=cmd[0])
  732. ctable.Show()
  733. else:
  734. dlg = rules.RulesText(self, cmd=cmd)
  735. dlg.CenterOnScreen()
  736. if dlg.ShowModal() == wx.ID_OK:
  737. gtemp = utils.GetTempfile()
  738. output = open(gtemp, "w")
  739. try:
  740. output.write(dlg.rules)
  741. finally:
  742. output.close()
  743. cmdlist = [cmd[0],
  744. 'input=%s' % dlg.inmap,
  745. 'output=%s' % dlg.outmap,
  746. 'rules=%s' % gtemp]
  747. if dlg.overwrite == True:
  748. cmdlist.append('--o')
  749. dlg.Destroy()
  750. self.goutput.RunCmd(cmdlist)
  751. def OnPreferences(self, event):
  752. """!General GUI preferences/settings"""
  753. if not self.dialogs['preferences']:
  754. dlg = preferences.PreferencesDialog(parent=self)
  755. self.dialogs['preferences'] = dlg
  756. self.dialogs['preferences'].CenterOnScreen()
  757. self.dialogs['preferences'].ShowModal()
  758. def DispHistogram(self, event):
  759. """
  760. Init histogram display canvas and tools
  761. """
  762. self.histogram = histogram.HistFrame(self,
  763. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  764. style=wx.DEFAULT_FRAME_STYLE)
  765. #show new display
  766. self.histogram.Show()
  767. self.histogram.Refresh()
  768. self.histogram.Update()
  769. def DispProfile(self, event):
  770. """
  771. Init profile canvas and tools
  772. """
  773. self.profile = profile.ProfileFrame(self,
  774. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  775. style=wx.DEFAULT_FRAME_STYLE)
  776. self.profile.Show()
  777. self.profile.Refresh()
  778. self.profile.Update()
  779. def DispMapCalculator(self, event):
  780. """
  781. Init map calculator for interactive creation of mapcalc statements
  782. """
  783. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  784. dimension=2)
  785. def Disp3DMapCalculator(self, event):
  786. """
  787. Init map calculator for interactive creation of mapcalc statements
  788. """
  789. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  790. dimension=3)
  791. def AddToolbarButton(self, toolbar, label, icon, help, handler):
  792. """!Adds button to the given toolbar"""
  793. if not label:
  794. toolbar.AddSeparator()
  795. return
  796. tool = toolbar.AddLabelTool(id=wx.ID_ANY, label=label, bitmap=icon, shortHelp=help)
  797. self.Bind(wx.EVT_TOOL, handler, tool)
  798. def ToolbarData(self):
  799. return (
  800. ('newdisplay', Icons["newdisplay"].GetBitmap(),
  801. Icons["newdisplay"].GetLabel(), self.OnNewDisplay),
  802. ('', '', '', ''),
  803. ('workspaceLoad', Icons["workspaceLoad"].GetBitmap(),
  804. Icons["workspaceLoad"].GetLabel(), self.OnWorkspace),
  805. ('workspaceOpen', Icons["workspaceOpen"].GetBitmap(),
  806. Icons["workspaceOpen"].GetLabel(), self.OnWorkspaceOpen),
  807. ('workspaceSave', Icons["workspaceSave"].GetBitmap(),
  808. Icons["workspaceSave"].GetLabel(), self.OnWorkspaceSave),
  809. ('', '', '', ''),
  810. ('addrast', Icons["addrast"].GetBitmap(),
  811. Icons["addrast"].GetLabel(), self.OnAddRaster),
  812. ('addshaded', Icons["addshaded"].GetBitmap(),
  813. _("Add various raster-based map layers"), self.OnAddRasterMisc),
  814. ('addvect', Icons["addvect"].GetBitmap(),
  815. Icons["addvect"].GetLabel(), self.OnAddVector),
  816. ('addthematic', Icons["addthematic"].GetBitmap(),
  817. _("Add various vector-based map layer"), self.OnAddVectorMisc),
  818. ('addcmd', Icons["addcmd"].GetBitmap(),
  819. Icons["addcmd"].GetLabel(), self.OnAddCommand),
  820. ('addgrp', Icons["addgrp"].GetBitmap(),
  821. Icons["addgrp"].GetLabel(), self.OnAddGroup),
  822. ('addovl', Icons["addovl"].GetBitmap(),
  823. Icons["addovl"].GetLabel(), self.OnAddOverlay),
  824. ('delcmd', Icons["delcmd"].GetBitmap(),
  825. Icons["delcmd"].GetLabel(), self.OnDeleteLayer),
  826. ('', '', '', ''),
  827. ('attrtable', Icons["attrtable"].GetBitmap(),
  828. Icons["attrtable"].GetLabel(), self.OnShowAttributeTable)
  829. )
  830. def OnImportDxfFile(self, event):
  831. """!Convert multiple DXF layers to GRASS vector map layers"""
  832. dlg = gdialogs.MultiImportDialog(parent=self, type='dxf',
  833. title=_("Import DXF layers"))
  834. dlg.ShowModal()
  835. def OnImportGdalLayers(self, event):
  836. """!Convert multiple GDAL layers to GRASS raster map layers"""
  837. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  838. title=_("Import GDAL layers"))
  839. dlg.ShowModal()
  840. def OnLinkGdalLayers(self, event):
  841. """!Link multiple GDAL layers to GRASS raster map layers"""
  842. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  843. title=_("Link GDAL layers"),
  844. link = True)
  845. dlg.ShowModal()
  846. def OnImportOgrLayers(self, event):
  847. """!Convert multiple OGR layers to GRASS vector map layers"""
  848. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  849. title=_("Import OGR layers"))
  850. dlg.ShowModal()
  851. def OnLinkOgrLayers(self, event):
  852. """!Links multiple OGR layers to GRASS vector map layers"""
  853. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  854. title=_("Link OGR layers"),
  855. link = True)
  856. dlg.ShowModal()
  857. def OnImportWMS(self, event):
  858. """!Import data from OGC WMS server"""
  859. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  860. dlg.CenterOnScreen()
  861. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  862. layers = dlg.GetLayers()
  863. if len(layers.keys()) > 0:
  864. for layer in layers.keys():
  865. cmd = ['r.in.wms',
  866. 'mapserver=%s' % dlg.GetSettings()['server'],
  867. 'layers=%s' % layer,
  868. 'output=%s' % layer]
  869. styles = ','.join(layers[layer])
  870. if styles:
  871. cmd.append('styles=%s' % styles)
  872. self.goutput.RunCmd(cmd, switchPage = True)
  873. else:
  874. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  875. dlg.Destroy()
  876. def OnShowAttributeTable(self, event):
  877. """
  878. Show attribute table of the given vector map layer
  879. """
  880. if not self.curr_page:
  881. self.MsgNoLayerSelected()
  882. return
  883. layer = self.curr_page.maptree.layer_selected
  884. # no map layer selected
  885. if not layer:
  886. self.MsgNoLayerSelected()
  887. return
  888. # available only for vector map layers
  889. try:
  890. maptype = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].type
  891. except:
  892. maptype = None
  893. if not maptype or maptype != 'vector':
  894. wx.MessageBox(parent=self,
  895. message=_("Attribute management is available only "
  896. "for vector maps."),
  897. caption=_("Message"),
  898. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  899. return
  900. if not self.curr_page.maptree.GetPyData(layer)[0]:
  901. return
  902. dcmd = self.curr_page.maptree.GetPyData(layer)[0]['cmd']
  903. if not dcmd:
  904. return
  905. busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
  906. parent=self)
  907. wx.Yield()
  908. dbmanager = dbm.AttributeManager(parent=self, id=wx.ID_ANY,
  909. size=wx.Size(500, 300),
  910. item=layer, log=self.goutput)
  911. busy.Destroy()
  912. # register ATM dialog
  913. self.dialogs['atm'].append(dbmanager)
  914. # show ATM window
  915. dbmanager.Show()
  916. def OnNewDisplay(self, event=None):
  917. """!Create new layer tree and map display instance"""
  918. self.NewDisplay()
  919. def NewDisplay(self, show=True):
  920. """!Create new layer tree, which will
  921. create an associated map display frame
  922. @param show show map display window if True
  923. @return reference to mapdisplay intance
  924. """
  925. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  926. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  927. self.pg_panel = wx.Panel(self.gm_cb, id=wx.ID_ANY, style= wx.EXPAND)
  928. self.gm_cb.AddPage(self.pg_panel, text="Display "+ str(self.disp_idx + 1), select = True)
  929. self.curr_page = self.gm_cb.GetCurrentPage()
  930. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  931. self.curr_page.maptree = wxgui_utils.LayerTree(self.curr_page, id=wx.ID_ANY, pos=wx.DefaultPosition,
  932. size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS
  933. |wx.TR_LINES_AT_ROOT|wx.TR_HIDE_ROOT
  934. |wx.TR_DEFAULT_STYLE|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE,
  935. idx=self.disp_idx, lmgr=self, notebook=self.gm_cb,
  936. auimgr=self._auimgr, showMapDisplay=show)
  937. # layout for controls
  938. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  939. cb_boxsizer.Add(self.curr_page.maptree, proportion=1, flag=wx.EXPAND, border=1)
  940. self.curr_page.SetSizer(cb_boxsizer)
  941. cb_boxsizer.Fit(self.curr_page.maptree)
  942. self.curr_page.Layout()
  943. self.curr_page.maptree.Layout()
  944. # use default window layout
  945. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  946. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  947. idx = 4 + self.disp_idx * 4
  948. try:
  949. x, y = map(int, dim.split(',')[idx:idx + 2])
  950. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  951. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  952. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  953. except:
  954. pass
  955. self.disp_idx += 1
  956. return self.curr_page.maptree.mapdisplay
  957. # toolBar button handlers
  958. def OnAddRaster(self, event):
  959. """!Add raster map layer"""
  960. # start new map display if no display is available
  961. if not self.curr_page:
  962. self.NewDisplay(show=False)
  963. self.AddRaster(event)
  964. def OnAddRasterMisc(self, event):
  965. """!Add raster menu"""
  966. # start new map display if no display is available
  967. if not self.curr_page:
  968. self.NewDisplay(show=False)
  969. point = wx.GetMousePosition()
  970. rastmenu = wx.Menu()
  971. # add items to the menu
  972. if self.curr_page.maptree.mapdisplay.toolbars['nviz']:
  973. addrast3d = wx.MenuItem(rastmenu, -1, Icons ["addrast3d"].GetLabel())
  974. addrast3d.SetBitmap(Icons["addrast3d"].GetBitmap (self.iconsize))
  975. rastmenu.AppendItem(addrast3d)
  976. self.Bind(wx.EVT_MENU, self.AddRaster3d, addrast3d)
  977. addshaded = wx.MenuItem(rastmenu, -1, Icons ["addshaded"].GetLabel())
  978. addshaded.SetBitmap(Icons["addshaded"].GetBitmap (self.iconsize))
  979. rastmenu.AppendItem(addshaded)
  980. self.Bind(wx.EVT_MENU, self.AddShaded, addshaded)
  981. addrgb = wx.MenuItem(rastmenu, -1, Icons["addrgb"].GetLabel())
  982. addrgb.SetBitmap(Icons["addrgb"].GetBitmap(self.iconsize))
  983. rastmenu.AppendItem(addrgb)
  984. self.Bind(wx.EVT_MENU, self.AddRGB, addrgb)
  985. addhis = wx.MenuItem(rastmenu, -1, Icons ["addhis"].GetLabel())
  986. addhis.SetBitmap(Icons["addhis"].GetBitmap (self.iconsize))
  987. rastmenu.AppendItem(addhis)
  988. self.Bind(wx.EVT_MENU, self.AddHIS, addhis)
  989. addrastarrow = wx.MenuItem(rastmenu, -1, Icons ["addrarrow"].GetLabel())
  990. addrastarrow.SetBitmap(Icons["addrarrow"].GetBitmap (self.iconsize))
  991. rastmenu.AppendItem(addrastarrow)
  992. self.Bind(wx.EVT_MENU, self.AddRastarrow, addrastarrow)
  993. addrastnums = wx.MenuItem(rastmenu, -1, Icons ["addrnum"].GetLabel())
  994. addrastnums.SetBitmap(Icons["addrnum"].GetBitmap (self.iconsize))
  995. rastmenu.AppendItem(addrastnums)
  996. self.Bind(wx.EVT_MENU, self.AddRastnum, addrastnums)
  997. # Popup the menu. If an item is selected then its handler
  998. # will be called before PopupMenu returns.
  999. self.PopupMenu(rastmenu)
  1000. rastmenu.Destroy()
  1001. # show map display
  1002. self.curr_page.maptree.mapdisplay.Show()
  1003. def OnAddVector(self, event):
  1004. """!Add vector map layer"""
  1005. # start new map display if no display is available
  1006. if not self.curr_page:
  1007. self.NewDisplay(show=False)
  1008. self.AddVector(event)
  1009. def OnAddVectorMisc(self, event):
  1010. """!Add vector menu"""
  1011. # start new map display if no display is available
  1012. if not self.curr_page:
  1013. self.NewDisplay(show=False)
  1014. point = wx.GetMousePosition()
  1015. vectmenu = wx.Menu()
  1016. addtheme = wx.MenuItem(vectmenu, -1, Icons["addthematic"].GetLabel())
  1017. addtheme.SetBitmap(Icons["addthematic"].GetBitmap(self.iconsize))
  1018. vectmenu.AppendItem(addtheme)
  1019. self.Bind(wx.EVT_MENU, self.AddThemeMap, addtheme)
  1020. addchart = wx.MenuItem(vectmenu, -1, Icons["addchart"].GetLabel())
  1021. addchart.SetBitmap(Icons["addchart"].GetBitmap(self.iconsize))
  1022. vectmenu.AppendItem(addchart)
  1023. self.Bind(wx.EVT_MENU, self.AddThemeChart, addchart)
  1024. # Popup the menu. If an item is selected then its handler
  1025. # will be called before PopupMenu returns.
  1026. self.PopupMenu(vectmenu)
  1027. vectmenu.Destroy()
  1028. # show map display
  1029. self.curr_page.maptree.mapdisplay.Show()
  1030. def OnAddOverlay(self, event):
  1031. """!Add decoration overlay menu"""
  1032. # start new map display if no display is available
  1033. if not self.curr_page:
  1034. self.NewDisplay(show=False)
  1035. point = wx.GetMousePosition()
  1036. ovlmenu = wx.Menu()
  1037. addgrid = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgrid"].GetLabel())
  1038. addgrid.SetBitmap(Icons["addgrid"].GetBitmap(self.iconsize))
  1039. ovlmenu.AppendItem(addgrid)
  1040. self.Bind(wx.EVT_MENU, self.AddGrid, addgrid)
  1041. addlabels = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addlabels"].GetLabel())
  1042. addlabels.SetBitmap(Icons["addlabels"].GetBitmap(self.iconsize))
  1043. ovlmenu.AppendItem(addlabels)
  1044. self.Bind(wx.EVT_MENU, self.OnAddLabels, addlabels)
  1045. addgeodesic = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgeodesic"].GetLabel())
  1046. addgeodesic.SetBitmap(Icons["addgeodesic"].GetBitmap(self.iconsize))
  1047. ovlmenu.AppendItem(addgeodesic)
  1048. self.Bind(wx.EVT_MENU, self.AddGeodesic, addgeodesic)
  1049. addrhumb = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addrhumb"].GetLabel())
  1050. addrhumb.SetBitmap(Icons["addrhumb"].GetBitmap(self.iconsize))
  1051. ovlmenu.AppendItem(addrhumb)
  1052. self.Bind(wx.EVT_MENU, self.AddRhumb, addrhumb)
  1053. # Popup the menu. If an item is selected then its handler
  1054. # will be called before PopupMenu returns.
  1055. self.PopupMenu(ovlmenu)
  1056. ovlmenu.Destroy()
  1057. # show map display
  1058. self.curr_page.maptree.mapdisplay.Show()
  1059. def AddRaster(self, event):
  1060. self.notebook.SetSelection(0)
  1061. self.curr_page.maptree.AddLayer('raster')
  1062. def AddRaster3d(self, event):
  1063. self.notebook.SetSelection(0)
  1064. self.curr_page.maptree.AddLayer('3d-raster')
  1065. def AddRGB(self, event):
  1066. """!Add RGB layer"""
  1067. self.notebook.SetSelection(0)
  1068. self.curr_page.maptree.AddLayer('rgb')
  1069. def AddHIS(self, event):
  1070. """!Add HIS layer"""
  1071. self.notebook.SetSelection(0)
  1072. self.curr_page.maptree.AddLayer('his')
  1073. def AddShaded(self, event):
  1074. """!Add shaded relief map layer"""
  1075. self.notebook.SetSelection(0)
  1076. self.curr_page.maptree.AddLayer('shaded')
  1077. def AddRastarrow(self, event):
  1078. """!Add raster flow arrows map"""
  1079. self.notebook.SetSelection(0)
  1080. self.curr_page.maptree.AddLayer('rastarrow')
  1081. def AddRastnum(self, event):
  1082. """!Add raster map with cell numbers"""
  1083. self.notebook.SetSelection(0)
  1084. self.curr_page.maptree.AddLayer('rastnum')
  1085. def AddVector(self, event):
  1086. """!Add vector layer"""
  1087. self.notebook.SetSelection(0)
  1088. self.curr_page.maptree.AddLayer('vector')
  1089. def AddThemeMap(self, event):
  1090. """!Add thematic map layer"""
  1091. self.notebook.SetSelection(0)
  1092. self.curr_page.maptree.AddLayer('thememap')
  1093. def AddThemeChart(self, event):
  1094. """!Add thematic chart layer"""
  1095. self.notebook.SetSelection(0)
  1096. self.curr_page.maptree.AddLayer('themechart')
  1097. def OnAddCommand(self, event):
  1098. """!Add command line layer"""
  1099. # start new map display if no display is available
  1100. if not self.curr_page:
  1101. self.NewDisplay(show=False)
  1102. self.notebook.SetSelection(0)
  1103. self.curr_page.maptree.AddLayer('command')
  1104. # show map display
  1105. self.curr_page.maptree.mapdisplay.Show()
  1106. def OnAddGroup(self, event):
  1107. """!Add layer group"""
  1108. # start new map display if no display is available
  1109. if not self.curr_page:
  1110. self.NewDisplay(show=False)
  1111. self.notebook.SetSelection(0)
  1112. self.curr_page.maptree.AddLayer('group')
  1113. # show map display
  1114. self.curr_page.maptree.mapdisplay.Show()
  1115. def AddGrid(self, event):
  1116. """!Add layer grid"""
  1117. self.notebook.SetSelection(0)
  1118. self.curr_page.maptree.AddLayer('grid')
  1119. def AddGeodesic(self, event):
  1120. """!Add layer geodesic"""
  1121. self.notebook.SetSelection(0)
  1122. self.curr_page.maptree.AddLayer('geodesic')
  1123. def AddRhumb(self, event):
  1124. """!Add layer rhumb"""
  1125. self.notebook.SetSelection(0)
  1126. self.curr_page.maptree.AddLayer('rhumb')
  1127. def OnAddLabels(self, event):
  1128. """!Add layer vector labels"""
  1129. # start new map display if no display is available
  1130. if not self.curr_page:
  1131. self.NewDisplay(show=False)
  1132. self.notebook.SetSelection(0)
  1133. self.curr_page.maptree.AddLayer('labels')
  1134. # show map display
  1135. self.curr_page.maptree.mapdisplay.Show()
  1136. def OnDeleteLayer(self, event):
  1137. """
  1138. Delete selected map display layer in GIS Manager tree widget
  1139. """
  1140. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1141. self.MsgNoLayerSelected()
  1142. return
  1143. if UserSettings.Get(group='manager', key='askOnRemoveLayer', subkey='enabled'):
  1144. layerName = ''
  1145. for item in self.curr_page.maptree.GetSelections():
  1146. name = str(self.curr_page.maptree.GetItemText(item))
  1147. idx = name.find('(opacity')
  1148. if idx > -1:
  1149. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1150. else:
  1151. layerName += '<' + name + '>,\n'
  1152. layerName = layerName.rstrip(',\n')
  1153. if len(layerName) > 2: # <>
  1154. message = _("Do you want to remove map layer(s)\n%s\n"
  1155. "from layer tree?") % layerName
  1156. else:
  1157. message = _("Do you want to remove selected map layer(s) "
  1158. "from layer tree?")
  1159. dlg = wx.MessageDialog (parent=self, message=message,
  1160. caption=_("Remove map layer"),
  1161. style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
  1162. if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
  1163. dlg.Destroy()
  1164. return
  1165. dlg.Destroy()
  1166. for layer in self.curr_page.maptree.GetSelections():
  1167. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1168. self.curr_page.maptree.DeleteChildren(layer)
  1169. self.curr_page.maptree.Delete(layer)
  1170. def OnKeyDown(self, event):
  1171. """!Key pressed"""
  1172. kc = event.GetKeyCode()
  1173. print kc
  1174. if event.ControlDown():
  1175. if kc == wx.WXK_TAB:
  1176. # switch layer list / command output
  1177. if self.notebook.GetSelection() == 0:
  1178. self.notebook.SetSelection(1)
  1179. else:
  1180. self.notebook.SetSelection(0)
  1181. try:
  1182. ckc = chr(kc)
  1183. except ValueError:
  1184. event.Skip()
  1185. return
  1186. if event.CtrlDown():
  1187. if kc == 'R':
  1188. self.OnAddRaster(None)
  1189. elif kc == 'V':
  1190. self.OnAddVector(None)
  1191. event.Skip()
  1192. def OnQuit(self, event):
  1193. """!Quit GRASS session (wxGUI and shell)"""
  1194. # quit wxGUI session
  1195. self.OnCloseWindow(event)
  1196. # quit GRASS shell
  1197. try:
  1198. pid = int(os.environ['GIS_LOCK'])
  1199. except (KeyError, ValueError):
  1200. sys.stderr.write('\n')
  1201. sys.stderr.write(_("WARNING: Unable to quit GRASS, uknown GIS_LOCK"))
  1202. return
  1203. os.kill(pid, signal.SIGQUIT)
  1204. def OnCloseWindow(self, event):
  1205. """!Cleanup when wxGUI is quit"""
  1206. if not self.curr_page:
  1207. self._auimgr.UnInit()
  1208. self.Destroy()
  1209. return
  1210. maptree = self.curr_page.maptree
  1211. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  1212. if self.workspaceFile:
  1213. message = _("Do you want to save changes in the workspace?")
  1214. else:
  1215. message = _("Do you want to store current settings "
  1216. "to workspace file?")
  1217. # ask user to save current settings
  1218. if maptree.GetCount() > 0:
  1219. dlg = wx.MessageDialog(self,
  1220. message=message,
  1221. caption=_("Quit GRASS GUI"),
  1222. style=wx.YES_NO | wx.YES_DEFAULT |
  1223. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1224. ret = dlg.ShowModal()
  1225. if ret == wx.ID_YES:
  1226. if not self.workspaceFile:
  1227. self.OnWorkspaceSaveAs()
  1228. else:
  1229. self.SaveToWorkspaceFile(self.workspaceFile)
  1230. elif ret == wx.ID_CANCEL:
  1231. event.Veto()
  1232. dlg.Destroy()
  1233. return
  1234. dlg.Destroy()
  1235. # don't ask any more...
  1236. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1237. value = False)
  1238. for page in range(self.gm_cb.GetPageCount()):
  1239. self.gm_cb.GetPage(0).maptree.mapdisplay.OnCloseWindow(event)
  1240. self.gm_cb.DeleteAllPages()
  1241. self._auimgr.UnInit()
  1242. self.Destroy()
  1243. def MsgNoLayerSelected(self):
  1244. """!Show dialog message 'No layer selected'"""
  1245. wx.MessageBox(parent=self,
  1246. message=_("No map layer selected. Operation cancelled."),
  1247. caption=_("Message"),
  1248. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1249. class GMApp(wx.App):
  1250. def __init__(self, workspace = None):
  1251. """!Main GUI class.
  1252. @param workspace path to the workspace file
  1253. """
  1254. self.workspaceFile = workspace
  1255. # call parent class initializer
  1256. wx.App.__init__(self, False)
  1257. def OnInit(self):
  1258. """!Initialize all available image handlers
  1259. @return True
  1260. """
  1261. wx.InitAllImageHandlers()
  1262. # create splash screen
  1263. introImagePath = os.path.join(globalvar.ETCWXDIR, "images", "intro.png")
  1264. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1265. introBmp = introImage.ConvertToBitmap()
  1266. wx.SplashScreen (bitmap=introBmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1267. milliseconds=1500, parent=None, id=wx.ID_ANY)
  1268. wx.Yield()
  1269. # create and show main frame
  1270. mainframe = GMFrame(parent=None, id=wx.ID_ANY,
  1271. workspace = self.workspaceFile)
  1272. mainframe.Show()
  1273. self.SetTopWindow(mainframe)
  1274. return True
  1275. class Usage(Exception):
  1276. def __init__(self, msg):
  1277. self.msg = msg
  1278. def printHelp():
  1279. """!Print program help"""
  1280. print >> sys.stderr, "Usage:"
  1281. print >> sys.stderr, " python wxgui.py [options]"
  1282. print >> sys.stderr, "%sOptions:" % os.linesep
  1283. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1284. sys.exit(0)
  1285. def process_opt(opts, args):
  1286. """!Process command-line arguments"""
  1287. workspaceFile = None
  1288. for o, a in opts:
  1289. if o in ("-h", "--help"):
  1290. printHelp()
  1291. if o in ("-w", "--workspace"):
  1292. if a != '':
  1293. workspaceFile = str(a)
  1294. else:
  1295. workspaceFile = args.pop(0)
  1296. return (workspaceFile,)
  1297. def main(argv=None):
  1298. #
  1299. # process command-line arguments
  1300. #
  1301. if argv is None:
  1302. argv = sys.argv
  1303. try:
  1304. try:
  1305. opts, args = getopt.getopt(argv[1:], "hw:",
  1306. ["help", "workspace"])
  1307. except getopt.error, msg:
  1308. raise Usage(msg)
  1309. except Usage, err:
  1310. print >> sys.stderr, err.msg
  1311. print >> sys.stderr, "for help use --help"
  1312. printHelp()
  1313. workspaceFile = process_opt(opts, args)[0]
  1314. #
  1315. # run application
  1316. #
  1317. app = GMApp(workspaceFile)
  1318. # suppress wxPython logs
  1319. q = wx.LogNull()
  1320. app.MainLoop()
  1321. if __name__ == "__main__":
  1322. sys.exit(main())