pyedit.py 25 KB

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