pyedit.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. class PyEditController(object):
  163. # using the naming GUI convention, change for controller?
  164. # pylint: disable=invalid-name
  165. def __init__(self, panel, guiparent, giface):
  166. """Simple editor, this class could be a pure controller"""
  167. self.guiparent = guiparent
  168. self.giface = giface
  169. self.body = panel
  170. self.filename = None
  171. self.tempfile = None # bool, make them strings for better code
  172. self.running = False
  173. def OnRun(self, event):
  174. """Run Python script"""
  175. if self.running:
  176. # ignore when already running
  177. return
  178. if not self.filename:
  179. self.filename = gscript.tempfile()
  180. self.tempfile = True
  181. try:
  182. fd = open(self.filename, "w")
  183. fd.write(self.body.GetText())
  184. except IOError as e:
  185. GError(_("Unable to launch Python script. %s") % e,
  186. parent=self.guiparent)
  187. return
  188. finally:
  189. fd.close()
  190. mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE])
  191. os.chmod(self.filename, mode | stat.S_IXUSR)
  192. else:
  193. fd = open(self.filename, "w")
  194. try:
  195. fd.write(self.body.GetText())
  196. finally:
  197. fd.close()
  198. # set executable file
  199. # (not sure if needed every time but useful for opened files)
  200. os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)
  201. # TODO: add overwrite to toolbar, needs env in GConsole
  202. # run in console as other modules, avoid Python shell which
  203. # carries variables over to the next execution
  204. self.giface.RunCmd([fd.name], skipInterface=True, onDone=self.OnDone)
  205. self.running = True
  206. def OnDone(self, event):
  207. """Python script finished"""
  208. if self.tempfile:
  209. try_remove(self.filename)
  210. self.filename = None
  211. self.running = False
  212. def SaveAs(self):
  213. """Save python script to file"""
  214. filename = ''
  215. dlg = wx.FileDialog(parent=self.guiparent,
  216. message=_("Choose file to save"),
  217. defaultDir=os.getcwd(),
  218. wildcard=_("Python script (*.py)|*.py"),
  219. style=wx.FD_SAVE)
  220. if dlg.ShowModal() == wx.ID_OK:
  221. filename = dlg.GetPath()
  222. if not filename:
  223. return
  224. # check for extension
  225. if filename[-3:] != ".py":
  226. filename += ".py"
  227. if os.path.exists(filename):
  228. dlg = wx.MessageDialog(
  229. parent=self.guiparent,
  230. message=_("File <%s> already exists. "
  231. "Do you want to overwrite this file?") % filename,
  232. caption=_("Save file"),
  233. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  234. if dlg.ShowModal() == wx.ID_NO:
  235. dlg.Destroy()
  236. return
  237. dlg.Destroy()
  238. self.filename = filename
  239. self.tempfile = False
  240. self.Save()
  241. def Save(self):
  242. """Save current content to a file and set executable permissions"""
  243. assert self.filename
  244. fd = open(self.filename, "w")
  245. try:
  246. fd.write(self.body.GetText())
  247. finally:
  248. fd.close()
  249. # executable file
  250. os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)
  251. def OnSave(self, event):
  252. """Save python script to file
  253. Just save if file already specified, save as action otherwise.
  254. """
  255. if self.filename:
  256. self.Save()
  257. else:
  258. self.SaveAs()
  259. # TODO: it should be probably used with replacing, when this gives what we want?
  260. def IsModified(self):
  261. """Check if python script has been modified"""
  262. return self.body.modified
  263. def Open(self):
  264. """Ask for a filename and load its content"""
  265. filename = ''
  266. dlg = wx.FileDialog(parent=self.guiparent,
  267. message=_("Open file"),
  268. defaultDir=os.getcwd(),
  269. wildcard=_("Python script (*.py)|*.py"),
  270. style=wx.OPEN)
  271. if dlg.ShowModal() == wx.ID_OK:
  272. filename = dlg.GetPath()
  273. if not filename:
  274. return
  275. fd = open(filename, "r")
  276. try:
  277. self.body.SetText(fd.read())
  278. finally:
  279. fd.close()
  280. self.filename = filename
  281. self.tempfile = False
  282. def OnOpen(self, event):
  283. if self.CanReplaceContent('file'):
  284. self.Open()
  285. def IsEmpty(self):
  286. """Check if python script is empty"""
  287. return len(self.body.GetText()) == 0
  288. def SetScriptTemplate(self, event):
  289. if self.CanReplaceContent('template'):
  290. self.body.SetText(script_template())
  291. def SetModuleTemplate(self, event):
  292. if self.CanReplaceContent('template'):
  293. self.body.SetText(module_template())
  294. def SetScriptExample(self, event):
  295. if self.CanReplaceContent('template'):
  296. self.body.SetText(script_example())
  297. def SetModuleExample(self, event):
  298. if self.CanReplaceContent('template'):
  299. self.body.SetText(module_example())
  300. def CanReplaceContent(self, by_message):
  301. if by_message == 'template':
  302. message = _("Replace the content by the template?")
  303. elif by_message == 'file':
  304. message = _("Replace the current content by the file content?")
  305. else:
  306. message = by_message
  307. if not self.IsEmpty():
  308. dlg = wx.MessageDialog(
  309. parent=self.guiparent, message=message,
  310. caption=_("Replace content"),
  311. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  312. if dlg.ShowModal() == wx.ID_NO:
  313. dlg.Destroy()
  314. return False
  315. dlg.Destroy()
  316. return True
  317. def OnHelp(self, event):
  318. import webbrowser
  319. # inspired by g.manual but simple not using GRASS_HTML_BROWSER
  320. # not using g.manual because it does not show
  321. entry = 'libpython/script_intro.html'
  322. major, minor, patch = gscript.version()['version'].split('.')
  323. url = 'http://grass.osgeo.org/grass%s%s/manuals/%s' % (
  324. major, minor, entry)
  325. webbrowser.open(url)
  326. def OnPythonHelp(self, event):
  327. import webbrowser
  328. url = 'https://docs.python.org/%s/tutorial/' % sys.version_info[0]
  329. webbrowser.open(url)
  330. def OnModulesHelp(self, event):
  331. self.giface.Help('full_index')
  332. def OnAddonsHelp(self, event):
  333. import webbrowser
  334. url = 'https://grass.osgeo.org/development/code-submission/'
  335. webbrowser.open(url)
  336. def OnSupport(self, event):
  337. import webbrowser
  338. url = 'https://grass.osgeo.org/support/'
  339. webbrowser.open(url)
  340. class PyEditToolbar(BaseToolbar):
  341. # GUI class
  342. # pylint: disable=too-many-ancestors
  343. # pylint: disable=too-many-public-methods
  344. """PyEdit toolbar"""
  345. def __init__(self, parent):
  346. BaseToolbar.__init__(self, parent)
  347. # workaround for http://trac.wxwidgets.org/ticket/13888
  348. if sys.platform == 'darwin':
  349. parent.SetToolBar(self)
  350. self.InitToolbar(self._toolbarData())
  351. # realize the toolbar
  352. self.Realize()
  353. def _toolbarData(self):
  354. """Toolbar data"""
  355. icons = {
  356. 'open': MetaIcon(img='open',
  357. label=_('Open (Ctrl+O)')),
  358. 'save': MetaIcon(img='save',
  359. label=_('Save (Ctrl+S)')),
  360. 'run': MetaIcon(img='execute',
  361. label=_('Run (Ctrl+R)')),
  362. }
  363. return self._getToolbarData((('open', icons['open'],
  364. self.parent.OnOpen),
  365. ('save', icons['save'],
  366. self.parent.OnSave),
  367. (None, ),
  368. ('run', icons['run'],
  369. self.parent.OnRun),
  370. (None, ),
  371. ("help", BaseIcons['help'],
  372. self.parent.OnHelp),
  373. ))
  374. class PyEditFrame(wx.Frame):
  375. # GUI class and a lot of trampoline methods
  376. # pylint: disable=missing-docstring
  377. # pylint: disable=too-many-public-methods
  378. # pylint: disable=invalid-name
  379. def __init__(self, parent, giface, id=wx.ID_ANY,
  380. title=_("GRASS GIS Simple Python Editor"),
  381. **kwargs):
  382. wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs)
  383. self.parent = parent
  384. filename = os.path.join(
  385. globalvar.WXGUIDIR, 'xml', 'menudata_pyedit.xml')
  386. self.menubar = Menu(
  387. parent=self,
  388. model=MenuTreeModelBuilder(filename).GetModel(separators=True))
  389. self.SetMenuBar(self.menubar)
  390. self.toolbar = PyEditToolbar(parent=self)
  391. # workaround for http://trac.wxwidgets.org/ticket/13888
  392. # TODO: toolbar is set in toolbar and here
  393. if sys.platform != 'darwin':
  394. self.SetToolBar(self.toolbar)
  395. self.panel = PyStc(parent=self)
  396. self.controller = PyEditController(
  397. panel=self.panel, guiparent=self, giface=giface)
  398. # don't start with an empty page
  399. self.panel.SetText(script_template())
  400. sizer = wx.BoxSizer(wx.VERTICAL)
  401. sizer.Add(item=self.panel, proportion=1,
  402. flag=wx.EXPAND)
  403. sizer.Fit(self)
  404. sizer.SetSizeHints(self)
  405. self.SetSizer(sizer)
  406. self.Fit()
  407. self.SetAutoLayout(True)
  408. self.Layout()
  409. # TODO: it would be nice if we can pass the controller to the menu
  410. # might not be possible on the side of menu
  411. # here we use self and self.controller which might make it harder
  412. def OnOpen(self, *args, **kwargs):
  413. self.controller.OnOpen(*args, **kwargs)
  414. def OnSave(self, *args, **kwargs):
  415. self.controller.OnSave(*args, **kwargs)
  416. def OnClose(self, *args, **kwargs):
  417. # saves without asking if we have an open file
  418. self.controller.OnSave(*args, **kwargs)
  419. self.Destroy()
  420. def OnRun(self, *args, **kwargs):
  421. # save without asking
  422. self.controller.OnRun(*args, **kwargs)
  423. def OnHelp(self, *args, **kwargs):
  424. # save without asking
  425. self.controller.OnHelp(*args, **kwargs)
  426. def OnSimpleScriptTemplate(self, *args, **kwargs):
  427. self.controller.SetScriptTemplate(*args, **kwargs)
  428. def OnGrassModuleTemplate(self, *args, **kwargs):
  429. self.controller.SetModuleTemplate(*args, **kwargs)
  430. def OnSimpleScriptExample(self, *args, **kwargs):
  431. self.controller.SetScriptExample(*args, **kwargs)
  432. def OnGrassModuleExample(self, *args, **kwargs):
  433. self.controller.SetModuleExample(*args, **kwargs)
  434. def OnPythonHelp(self, *args, **kwargs):
  435. self.controller.OnPythonHelp(*args, **kwargs)
  436. def OnModulesHelp(self, *args, **kwargs):
  437. self.controller.OnModulesHelp(*args, **kwargs)
  438. def OnAddonsHelp(self, *args, **kwargs):
  439. self.controller.OnAddonsHelp(*args, **kwargs)
  440. def OnSupport(self, *args, **kwargs):
  441. self.controller.OnSupport(*args, **kwargs)
  442. def main():
  443. """Test application (potentially useful as g.gui.pyedit)"""
  444. app = wx.App()
  445. giface = StandaloneGrassInterface()
  446. simple_editor = PyEditFrame(parent=None, giface=giface)
  447. simple_editor.SetSize((600, 800))
  448. simple_editor.Show()
  449. app.MainLoop()
  450. if __name__ == '__main__':
  451. main()