pyedit.py 25 KB

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