pyedit.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. """GRASS GIS Simple Python Editor
  2. Copyright (C) 2016 by the GRASS Development Team
  3. This program is free software under the GNU General Public
  4. License (>=v2). Read the file COPYING that comes with GRASS GIS
  5. for details.
  6. :authors: Vaclav Petras
  7. :authors: Martin Landa
  8. """
  9. import sys
  10. import os
  11. import stat
  12. from StringIO import StringIO
  13. import time
  14. import wx
  15. import grass.script as gscript
  16. from grass.script.utils import try_remove
  17. # just for testing
  18. if __name__ == '__main__':
  19. from grass.script.setup import set_gui_path
  20. set_gui_path()
  21. from core.utils import _
  22. from core.gcmd import EncodeString, GError
  23. from core.giface import StandaloneGrassInterface
  24. from gui_core.pystc import PyStc
  25. from core import globalvar
  26. from core.menutree import MenuTreeModelBuilder
  27. from gui_core.menu import Menu
  28. from gui_core.toolbars import BaseToolbar, BaseIcons
  29. from icons.icon import MetaIcon
  30. # TODO: add validation: call/import pep8 (error message if not available)
  31. # TODO: run with parameters
  32. # TODO: run with overwrite (in process env, not os.environ)
  33. # TODO: add more examples (separate file)
  34. # TODO: add test for templates and examples
  35. # TODO: add pep8 test for templates and examples
  36. # TODO: add snippets?
  37. def script_template():
  38. """The most simple script which runs and gives something"""
  39. return r"""#!/usr/bin/env python
  40. import grass.script as gscript
  41. def main():
  42. gscript.run_command('g.region', flags='p')
  43. if __name__ == '__main__':
  44. main()
  45. """
  46. def module_template():
  47. """Template from which to start writing GRASS module"""
  48. import getpass
  49. author = getpass.getuser()
  50. properties = {}
  51. properties['name'] = 'module name'
  52. properties['author'] = author
  53. properties['description'] = 'Module description'
  54. output = StringIO()
  55. # header
  56. output.write(
  57. r"""#!/usr/bin/env python
  58. #
  59. #%s
  60. #
  61. # MODULE: %s
  62. #
  63. # AUTHOR(S): %s
  64. #
  65. # PURPOSE: %s
  66. #
  67. # DATE: %s
  68. #
  69. #%s
  70. """ % ('#' * 72,
  71. EncodeString(properties['name']),
  72. EncodeString(properties['author']),
  73. EncodeString('\n# '.join(properties['description'].splitlines())),
  74. time.asctime(),
  75. '#' * 72))
  76. # UI
  77. output.write(
  78. r"""
  79. #%%module
  80. #%% description: %s
  81. #%%end
  82. """ % (EncodeString(' '.join(properties['description'].splitlines()))))
  83. # import modules
  84. output.write(
  85. r"""
  86. import sys
  87. import os
  88. import atexit
  89. import grass.script as gscript
  90. """)
  91. # cleanup()
  92. output.write(
  93. r"""
  94. RAST_REMOVE = []
  95. def cleanup():
  96. """)
  97. output.write(
  98. r""" gscript.run_command('g.remove', flags='f', type='raster',
  99. name=RAST_REMOVE)
  100. """)
  101. output.write("\ndef main():\n")
  102. output.write(
  103. r""" options, flags = gscript.parser()
  104. gscript.run_command('g.remove', flags='f', type='raster',
  105. name=RAST_REMOVE)
  106. """)
  107. output.write("\n return 0\n")
  108. output.write(
  109. r"""
  110. if __name__ == "__main__":
  111. atexit.register(cleanup)
  112. sys.exit(main())
  113. """)
  114. return output.getvalue()
  115. def script_example():
  116. """Example of a simple script"""
  117. return r"""#!/usr/bin/env python
  118. import grass.script as gscript
  119. def main():
  120. input_raster = 'elevation'
  121. output_raster = 'high_areas'
  122. stats = gscript.parse_command('r.univar', map='elevation', flags='g')
  123. raster_mean = float(stats['mean'])
  124. raster_stddev = float(stats['stddev'])
  125. raster_high = raster_mean + raster_stddev
  126. gscript.mapcalc('{r} = {a} > {m}'.format(r=output_raster, a=input_raster,
  127. m=raster_high))
  128. if __name__ == "__main__":
  129. main()
  130. """
  131. def module_example():
  132. """Example of a GRASS module"""
  133. return r"""#!/usr/bin/env python
  134. #%module
  135. #% description: Adds the values of two rasters (A + B)
  136. #% keyword: raster
  137. #% keyword: algebra
  138. #% keyword: sum
  139. #%end
  140. #%option G_OPT_R_INPUT
  141. #% key: araster
  142. #% description: Name of input raster A in an expression A + B
  143. #%end
  144. #%option G_OPT_R_INPUT
  145. #% key: braster
  146. #% description: Name of input raster B in an expression A + B
  147. #%end
  148. #%option G_OPT_R_OUTPUT
  149. #%end
  150. import sys
  151. import grass.script as gscript
  152. def main():
  153. options, flags = gscript.parser()
  154. araster = options['araster']
  155. braster = options['braster']
  156. output = options['output']
  157. gscript.mapcalc('{r} = {a} + {b}'.format(r=output, a=araster, b=braster))
  158. return 0
  159. if __name__ == "__main__":
  160. sys.exit(main())
  161. """
  162. def module_error_handling_example():
  163. """Example of a GRASS module"""
  164. return r"""#!/usr/bin/env python
  165. #%module
  166. #% description: Selects values from raster above value of mean plus standard deviation
  167. #% keyword: raster
  168. #% keyword: select
  169. #% keyword: standard deviation
  170. #%end
  171. #%option G_OPT_R_INPUT
  172. #%end
  173. #%option G_OPT_R_OUTPUT
  174. #%end
  175. import sys
  176. import grass.script as gscript
  177. from grass.exceptions import CalledModuleError
  178. def main():
  179. options, flags = gscript.parser()
  180. input_raster = options['input']
  181. output_raster = options['output']
  182. try:
  183. stats = gscript.parse_command('r.univar', map=input_raster, flags='g')
  184. except CalledModuleError as e:
  185. gscript.fatal('{}'.format(e))
  186. raster_mean = float(stats['mean'])
  187. raster_stddev = float(stats['stddev'])
  188. raster_high = raster_mean + raster_stddev
  189. gscript.mapcalc('{r} = {i} > {v}'.format(r=output_raster, i=input_raster,
  190. v=raster_high))
  191. return 0
  192. if __name__ == "__main__":
  193. sys.exit(main())
  194. """
  195. class PyEditController(object):
  196. # using the naming GUI convention, change for controller?
  197. # pylint: disable=invalid-name
  198. def __init__(self, panel, guiparent, giface):
  199. """Simple editor, this class could be a pure controller"""
  200. self.guiparent = guiparent
  201. self.giface = giface
  202. self.body = panel
  203. self.filename = None
  204. self.tempfile = None # bool, make them strings for better code
  205. self.running = False
  206. def OnRun(self, event):
  207. """Run Python script"""
  208. if self.running:
  209. # ignore when already running
  210. return
  211. if not self.filename:
  212. self.filename = gscript.tempfile() + '.py'
  213. self.tempfile = True
  214. try:
  215. fd = open(self.filename, "w")
  216. fd.write(self.body.GetText())
  217. except IOError as e:
  218. GError(_("Unable to launch Python script. %s") % e,
  219. parent=self.guiparent)
  220. return
  221. finally:
  222. fd.close()
  223. mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE])
  224. os.chmod(self.filename, mode | stat.S_IXUSR)
  225. else:
  226. fd = open(self.filename, "w")
  227. try:
  228. fd.write(self.body.GetText())
  229. finally:
  230. fd.close()
  231. # set executable file
  232. # (not sure if needed every time but useful for opened files)
  233. os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)
  234. # TODO: add overwrite to toolbar, needs env in GConsole
  235. # run in console as other modules, avoid Python shell which
  236. # carries variables over to the next execution
  237. self.giface.RunCmd([fd.name], skipInterface=True, onDone=self.OnDone)
  238. self.running = True
  239. def OnDone(self, event):
  240. """Python script finished"""
  241. if self.tempfile:
  242. try_remove(self.filename)
  243. self.filename = None
  244. self.running = False
  245. def SaveAs(self):
  246. """Save python script to file"""
  247. filename = ''
  248. dlg = wx.FileDialog(parent=self.guiparent,
  249. message=_("Choose file to save"),
  250. defaultDir=os.getcwd(),
  251. wildcard=_("Python script (*.py)|*.py"),
  252. style=wx.FD_SAVE)
  253. if dlg.ShowModal() == wx.ID_OK:
  254. filename = dlg.GetPath()
  255. if not filename:
  256. return
  257. # check for extension
  258. if filename[-3:] != ".py":
  259. filename += ".py"
  260. if os.path.exists(filename):
  261. dlg = wx.MessageDialog(
  262. parent=self.guiparent,
  263. message=_("File <%s> already exists. "
  264. "Do you want to overwrite this file?") % filename,
  265. caption=_("Save file"),
  266. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  267. if dlg.ShowModal() == wx.ID_NO:
  268. dlg.Destroy()
  269. return
  270. dlg.Destroy()
  271. self.filename = filename
  272. self.tempfile = False
  273. self.Save()
  274. def Save(self):
  275. """Save current content to a file and set executable permissions"""
  276. assert self.filename
  277. fd = open(self.filename, "w")
  278. try:
  279. fd.write(self.body.GetText())
  280. finally:
  281. fd.close()
  282. # executable file
  283. os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)
  284. def OnSave(self, event):
  285. """Save python script to file
  286. Just save if file already specified, save as action otherwise.
  287. """
  288. if self.filename:
  289. self.Save()
  290. else:
  291. self.SaveAs()
  292. # TODO: it should be probably used with replacing, when this gives what we
  293. # want?
  294. def IsModified(self):
  295. """Check if python script has been modified"""
  296. return self.body.modified
  297. def Open(self):
  298. """Ask for a filename and load its content"""
  299. filename = ''
  300. dlg = wx.FileDialog(parent=self.guiparent,
  301. message=_("Open file"),
  302. defaultDir=os.getcwd(),
  303. wildcard=_("Python script (*.py)|*.py"),
  304. style=wx.OPEN)
  305. if dlg.ShowModal() == wx.ID_OK:
  306. filename = dlg.GetPath()
  307. if not filename:
  308. return
  309. fd = open(filename, "r")
  310. try:
  311. self.body.SetText(fd.read())
  312. finally:
  313. fd.close()
  314. self.filename = filename
  315. self.tempfile = False
  316. def OnOpen(self, event):
  317. if self.CanReplaceContent('file'):
  318. self.Open()
  319. def IsEmpty(self):
  320. """Check if python script is empty"""
  321. return len(self.body.GetText()) == 0
  322. def SetScriptTemplate(self, event):
  323. if self.CanReplaceContent('template'):
  324. self.body.SetText(script_template())
  325. def SetModuleTemplate(self, event):
  326. if self.CanReplaceContent('template'):
  327. self.body.SetText(module_template())
  328. def SetScriptExample(self, event):
  329. if self.CanReplaceContent('template'):
  330. self.body.SetText(script_example())
  331. def SetModuleExample(self, event):
  332. if self.CanReplaceContent('template'):
  333. self.body.SetText(module_example())
  334. def SetModuleErrorHandlingExample(self, event):
  335. if self.CanReplaceContent('template'):
  336. self.body.SetText(module_error_handling_example())
  337. def CanReplaceContent(self, by_message):
  338. if by_message == 'template':
  339. message = _("Replace the content by the template?")
  340. elif by_message == 'file':
  341. message = _("Replace the current content by the file content?")
  342. else:
  343. message = by_message
  344. if not self.IsEmpty():
  345. dlg = wx.MessageDialog(
  346. parent=self.guiparent, message=message,
  347. caption=_("Replace content"),
  348. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  349. if dlg.ShowModal() == wx.ID_NO:
  350. dlg.Destroy()
  351. return False
  352. dlg.Destroy()
  353. return True
  354. def OnHelp(self, event):
  355. import webbrowser
  356. # inspired by g.manual but simple not using GRASS_HTML_BROWSER
  357. # not using g.manual because it does not show
  358. entry = 'libpython/script_intro.html'
  359. major, minor, patch = gscript.version()['version'].split('.')
  360. url = 'http://grass.osgeo.org/grass%s%s/manuals/%s' % (
  361. major, minor, entry)
  362. webbrowser.open(url)
  363. def OnPythonHelp(self, event):
  364. import webbrowser
  365. url = 'https://docs.python.org/%s/tutorial/' % sys.version_info[0]
  366. webbrowser.open(url)
  367. def OnModulesHelp(self, event):
  368. self.giface.Help('full_index')
  369. def OnAddonsHelp(self, event):
  370. import webbrowser
  371. url = 'https://grass.osgeo.org/development/code-submission/'
  372. webbrowser.open(url)
  373. def OnSupport(self, event):
  374. import webbrowser
  375. url = 'https://grass.osgeo.org/support/'
  376. webbrowser.open(url)
  377. class PyEditToolbar(BaseToolbar):
  378. # GUI class
  379. # pylint: disable=too-many-ancestors
  380. # pylint: disable=too-many-public-methods
  381. """PyEdit toolbar"""
  382. def __init__(self, parent):
  383. BaseToolbar.__init__(self, parent)
  384. # workaround for http://trac.wxwidgets.org/ticket/13888
  385. if sys.platform == 'darwin':
  386. parent.SetToolBar(self)
  387. self.InitToolbar(self._toolbarData())
  388. # realize the toolbar
  389. self.Realize()
  390. def _toolbarData(self):
  391. """Toolbar data"""
  392. icons = {
  393. 'open': MetaIcon(img='open',
  394. label=_('Open (Ctrl+O)')),
  395. 'save': MetaIcon(img='save',
  396. label=_('Save (Ctrl+S)')),
  397. 'run': MetaIcon(img='execute',
  398. label=_('Run (Ctrl+R)')),
  399. }
  400. return self._getToolbarData((('open', icons['open'],
  401. self.parent.OnOpen),
  402. ('save', icons['save'],
  403. self.parent.OnSave),
  404. (None, ),
  405. ('run', icons['run'],
  406. self.parent.OnRun),
  407. (None, ),
  408. ("help", BaseIcons['help'],
  409. self.parent.OnHelp),
  410. ))
  411. class PyEditFrame(wx.Frame):
  412. # GUI class and a lot of trampoline methods
  413. # pylint: disable=missing-docstring
  414. # pylint: disable=too-many-public-methods
  415. # pylint: disable=invalid-name
  416. def __init__(self, parent, giface, id=wx.ID_ANY,
  417. title=_("GRASS GIS Simple Python Editor"),
  418. **kwargs):
  419. wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs)
  420. self.parent = parent
  421. filename = os.path.join(
  422. globalvar.WXGUIDIR, 'xml', 'menudata_pyedit.xml')
  423. self.menubar = Menu(
  424. parent=self,
  425. model=MenuTreeModelBuilder(filename).GetModel(separators=True))
  426. self.SetMenuBar(self.menubar)
  427. self.toolbar = PyEditToolbar(parent=self)
  428. # workaround for http://trac.wxwidgets.org/ticket/13888
  429. # TODO: toolbar is set in toolbar and here
  430. if sys.platform != 'darwin':
  431. self.SetToolBar(self.toolbar)
  432. self.panel = PyStc(parent=self)
  433. self.controller = PyEditController(
  434. panel=self.panel, guiparent=self, giface=giface)
  435. # don't start with an empty page
  436. self.panel.SetText(script_template())
  437. sizer = wx.BoxSizer(wx.VERTICAL)
  438. sizer.Add(item=self.panel, proportion=1,
  439. flag=wx.EXPAND)
  440. sizer.Fit(self)
  441. sizer.SetSizeHints(self)
  442. self.SetSizer(sizer)
  443. self.Fit()
  444. self.SetAutoLayout(True)
  445. self.Layout()
  446. # TODO: it would be nice if we can pass the controller to the menu
  447. # might not be possible on the side of menu
  448. # here we use self and self.controller which might make it harder
  449. def OnOpen(self, *args, **kwargs):
  450. self.controller.OnOpen(*args, **kwargs)
  451. def OnSave(self, *args, **kwargs):
  452. self.controller.OnSave(*args, **kwargs)
  453. def OnClose(self, *args, **kwargs):
  454. # saves without asking if we have an open file
  455. self.controller.OnSave(*args, **kwargs)
  456. self.Destroy()
  457. def OnRun(self, *args, **kwargs):
  458. # save without asking
  459. self.controller.OnRun(*args, **kwargs)
  460. def OnHelp(self, *args, **kwargs):
  461. self.controller.OnHelp(*args, **kwargs)
  462. def OnSimpleScriptTemplate(self, *args, **kwargs):
  463. self.controller.SetScriptTemplate(*args, **kwargs)
  464. def OnGrassModuleTemplate(self, *args, **kwargs):
  465. self.controller.SetModuleTemplate(*args, **kwargs)
  466. def OnSimpleScriptExample(self, *args, **kwargs):
  467. self.controller.SetScriptExample(*args, **kwargs)
  468. def OnGrassModuleExample(self, *args, **kwargs):
  469. self.controller.SetModuleExample(*args, **kwargs)
  470. def OnGrassModuleErrorHandlingExample(self, *args, **kwargs):
  471. self.controller.SetModuleErrorHandlingExample(*args, **kwargs)
  472. def OnPythonHelp(self, *args, **kwargs):
  473. self.controller.OnPythonHelp(*args, **kwargs)
  474. def OnModulesHelp(self, *args, **kwargs):
  475. self.controller.OnModulesHelp(*args, **kwargs)
  476. def OnAddonsHelp(self, *args, **kwargs):
  477. self.controller.OnAddonsHelp(*args, **kwargs)
  478. def OnSupport(self, *args, **kwargs):
  479. self.controller.OnSupport(*args, **kwargs)
  480. def main():
  481. """Test application (potentially useful as g.gui.pyedit)"""
  482. app = wx.App()
  483. giface = StandaloneGrassInterface()
  484. simple_editor = PyEditFrame(parent=None, giface=giface)
  485. simple_editor.SetSize((600, 800))
  486. simple_editor.Show()
  487. app.MainLoop()
  488. if __name__ == '__main__':
  489. main()