pyedit.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. # needed 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 gui_core.pystc import PyStc
  24. from core import globalvar
  25. from core.menutree import MenuTreeModelBuilder
  26. from gui_core.menu import Menu
  27. from gui_core.toolbars import BaseToolbar, BaseIcons
  28. from icons.icon import MetaIcon
  29. from core.debug import Debug
  30. # TODO: add validation: call/import pep8 (error message if not available)
  31. # TODO: run with parameters (alternatively, just use console or GUI)
  32. # TODO: add more examples (better separate file)
  33. # TODO: add test for templates and examples
  34. # TODO: add pep8 test for templates and examples
  35. # TODO: add snippets?
  36. def script_template():
  37. """The most simple script which runs and gives something"""
  38. return r"""#!/usr/bin/env python
  39. import grass.script as gscript
  40. def main():
  41. gscript.run_command('g.region', flags='p')
  42. if __name__ == '__main__':
  43. main()
  44. """
  45. def module_template():
  46. """Template from which to start writing GRASS module"""
  47. import getpass
  48. author = getpass.getuser()
  49. properties = {}
  50. properties['name'] = 'module name'
  51. properties['author'] = author
  52. properties['description'] = 'Module description'
  53. output = StringIO()
  54. # header
  55. output.write(
  56. r"""#!/usr/bin/env python
  57. #
  58. #%s
  59. #
  60. # MODULE: %s
  61. #
  62. # AUTHOR(S): %s
  63. #
  64. # PURPOSE: %s
  65. #
  66. # DATE: %s
  67. #
  68. #%s
  69. """ % ('#' * 72,
  70. EncodeString(properties['name']),
  71. EncodeString(properties['author']),
  72. EncodeString('\n# '.join(properties['description'].splitlines())),
  73. time.asctime(),
  74. '#' * 72))
  75. # UI
  76. output.write(
  77. r"""
  78. #%%module
  79. #%% description: %s
  80. #%%end
  81. """ % (EncodeString(' '.join(properties['description'].splitlines()))))
  82. # import modules
  83. output.write(
  84. r"""
  85. import sys
  86. import os
  87. import atexit
  88. import grass.script as gscript
  89. """)
  90. # cleanup()
  91. output.write(
  92. r"""
  93. RAST_REMOVE = []
  94. def cleanup():
  95. """)
  96. output.write(
  97. r""" gscript.run_command('g.remove', flags='f', type='raster',
  98. name=RAST_REMOVE)
  99. """)
  100. output.write("\ndef main():\n")
  101. output.write(
  102. r""" options, flags = gscript.parser()
  103. gscript.run_command('g.remove', flags='f', type='raster',
  104. name=RAST_REMOVE)
  105. """)
  106. output.write("\n return 0\n")
  107. output.write(
  108. r"""
  109. if __name__ == "__main__":
  110. atexit.register(cleanup)
  111. sys.exit(main())
  112. """)
  113. return output.getvalue()
  114. def script_example():
  115. """Example of a simple script"""
  116. return r"""#!/usr/bin/env python
  117. import grass.script as gscript
  118. def main():
  119. input_raster = 'elevation'
  120. output_raster = 'high_areas'
  121. stats = gscript.parse_command('r.univar', map='elevation', flags='g')
  122. raster_mean = float(stats['mean'])
  123. raster_stddev = float(stats['stddev'])
  124. raster_high = raster_mean + raster_stddev
  125. gscript.mapcalc('{r} = {a} > {m}'.format(r=output_raster, a=input_raster,
  126. m=raster_high))
  127. if __name__ == "__main__":
  128. main()
  129. """
  130. def module_example():
  131. """Example of a GRASS module"""
  132. return r"""#!/usr/bin/env python
  133. #%module
  134. #% description: Adds the values of two rasters (A + B)
  135. #% keyword: raster
  136. #% keyword: algebra
  137. #% keyword: sum
  138. #%end
  139. #%option G_OPT_R_INPUT
  140. #% key: araster
  141. #% description: Name of input raster A in an expression A + B
  142. #%end
  143. #%option G_OPT_R_INPUT
  144. #% key: braster
  145. #% description: Name of input raster B in an expression A + B
  146. #%end
  147. #%option G_OPT_R_OUTPUT
  148. #%end
  149. import sys
  150. import grass.script as gscript
  151. def main():
  152. options, flags = gscript.parser()
  153. araster = options['araster']
  154. braster = options['braster']
  155. output = options['output']
  156. gscript.mapcalc('{r} = {a} + {b}'.format(r=output, a=araster, b=braster))
  157. return 0
  158. if __name__ == "__main__":
  159. sys.exit(main())
  160. """
  161. def module_error_handling_example():
  162. """Example of a GRASS module"""
  163. return r"""#!/usr/bin/env python
  164. #%module
  165. #% description: Selects values from raster above value of mean plus standard deviation
  166. #% keyword: raster
  167. #% keyword: select
  168. #% keyword: standard deviation
  169. #%end
  170. #%option G_OPT_R_INPUT
  171. #%end
  172. #%option G_OPT_R_OUTPUT
  173. #%end
  174. import sys
  175. import grass.script as gscript
  176. from grass.exceptions import CalledModuleError
  177. def main():
  178. options, flags = gscript.parser()
  179. input_raster = options['input']
  180. output_raster = options['output']
  181. try:
  182. stats = gscript.parse_command('r.univar', map=input_raster, flags='g')
  183. except CalledModuleError as e:
  184. gscript.fatal('{}'.format(e))
  185. raster_mean = float(stats['mean'])
  186. raster_stddev = float(stats['stddev'])
  187. raster_high = raster_mean + raster_stddev
  188. gscript.mapcalc('{r} = {i} > {v}'.format(r=output_raster, i=input_raster,
  189. v=raster_high))
  190. return 0
  191. if __name__ == "__main__":
  192. sys.exit(main())
  193. """
  194. def open_url(url):
  195. import webbrowser
  196. webbrowser.open(url)
  197. class PyEditController(object):
  198. # using the naming GUI convention, change for controller?
  199. # pylint: disable=invalid-name
  200. def __init__(self, panel, guiparent, giface):
  201. """Simple editor, this class could be a pure controller"""
  202. self.guiparent = guiparent
  203. self.giface = giface
  204. self.body = panel
  205. self.filename = None
  206. self.tempfile = None # bool, make them strings for better code
  207. self.overwrite = False
  208. self.parameters = None
  209. def OnRun(self, event):
  210. """Run Python script"""
  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. # always save automatically before running
  227. fd = open(self.filename, "w")
  228. try:
  229. fd.write(self.body.GetText())
  230. finally:
  231. fd.close()
  232. # set executable file
  233. # (not sure if needed every time but useful for opened files)
  234. os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)
  235. # run in console as other modules, avoid Python shell which
  236. # carries variables over to the next execution
  237. env = os.environ.copy()
  238. if self.overwrite:
  239. env['GRASS_OVERWRITE'] = '1'
  240. cmd = [fd.name]
  241. if self.parameters:
  242. cmd.extend(self.parameters)
  243. self.giface.RunCmd(cmd, env=env)
  244. def SaveAs(self):
  245. """Save python script to file"""
  246. if self.tempfile:
  247. try_remove(self.filename)
  248. self.tempfile = False
  249. filename = None
  250. dlg = wx.FileDialog(parent=self.guiparent,
  251. message=_("Choose file to save"),
  252. defaultDir=os.getcwd(),
  253. wildcard=_("Python script (*.py)|*.py"),
  254. style=wx.FD_SAVE)
  255. if dlg.ShowModal() == wx.ID_OK:
  256. filename = dlg.GetPath()
  257. if not filename:
  258. return
  259. # check for extension
  260. if filename[-3:] != ".py":
  261. filename += ".py"
  262. if os.path.exists(filename):
  263. dlg = wx.MessageDialog(
  264. parent=self.guiparent,
  265. message=_("File <%s> already exists. "
  266. "Do you want to overwrite this file?") % filename,
  267. caption=_("Save file"),
  268. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  269. if dlg.ShowModal() == wx.ID_NO:
  270. dlg.Destroy()
  271. return
  272. dlg.Destroy()
  273. self.filename = filename
  274. self.tempfile = False
  275. self.Save()
  276. def Save(self):
  277. """Save current content to a file and set executable permissions"""
  278. assert self.filename
  279. fd = open(self.filename, "w")
  280. try:
  281. fd.write(self.body.GetText())
  282. finally:
  283. fd.close()
  284. # executable file
  285. os.chmod(self.filename, stat.S_IRWXU | stat.S_IWUSR)
  286. def OnSave(self, event):
  287. """Save python script to file
  288. Just save if file already specified, save as action otherwise.
  289. """
  290. if self.filename and not self.tempfile:
  291. self.Save()
  292. else:
  293. self.SaveAs()
  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. """Handle open event but ask about replacing content first"""
  318. if self.CanReplaceContent('file'):
  319. self.Open()
  320. def IsEmpty(self):
  321. """Check if python script is empty"""
  322. return len(self.body.GetText()) == 0
  323. def IsContentValuable(self):
  324. """Check if content of the editor is valuable to user
  325. Used for example to check if content should be saved before closing.
  326. The content is not valuable for example if it already saved in a file.
  327. """
  328. Debug.msg(2, "pyedit IsContentValuable? empty={}, modified={}",
  329. self.IsEmpty(), self.IsModified())
  330. return not self.IsEmpty() and self.IsModified()
  331. def SetScriptTemplate(self, event):
  332. if self.CanReplaceContent('template'):
  333. self.body.SetText(script_template())
  334. def SetModuleTemplate(self, event):
  335. if self.CanReplaceContent('template'):
  336. self.body.SetText(module_template())
  337. def SetScriptExample(self, event):
  338. if self.CanReplaceContent('example'):
  339. self.body.SetText(script_example())
  340. def SetModuleExample(self, event):
  341. if self.CanReplaceContent('example'):
  342. self.body.SetText(module_example())
  343. def SetModuleErrorHandlingExample(self, event):
  344. if self.CanReplaceContent('example'):
  345. self.body.SetText(module_error_handling_example())
  346. def CanReplaceContent(self, by_message):
  347. """Check with user if we can replace content by something else
  348. Asks user if replacement is OK depending on the state of the editor.
  349. Use before replacing all editor content by some other text.
  350. :param by_message: message used to ask user if it is OK to replace
  351. the content with something else; special values are 'template',
  352. 'example' and 'file' which will use predefined messages, otherwise
  353. a translatable, user visible string should be used.
  354. """
  355. if by_message == 'template':
  356. message = _("Replace the content by the template?")
  357. elif by_message == 'example':
  358. message = _("Replace the content by the example?")
  359. elif by_message == 'file':
  360. message = _("Replace the current content by the file content?")
  361. else:
  362. message = by_message
  363. if self.IsContentValuable():
  364. dlg = wx.MessageDialog(
  365. parent=self.guiparent, message=message,
  366. caption=_("Replace content"),
  367. style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  368. if dlg.ShowModal() == wx.ID_NO:
  369. dlg.Destroy()
  370. return False
  371. dlg.Destroy()
  372. return True
  373. def OnSetParameters(self, event):
  374. """Handle setting CLI parameters for the script (asks for input)"""
  375. dlg = wx.TextEntryDialog(
  376. parent=self.guiparent,
  377. caption=_("Set parameters for the script"),
  378. message=_("Specify command line parameters for the script separated by spaces:"),
  379. )
  380. if self.parameters:
  381. dlg.SetValue(" ".join(self.parameters))
  382. # TODO: modality might not be needed here if we bind the events
  383. if dlg.ShowModal() == wx.ID_OK:
  384. text = dlg.GetValue().strip()
  385. # TODO: split in the same way as in console
  386. if text:
  387. self.parameters = text.split()
  388. else:
  389. self.parameters = None
  390. def OnHelp(self, event):
  391. # inspired by g.manual but simple not using GRASS_HTML_BROWSER
  392. # not using g.manual because it does not show
  393. entry = 'libpython/script_intro.html'
  394. major, minor, patch = gscript.version()['version'].split('.')
  395. url = 'http://grass.osgeo.org/grass%s%s/manuals/%s' % (
  396. major, minor, entry)
  397. open_url(url)
  398. def OnPythonHelp(self, event):
  399. url = 'https://docs.python.org/%s/tutorial/' % sys.version_info[0]
  400. open_url(url)
  401. def OnModulesHelp(self, event):
  402. self.giface.Help('full_index')
  403. def OnSubmittingHelp(self, event):
  404. open_url('https://trac.osgeo.org/grass/wiki/Submitting/Python')
  405. def OnAddonsHelp(self, event):
  406. open_url('https://grass.osgeo.org/development/code-submission/')
  407. def OnSupport(self, event):
  408. open_url('https://grass.osgeo.org/support/')
  409. class PyEditToolbar(BaseToolbar):
  410. # GUI class
  411. # pylint: disable=too-many-ancestors
  412. # pylint: disable=too-many-public-methods
  413. """PyEdit toolbar"""
  414. def __init__(self, parent):
  415. BaseToolbar.__init__(self, parent)
  416. self.icons = {
  417. 'open': MetaIcon(img='open',
  418. label=_('Open (Ctrl+O)')),
  419. 'save': MetaIcon(img='save',
  420. label=_('Save (Ctrl+S)')),
  421. 'run': MetaIcon(img='execute',
  422. label=_('Run (Ctrl+R)')),
  423. # TODO: better icons for overwrite modes
  424. 'overwriteTrue': MetaIcon(img='locked',
  425. label=_('Activate overwrite')),
  426. 'overwriteFalse': MetaIcon(img='unlocked',
  427. label=_('Deactive overwrite')),
  428. }
  429. # workaround for http://trac.wxwidgets.org/ticket/13888
  430. if sys.platform == 'darwin':
  431. parent.SetToolBar(self)
  432. self.InitToolbar(self._toolbarData())
  433. # realize the toolbar
  434. self.Realize()
  435. def _toolbarData(self):
  436. """Toolbar data"""
  437. return self._getToolbarData((('open', self.icons['open'],
  438. self.parent.OnOpen),
  439. ('save', self.icons['save'],
  440. self.parent.OnSave),
  441. (None, ),
  442. ('run', self.icons['run'],
  443. self.parent.OnRun),
  444. ('overwrite', self.icons['overwriteTrue'],
  445. self.OnSetOverwrite, wx.ITEM_CHECK),
  446. (None, ),
  447. ("help", BaseIcons['help'],
  448. self.parent.OnHelp),
  449. ))
  450. # TODO: add overwrite also to the menu and sync with toolbar
  451. def OnSetOverwrite(self, event):
  452. if self.GetToolState(self.overwrite):
  453. self.SetToolNormalBitmap(self.overwrite,
  454. self.icons['overwriteFalse'].GetBitmap())
  455. self.SetToolShortHelp(self.overwrite,
  456. self.icons['overwriteFalse'].GetLabel())
  457. self.parent.overwrite = True
  458. else:
  459. self.SetToolNormalBitmap(self.overwrite,
  460. self.icons['overwriteTrue'].GetBitmap())
  461. self.SetToolShortHelp(self.overwrite,
  462. self.icons['overwriteTrue'].GetLabel())
  463. self.parent.overwrite = False
  464. class PyEditFrame(wx.Frame):
  465. # GUI class and a lot of trampoline methods
  466. # pylint: disable=missing-docstring
  467. # pylint: disable=too-many-public-methods
  468. # pylint: disable=invalid-name
  469. def __init__(self, parent, giface, id=wx.ID_ANY,
  470. title=_("GRASS GIS Simple Python Editor"),
  471. **kwargs):
  472. wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs)
  473. self.parent = parent
  474. filename = os.path.join(
  475. globalvar.WXGUIDIR, 'xml', 'menudata_pyedit.xml')
  476. self.menubar = Menu(
  477. parent=self,
  478. model=MenuTreeModelBuilder(filename).GetModel(separators=True))
  479. self.SetMenuBar(self.menubar)
  480. self.toolbar = PyEditToolbar(parent=self)
  481. # workaround for http://trac.wxwidgets.org/ticket/13888
  482. # TODO: toolbar is set in toolbar and here
  483. if sys.platform != 'darwin':
  484. self.SetToolBar(self.toolbar)
  485. self.panel = PyStc(parent=self)
  486. self.controller = PyEditController(
  487. panel=self.panel, guiparent=self, giface=giface)
  488. # don't start with an empty page
  489. self.panel.SetText(script_template())
  490. sizer = wx.BoxSizer(wx.VERTICAL)
  491. sizer.Add(self.panel, proportion=1,
  492. flag=wx.EXPAND)
  493. sizer.Fit(self)
  494. sizer.SetSizeHints(self)
  495. self.SetSizer(sizer)
  496. self.Fit()
  497. self.SetAutoLayout(True)
  498. self.Layout()
  499. self.Bind(wx.EVT_CLOSE, self.OnClose)
  500. # TODO: it would be nice if we can pass the controller to the menu
  501. # might not be possible on the side of menu
  502. # here we use self and self.controller which might make it harder
  503. def OnOpen(self, *args, **kwargs):
  504. self.controller.OnOpen(*args, **kwargs)
  505. def OnSave(self, *args, **kwargs):
  506. self.controller.OnSave(*args, **kwargs)
  507. def OnClose(self, *args, **kwargs):
  508. # this will be often true because PyStc is using EVT_KEY_DOWN
  509. # to say if it was modified, not actual user change in text
  510. if self.controller.IsContentValuable():
  511. self.controller.OnSave(*args, **kwargs)
  512. self.Destroy()
  513. def OnRun(self, *args, **kwargs):
  514. # save without asking
  515. self.controller.OnRun(*args, **kwargs)
  516. def OnHelp(self, *args, **kwargs):
  517. self.controller.OnHelp(*args, **kwargs)
  518. def OnSimpleScriptTemplate(self, *args, **kwargs):
  519. self.controller.SetScriptTemplate(*args, **kwargs)
  520. def OnGrassModuleTemplate(self, *args, **kwargs):
  521. self.controller.SetModuleTemplate(*args, **kwargs)
  522. def OnSimpleScriptExample(self, *args, **kwargs):
  523. self.controller.SetScriptExample(*args, **kwargs)
  524. def OnGrassModuleExample(self, *args, **kwargs):
  525. self.controller.SetModuleExample(*args, **kwargs)
  526. def OnGrassModuleErrorHandlingExample(self, *args, **kwargs):
  527. self.controller.SetModuleErrorHandlingExample(*args, **kwargs)
  528. def OnPythonHelp(self, *args, **kwargs):
  529. self.controller.OnPythonHelp(*args, **kwargs)
  530. def OnModulesHelp(self, *args, **kwargs):
  531. self.controller.OnModulesHelp(*args, **kwargs)
  532. def OnSubmittingHelp(self, *args, **kwargs):
  533. self.controller.OnSubmittingHelp(*args, **kwargs)
  534. def OnAddonsHelp(self, *args, **kwargs):
  535. self.controller.OnAddonsHelp(*args, **kwargs)
  536. def OnSupport(self, *args, **kwargs):
  537. self.controller.OnSupport(*args, **kwargs)
  538. def _get_overwrite(self):
  539. return self.controller.overwrite
  540. def _set_overwrite(self, overwrite):
  541. self.controller.overwrite = overwrite
  542. overwrite = property(_get_overwrite, _set_overwrite,
  543. doc="Tells if overwrite should be used")
  544. def OnSetParameters(self, *args, **kwargs):
  545. self.controller.OnSetParameters(*args, **kwargs)
  546. def main():
  547. """Test application (potentially useful as g.gui.pyedit)"""
  548. from core.giface import StandaloneGrassInterface
  549. app = wx.App()
  550. giface = StandaloneGrassInterface()
  551. simple_editor = PyEditFrame(parent=None, giface=giface)
  552. simple_editor.SetSize((600, 800))
  553. simple_editor.Show()
  554. app.MainLoop()
  555. if __name__ == '__main__':
  556. main()