goutput.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. """!
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GConsole
  7. - goutput::GStdout
  8. - goutput::GStderr
  9. - goutput::GStc
  10. (C) 2007-2012 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Martin Landa <landa.martin gmail.com>
  15. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  16. """
  17. import os
  18. import sys
  19. import re
  20. import textwrap
  21. import time
  22. import threading
  23. import Queue
  24. import codecs
  25. import locale
  26. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  27. import wx
  28. from wx import stc
  29. from wx.lib.newevent import NewEvent
  30. import grass.script as grass
  31. from grass.script import task as gtask
  32. from core import globalvar
  33. from core import utils
  34. from core.gcmd import CommandThread, GMessage, GError, GException, EncodeString
  35. from core.events import gShowNotification, gMapCreated
  36. from gui_core.forms import GUI
  37. from gui_core.prompt import GPromptSTC, EVT_GPROMPT_RUN_CMD
  38. from core.debug import Debug
  39. from core.settings import UserSettings
  40. from gui_core.widgets import SearchModuleWidget, EVT_MODULE_SELECTED
  41. from core.modulesdata import ModulesData
  42. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  43. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  44. wxCmdRun, EVT_CMD_RUN = NewEvent()
  45. wxCmdDone, EVT_CMD_DONE = NewEvent()
  46. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  47. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  48. GC_EMPTY = 0
  49. GC_SEARCH = 1
  50. GC_PROMPT = 2
  51. def GrassCmd(cmd, env = None, stdout = None, stderr = None):
  52. """!Return GRASS command thread"""
  53. return CommandThread(cmd, env = env,
  54. stdout = stdout, stderr = stderr)
  55. class CmdThread(threading.Thread):
  56. """!Thread for GRASS commands"""
  57. requestId = 0
  58. def __init__(self, receiver, requestQ = None, resultQ = None, **kwds):
  59. """!
  60. @param receiver event receiver (used in PostEvent)
  61. """
  62. threading.Thread.__init__(self, **kwds)
  63. if requestQ is None:
  64. self.requestQ = Queue.Queue()
  65. else:
  66. self.requestQ = requestQ
  67. if resultQ is None:
  68. self.resultQ = Queue.Queue()
  69. else:
  70. self.resultQ = resultQ
  71. self.setDaemon(True)
  72. self.receiver = receiver
  73. self._want_abort_all = False
  74. self.start()
  75. def RunCmd(self, *args, **kwds):
  76. """!Run command in queue
  77. @param args unnamed command arguments
  78. @param kwds named command arguments
  79. @return request id in queue
  80. """
  81. CmdThread.requestId += 1
  82. self.requestCmd = None
  83. self.requestQ.put((CmdThread.requestId, args, kwds))
  84. return CmdThread.requestId
  85. def SetId(self, id):
  86. """!Set starting id"""
  87. CmdThread.requestId = id
  88. def run(self):
  89. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  90. while True:
  91. requestId, args, kwds = self.requestQ.get()
  92. for key in ('callable', 'onDone', 'onPrepare', 'userData'):
  93. if key in kwds:
  94. vars()[key] = kwds[key]
  95. del kwds[key]
  96. else:
  97. vars()[key] = None
  98. if not vars()['callable']:
  99. vars()['callable'] = GrassCmd
  100. requestTime = time.time()
  101. # prepare
  102. event = wxCmdPrepare(cmd = args[0],
  103. time = requestTime,
  104. pid = requestId,
  105. onPrepare = vars()['onPrepare'],
  106. userData = vars()['userData'])
  107. wx.PostEvent(self.receiver, event)
  108. # run command
  109. event = wxCmdRun(cmd = args[0],
  110. pid = requestId)
  111. wx.PostEvent(self.receiver, event)
  112. time.sleep(.1)
  113. self.requestCmd = vars()['callable'](*args, **kwds)
  114. if self._want_abort_all:
  115. self.requestCmd.abort()
  116. if self.requestQ.empty():
  117. self._want_abort_all = False
  118. self.resultQ.put((requestId, self.requestCmd.run()))
  119. try:
  120. returncode = self.requestCmd.module.returncode
  121. except AttributeError:
  122. returncode = 0 # being optimistic
  123. try:
  124. aborted = self.requestCmd.aborted
  125. except AttributeError:
  126. aborted = False
  127. time.sleep(.1)
  128. # set default color table for raster data
  129. if UserSettings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'enabled') and \
  130. args[0][0][:2] == 'r.':
  131. colorTable = UserSettings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'selection')
  132. mapName = None
  133. if args[0][0] == 'r.mapcalc':
  134. try:
  135. mapName = args[0][1].split('=', 1)[0].strip()
  136. except KeyError:
  137. pass
  138. else:
  139. moduleInterface = GUI(show = None).ParseCommand(args[0])
  140. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  141. if outputParam and outputParam['prompt'] == 'raster':
  142. mapName = outputParam['value']
  143. if mapName:
  144. argsColor = list(args)
  145. argsColor[0] = [ 'r.colors',
  146. 'map=%s' % mapName,
  147. 'color=%s' % colorTable ]
  148. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  149. self.resultQ.put((requestId, self.requestCmdColor.run()))
  150. event = wxCmdDone(cmd = args[0],
  151. aborted = aborted,
  152. returncode = returncode,
  153. time = requestTime,
  154. pid = requestId,
  155. onDone = vars()['onDone'],
  156. userData = vars()['userData'])
  157. # send event
  158. wx.PostEvent(self.receiver, event)
  159. def abort(self, abortall = True):
  160. """!Abort command(s)"""
  161. if abortall:
  162. self._want_abort_all = True
  163. self.requestCmd.abort()
  164. if self.requestQ.empty():
  165. self._want_abort_all = False
  166. # Occurs when some new text appears.
  167. # Text priority is specified by priority attribute.
  168. # Priority is 1 (lowest), 2, 3 (highest);
  169. # value 0 is currently not used and probably will not be used.
  170. # In theory, it can be used when text is completely uninteresting.
  171. # It is similar to wx.EVT_TEXT.
  172. # However, the new text or the whole text are not event attributes.
  173. gOutputText, EVT_OUTPUT_TEXT = NewEvent()
  174. # Occurs when ignored command is called.
  175. # Attribute cmd contains command (as a list).
  176. gIgnoredCmdRun, EVT_IGNORED_CMD_RUN = NewEvent()
  177. class GConsole(wx.SplitterWindow):
  178. """!Create and manage output console for commands run by GUI.
  179. """
  180. def __init__(self, parent, margin = False,
  181. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  182. gcstyle = GC_EMPTY,
  183. ignoredCmdPattern = None,
  184. **kwargs):
  185. """!
  186. @param parent gui parent
  187. @param margin use margin in output pane (GStc)
  188. @param style wx.SplitterWindow style
  189. @param gcstyle GConsole style
  190. (GC_EMPTY, GC_PROMPT to show command prompt,
  191. GC_SEARCH to show search widget)
  192. @param ignoredCmdPattern regular expression specifying commads
  193. to be ignored (e.g. @c '^d\..*' for display commands)
  194. """
  195. wx.SplitterWindow.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  196. self.SetName("GConsole")
  197. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  198. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  199. # initialize variables
  200. self.parent = parent # GMFrame | CmdPanel | ?
  201. self._gcstyle = gcstyle
  202. self.lineWidth = 80
  203. self._ignoredCmdPattern = ignoredCmdPattern
  204. # create queues
  205. self.requestQ = Queue.Queue()
  206. self.resultQ = Queue.Queue()
  207. # progress bar
  208. self.progressbar = wx.Gauge(parent = self.panelOutput, id = wx.ID_ANY,
  209. range = 100, pos = (110, 50), size = (-1, 25),
  210. style = wx.GA_HORIZONTAL)
  211. self.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  212. # text control for command output
  213. self.cmdOutput = GStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  214. wrap = None)
  215. self.cmdOutputTimer = wx.Timer(self.cmdOutput, id = wx.ID_ANY)
  216. self.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  217. self.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  218. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  219. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  220. # information about available modules
  221. modulesData = ModulesData()
  222. # search & command prompt
  223. # move to the if below
  224. # search depends on cmd prompt
  225. self.cmdPrompt = GPromptSTC(parent = self, modulesData = modulesData)
  226. self.cmdPrompt.Bind(EVT_GPROMPT_RUN_CMD,
  227. lambda event: self.RunCmd(command = event.cmd))
  228. if not self._gcstyle & GC_PROMPT:
  229. self.cmdPrompt.Hide()
  230. if self._gcstyle & GC_SEARCH:
  231. self.infoCollapseLabelExp = _("Click here to show search module engine")
  232. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  233. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  234. label = self.infoCollapseLabelExp,
  235. style = wx.CP_DEFAULT_STYLE |
  236. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  237. self.MakeSearchPaneContent(self.searchPane.GetPane(), modulesData)
  238. self.searchPane.Collapse(True)
  239. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  240. self.search.Bind(EVT_MODULE_SELECTED,
  241. lambda event:
  242. self.cmdPrompt.SetTextAndFocus(event.name + ' '))
  243. else:
  244. self.search = None
  245. # stream redirection
  246. self.cmdStdOut = GStdout(self)
  247. self.cmdStdErr = GStderr(self)
  248. # thread
  249. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  250. self.outputBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  251. label = " %s " % _("Output window"))
  252. if self._gcstyle & GC_PROMPT:
  253. cmdLabel = _("Command prompt")
  254. else:
  255. cmdLabel = _("Command")
  256. self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  257. label = " %s " % cmdLabel)
  258. # buttons
  259. self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  260. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  261. self.btnCmdClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  262. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  263. self.btnOutputSave = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
  264. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  265. self.btnCmdAbort = wx.Button(parent = self.panelOutput, id = wx.ID_STOP)
  266. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  267. self.btnCmdAbort.Enable(False)
  268. self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
  269. label = _("&Protocol"),
  270. size = self.btnCmdClear.GetSize())
  271. self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into file; "
  272. "content saved when switching off."))
  273. if not self._gcstyle & GC_PROMPT:
  274. self.btnCmdClear.Hide()
  275. self.btnCmdProtocol.Hide()
  276. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  277. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  278. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  279. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  280. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  281. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  282. self._layout()
  283. def _layout(self):
  284. """!Do layout"""
  285. outputSizer = wx.BoxSizer(wx.VERTICAL)
  286. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  287. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  288. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  289. if self._gcstyle & GC_PROMPT:
  290. promptSizer = wx.BoxSizer(wx.VERTICAL)
  291. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  292. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  293. if self._gcstyle & GC_SEARCH:
  294. outputSizer.Add(item = self.searchPane, proportion = 0,
  295. flag = wx.EXPAND | wx.ALL, border = 3)
  296. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  297. flag = wx.EXPAND | wx.ALL, border = 3)
  298. outputSizer.Add(item = self.progressbar, proportion = 0,
  299. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  300. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  301. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  302. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  303. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  304. cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
  305. flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  306. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  307. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  308. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  309. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  310. if self._gcstyle & GC_PROMPT:
  311. proportion = (2, 3)
  312. else:
  313. proportion = (1, 1)
  314. btnSizer.Add(item = outBtnSizer, proportion = proportion[0],
  315. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  316. btnSizer.Add(item = cmdBtnSizer, proportion = proportion[1],
  317. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  318. outputSizer.Add(item = btnSizer, proportion = 0,
  319. flag = wx.EXPAND)
  320. outputSizer.Fit(self)
  321. outputSizer.SetSizeHints(self)
  322. self.panelOutput.SetSizer(outputSizer)
  323. # eliminate gtk_widget_size_allocate() warnings
  324. outputSizer.SetVirtualSizeHints(self.panelOutput)
  325. if self._gcstyle & GC_PROMPT:
  326. promptSizer.Fit(self)
  327. promptSizer.SetSizeHints(self)
  328. self.panelPrompt.SetSizer(promptSizer)
  329. # split window
  330. if self._gcstyle & GC_PROMPT:
  331. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  332. else:
  333. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  334. self.Unsplit()
  335. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  336. self.SetSashGravity(1.0)
  337. # layout
  338. self.SetAutoLayout(True)
  339. self.Layout()
  340. def MakeSearchPaneContent(self, pane, modulesData):
  341. """!Create search pane"""
  342. border = wx.BoxSizer(wx.VERTICAL)
  343. self.search = SearchModuleWidget(parent = pane,
  344. modulesData = modulesData)
  345. border.Add(item = self.search, proportion = 0,
  346. flag = wx.EXPAND | wx.ALL, border = 1)
  347. pane.SetSizer(border)
  348. border.Fit(pane)
  349. def OnSearchPaneChanged(self, event):
  350. """!Collapse search module box"""
  351. if self.searchPane.IsExpanded():
  352. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  353. else:
  354. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  355. self.panelOutput.Layout()
  356. self.panelOutput.SendSizeEvent()
  357. def GetPanel(self, prompt = True):
  358. """!Get panel
  359. @param prompt get prompt / output panel
  360. @return wx.Panel reference
  361. """
  362. if prompt:
  363. return self.panelPrompt
  364. return self.panelOutput
  365. def Redirect(self):
  366. """!Redirect stdout/stderr
  367. """
  368. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  369. # don't redirect when debugging is enabled
  370. sys.stdout = self.cmdStdOut
  371. sys.stderr = self.cmdStdErr
  372. else:
  373. enc = locale.getdefaultlocale()[1]
  374. if enc:
  375. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  376. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  377. else:
  378. sys.stdout = sys.__stdout__
  379. sys.stderr = sys.__stderr__
  380. def WriteLog(self, text, style = None, wrap = None,
  381. switchPage = False, priority = 1):
  382. """!Generic method for writing log message in
  383. given style
  384. @param line text line
  385. @param style text style (see GStc)
  386. @param stdout write to stdout or stderr
  387. @param switchPage for backward compatibility
  388. (replace by priority: False=1, True=2)
  389. @param priority priority of this message
  390. (0=no priority, 1=normal, 2=medium, 3=high)
  391. """
  392. self.cmdOutput.SetStyle()
  393. # documenting old behavior/implementation:
  394. # switch notebook if required
  395. if priority == 1:
  396. if switchPage:
  397. priority = 2
  398. event = gOutputText(priority = priority)
  399. wx.PostEvent(self, event)
  400. if not style:
  401. style = self.cmdOutput.StyleDefault
  402. # p1 = self.cmdOutput.GetCurrentPos()
  403. p1 = self.cmdOutput.GetEndStyled()
  404. # self.cmdOutput.GotoPos(p1)
  405. self.cmdOutput.DocumentEnd()
  406. for line in text.splitlines():
  407. # fill space
  408. if len(line) < self.lineWidth:
  409. diff = self.lineWidth - len(line)
  410. line += diff * ' '
  411. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  412. p2 = self.cmdOutput.GetCurrentPos()
  413. self.cmdOutput.StartStyling(p1, 0xff)
  414. self.cmdOutput.SetStyling(p2 - p1, style)
  415. self.cmdOutput.EnsureCaretVisible()
  416. def WriteCmdLog(self, line, pid = None, switchPage = True):
  417. """!Write message in selected style
  418. @param line message to be printed
  419. @param pid process pid or None
  420. @param switchPage True to switch page
  421. """
  422. if pid:
  423. line = '(' + str(pid) + ') ' + line
  424. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  425. def WriteWarning(self, line):
  426. """!Write message in warning style"""
  427. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  428. def WriteError(self, line):
  429. """!Write message in error style"""
  430. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  431. def RunCmd(self, command, compReg = True, switchPage = False, skipInterface = False,
  432. onDone = None, onPrepare = None, userData = None):
  433. """!Run command typed into console command prompt (GPrompt).
  434. @todo Document the other event.
  435. @todo Solve problem with the other event
  436. (now uses gOutputText event but there is no text,
  437. use onPrepare handler instead?)
  438. Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
  439. (according to ignoredCmdPattern) is run.
  440. For example, see layer manager which handles d.* on its own.
  441. @param command command given as a list (produced e.g. by utils.split())
  442. @param compReg True use computation region
  443. @param switchPage switch to output page
  444. @param skipInterface True to do not launch GRASS interface
  445. parser when command has no arguments given
  446. @param onDone function to be called when command is finished
  447. @param onPrepare function to be called before command is launched
  448. @param userData data defined for the command
  449. """
  450. if len(command) == 0:
  451. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  452. return
  453. # update history file
  454. env = grass.gisenv()
  455. try:
  456. filePath = os.path.join(env['GISDBASE'],
  457. env['LOCATION_NAME'],
  458. env['MAPSET'],
  459. '.bash_history')
  460. fileHistory = codecs.open(filePath, encoding = 'utf-8', mode = 'a')
  461. except IOError, e:
  462. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  463. {'filePath': filePath, 'error' : e },
  464. parent = self)
  465. fileHistory = None
  466. if fileHistory:
  467. try:
  468. fileHistory.write(' '.join(command) + os.linesep)
  469. finally:
  470. fileHistory.close()
  471. if command[0] in globalvar.grassCmd:
  472. # send GRASS command without arguments to GUI command interface
  473. # except ignored commands (event is emitted)
  474. if self._ignoredCmdPattern and \
  475. re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
  476. '--help' not in command:
  477. event = gIgnoredCmdRun(cmd = command)
  478. wx.PostEvent(self, event)
  479. return
  480. else:
  481. # other GRASS commands (r|v|g|...)
  482. try:
  483. task = GUI(show = None).ParseCommand(command)
  484. except GException, e:
  485. GError(parent = self,
  486. message = unicode(e),
  487. showTraceback = False)
  488. return
  489. hasParams = False
  490. if task:
  491. options = task.get_options()
  492. hasParams = options['params'] and options['flags']
  493. # check for <input>=-
  494. for p in options['params']:
  495. if p.get('prompt', '') == 'input' and \
  496. p.get('element', '') == 'file' and \
  497. p.get('age', 'new') == 'old' and \
  498. p.get('value', '') == '-':
  499. GError(parent = self,
  500. message = _("Unable to run command:\n%(cmd)s\n\n"
  501. "Option <%(opt)s>: read from standard input is not "
  502. "supported by wxGUI") % { 'cmd': ' '.join(command),
  503. 'opt': p.get('name', '') })
  504. return
  505. if len(command) == 1 and hasParams and \
  506. command[0] != 'v.krige':
  507. # no arguments given
  508. try:
  509. GUI(parent = self, lmgr = self.parent).ParseCommand(command)
  510. except GException, e:
  511. print >> sys.stderr, e
  512. return
  513. # documenting old behavior/implementation:
  514. # switch and focus if required
  515. # TODO: this probably should be run command event
  516. if switchPage:
  517. priority = 3
  518. event = gOutputText(priority = priority)
  519. wx.PostEvent(self, event)
  520. # activate computational region (set with g.region)
  521. # for all non-display commands.
  522. if compReg:
  523. tmpreg = os.getenv("GRASS_REGION")
  524. if "GRASS_REGION" in os.environ:
  525. del os.environ["GRASS_REGION"]
  526. # process GRASS command with argument
  527. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  528. onDone = onDone, onPrepare = onPrepare, userData = userData,
  529. env = os.environ.copy())
  530. self.cmdOutputTimer.Start(50)
  531. # deactivate computational region and return to display settings
  532. if compReg and tmpreg:
  533. os.environ["GRASS_REGION"] = tmpreg
  534. else:
  535. # Send any other command to the shell. Send output to
  536. # console output window
  537. if len(command) == 1 and not skipInterface:
  538. try:
  539. task = gtask.parse_interface(command[0])
  540. except:
  541. task = None
  542. else:
  543. task = None
  544. if task:
  545. # process GRASS command without argument
  546. GUI(parent = self, lmgr = self.parent).ParseCommand(command)
  547. else:
  548. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  549. onDone = onDone, onPrepare = onPrepare, userData = userData)
  550. self.cmdOutputTimer.Start(50)
  551. def OnOutputClear(self, event):
  552. """!Clear content of output window"""
  553. self.cmdOutput.SetReadOnly(False)
  554. self.cmdOutput.ClearAll()
  555. self.cmdOutput.SetReadOnly(True)
  556. self.progressbar.SetValue(0)
  557. def GetProgressBar(self):
  558. """!Return progress bar widget"""
  559. return self.progressbar
  560. def GetLog(self, err = False):
  561. """!Get widget used for logging
  562. @param err True to get stderr widget
  563. """
  564. if err:
  565. return self.cmdStdErr
  566. return self.cmdStdOut
  567. def OnOutputSave(self, event):
  568. """!Save (selected) text from output window to the file"""
  569. text = self.cmdOutput.GetSelectedText()
  570. if not text:
  571. text = self.cmdOutput.GetText()
  572. # add newline if needed
  573. if len(text) > 0 and text[-1] != '\n':
  574. text += '\n'
  575. dlg = wx.FileDialog(self, message = _("Save file as..."),
  576. defaultFile = "grass_cmd_output.txt",
  577. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  578. {'txt': _("Text files"), 'files': _("Files")},
  579. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  580. # Show the dialog and retrieve the user response. If it is the OK response,
  581. # process the data.
  582. if dlg.ShowModal() == wx.ID_OK:
  583. path = dlg.GetPath()
  584. try:
  585. output = open(path, "w")
  586. output.write(text)
  587. except IOError, e:
  588. GError(_("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {'path': path, 'error': e})
  589. finally:
  590. output.close()
  591. message = _("Commands output saved into '%s'") % path
  592. wx.PostEvent(self, gShowNotification(self.GetId(), message = message))
  593. dlg.Destroy()
  594. def GetCmd(self):
  595. """!Get running command or None"""
  596. return self.requestQ.get()
  597. def SetCopyingOfSelectedText(self, copy):
  598. """!Enable or disable copying of selected text in to clipboard.
  599. Effects prompt and output.
  600. @param copy True for enable, False for disable
  601. """
  602. if copy:
  603. self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  604. self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  605. else:
  606. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  607. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  608. def OnCmdOutput(self, event):
  609. """!Print command output
  610. Posts event EVT_OUTPUT_TEXT with priority attribute set to 1.
  611. """
  612. message = event.text
  613. type = event.type
  614. self.cmdOutput.AddStyledMessage(message, type)
  615. # documenting old behavior/implementation:
  616. # add elipses if not active
  617. event = gOutputText(priority = 1)
  618. wx.PostEvent(self, event)
  619. def OnCmdProgress(self, event):
  620. """!Update progress message info"""
  621. self.progressbar.SetValue(event.value)
  622. event.Skip()
  623. def CmdProtocolSave(self):
  624. """Save commands protocol into the file"""
  625. if not hasattr(self, 'cmdFileProtocol'):
  626. return # it should not happen
  627. try:
  628. output = open(self.cmdFileProtocol, "w")
  629. cmds = self.cmdPrompt.GetCommands()
  630. output.write('\n'.join(cmds))
  631. if len(cmds) > 0:
  632. output.write('\n')
  633. except IOError, e:
  634. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  635. {'filePath': self.cmdFileProtocol, 'error': e})
  636. finally:
  637. output.close()
  638. message = _("Commands protocol saved into '%s'") % self.cmdFileProtocol
  639. wx.PostEvent(self, gShowNotification(self.GetId(), message = message))
  640. del self.cmdFileProtocol
  641. def OnCmdProtocol(self, event = None):
  642. """!Save commands into file"""
  643. if not event.IsChecked():
  644. # stop capturing commands, save list of commands to the
  645. # protocol file
  646. self.CmdProtocolSave()
  647. else:
  648. # start capturing commands
  649. self.cmdPrompt.ClearCommands()
  650. # ask for the file
  651. dlg = wx.FileDialog(self, message = _("Save file as..."),
  652. defaultFile = "grass_cmd_protocol.txt",
  653. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  654. {'txt': _("Text files"), 'files': _("Files")},
  655. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  656. if dlg.ShowModal() == wx.ID_OK:
  657. self.cmdFileProtocol = dlg.GetPath()
  658. else:
  659. wx.CallAfter(self.btnCmdProtocol.SetValue, False)
  660. dlg.Destroy()
  661. event.Skip()
  662. def OnCmdAbort(self, event):
  663. """!Abort running command"""
  664. self.cmdThread.abort()
  665. event.Skip()
  666. def OnCmdRun(self, event):
  667. """!Run command"""
  668. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  669. self.btnCmdAbort.Enable()
  670. event.Skip()
  671. def OnCmdDone(self, event):
  672. """!Command done (or aborted)
  673. Posts event EVT_MAP_CREATED.
  674. """
  675. # Process results here
  676. try:
  677. ctime = time.time() - event.time
  678. if ctime < 60:
  679. stime = _("%d sec") % int(ctime)
  680. else:
  681. mtime = int(ctime / 60)
  682. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  683. 'sec' : int(ctime - (mtime * 60)) }
  684. except KeyError:
  685. # stopped deamon
  686. stime = _("unknown")
  687. if event.aborted:
  688. # Thread aborted (using our convention of None return)
  689. self.WriteLog(_('Please note that the data are left in inconsistent state '
  690. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  691. msg = _('Command aborted')
  692. else:
  693. msg = _('Command finished')
  694. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  695. self.btnCmdAbort.Enable(False)
  696. if event.onDone:
  697. event.onDone(cmd = event.cmd, returncode = event.returncode)
  698. self.progressbar.SetValue(0) # reset progress bar on '0%'
  699. self.cmdOutputTimer.Stop()
  700. if event.cmd[0] == 'g.gisenv':
  701. Debug.SetLevel()
  702. self.Redirect()
  703. # do nothing when no map added
  704. if event.returncode != 0 or event.aborted:
  705. event.Skip()
  706. return
  707. # find which maps were created
  708. try:
  709. task = GUI(show = None).ParseCommand(event.cmd)
  710. except GException, e:
  711. print >> sys.stderr, e
  712. task = None
  713. return
  714. for p in task.get_options()['params']:
  715. prompt = p.get('prompt', '')
  716. if prompt in ('raster', 'vector', '3d-raster') and \
  717. p.get('age', 'old') == 'new' and \
  718. p.get('value', None):
  719. name = p.get('value')
  720. if '@' not in name:
  721. name = name + '@' + grass.gisenv()['MAPSET']
  722. mapEvent = gMapCreated(self.GetId(),
  723. name = name, ltype = prompt, add = None)
  724. wx.PostEvent(self, mapEvent)
  725. event.Skip()
  726. def OnProcessPendingOutputWindowEvents(self, event):
  727. wx.GetApp().ProcessPendingEvents()
  728. def ResetFocus(self):
  729. """!Reset focus"""
  730. self.cmdPrompt.SetFocus()
  731. def GetPrompt(self):
  732. """!Get prompt"""
  733. return self.cmdPrompt
  734. class GStdout:
  735. """!GConsole standard output
  736. Based on FrameOutErr.py
  737. Name: FrameOutErr.py
  738. Purpose: Redirecting stdout / stderr
  739. Author: Jean-Michel Fauth, Switzerland
  740. Copyright: (c) 2005-2007 Jean-Michel Fauth
  741. Licence: GPL
  742. """
  743. def __init__(self, receiver):
  744. """!
  745. @param receiver event receiver (used in PostEvent)
  746. """
  747. self.receiver = receiver
  748. def write(self, s):
  749. if len(s) == 0 or s == '\n':
  750. return
  751. for line in s.splitlines():
  752. if len(line) == 0:
  753. continue
  754. evt = wxCmdOutput(text = line + '\n',
  755. type = '')
  756. wx.PostEvent(self.receiver, evt)
  757. class GStderr:
  758. """!GConsole standard error output
  759. Based on FrameOutErr.py
  760. Name: FrameOutErr.py
  761. Purpose: Redirecting stdout / stderr
  762. Author: Jean-Michel Fauth, Switzerland
  763. Copyright: (c) 2005-2007 Jean-Michel Fauth
  764. Licence: GPL
  765. """
  766. def __init__(self, receiver):
  767. """!
  768. @param receiver event receiver (used in PostEvent)
  769. """
  770. self.receiver = receiver
  771. self.type = ''
  772. self.message = ''
  773. self.printMessage = False
  774. def flush(self):
  775. pass
  776. def write(self, s):
  777. if "GtkPizza" in s:
  778. return
  779. # remove/replace escape sequences '\b' or '\r' from stream
  780. progressValue = -1
  781. for line in s.splitlines():
  782. if len(line) == 0:
  783. continue
  784. if 'GRASS_INFO_PERCENT' in line:
  785. value = int(line.rsplit(':', 1)[1].strip())
  786. if value >= 0 and value < 100:
  787. progressValue = value
  788. else:
  789. progressValue = 0
  790. elif 'GRASS_INFO_MESSAGE' in line:
  791. self.type = 'message'
  792. self.message += line.split(':', 1)[1].strip() + '\n'
  793. elif 'GRASS_INFO_WARNING' in line:
  794. self.type = 'warning'
  795. self.message += line.split(':', 1)[1].strip() + '\n'
  796. elif 'GRASS_INFO_ERROR' in line:
  797. self.type = 'error'
  798. self.message += line.split(':', 1)[1].strip() + '\n'
  799. elif 'GRASS_INFO_END' in line:
  800. self.printMessage = True
  801. elif self.type == '':
  802. if len(line) == 0:
  803. continue
  804. evt = wxCmdOutput(text = line,
  805. type = '')
  806. wx.PostEvent(self.receiver, evt)
  807. elif len(line) > 0:
  808. self.message += line.strip() + '\n'
  809. if self.printMessage and len(self.message) > 0:
  810. evt = wxCmdOutput(text = self.message,
  811. type = self.type)
  812. wx.PostEvent(self.receiver, evt)
  813. self.type = ''
  814. self.message = ''
  815. self.printMessage = False
  816. # update progress message
  817. if progressValue > -1:
  818. # self.gmgauge.SetValue(progressValue)
  819. evt = wxCmdProgress(value = progressValue)
  820. wx.PostEvent(self.receiver, evt)
  821. class GStc(stc.StyledTextCtrl):
  822. """!Styled text control for GRASS stdout and stderr.
  823. Based on FrameOutErr.py
  824. Name: FrameOutErr.py
  825. Purpose: Redirecting stdout / stderr
  826. Author: Jean-Michel Fauth, Switzerland
  827. Copyright: (c) 2005-2007 Jean-Michel Fauth
  828. Licence: GPL
  829. """
  830. def __init__(self, parent, id, margin = False, wrap = None):
  831. stc.StyledTextCtrl.__init__(self, parent, id)
  832. self.parent = parent
  833. self.SetUndoCollection(True)
  834. self.SetReadOnly(True)
  835. # remember position of line begining (used for '\r')
  836. self.linePos = -1
  837. #
  838. # styles
  839. #
  840. self.SetStyle()
  841. #
  842. # line margins
  843. #
  844. # TODO print number only from cmdlog
  845. self.SetMarginWidth(1, 0)
  846. self.SetMarginWidth(2, 0)
  847. if margin:
  848. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  849. self.SetMarginWidth(0, 30)
  850. else:
  851. self.SetMarginWidth(0, 0)
  852. #
  853. # miscellaneous
  854. #
  855. self.SetViewWhiteSpace(False)
  856. self.SetTabWidth(4)
  857. self.SetUseTabs(False)
  858. self.UsePopUp(True)
  859. self.SetSelBackground(True, "#FFFF00")
  860. self.SetUseHorizontalScrollBar(True)
  861. #
  862. # bindings
  863. #
  864. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  865. def OnTextSelectionChanged(self, event):
  866. """!Copy selected text to clipboard and skip event.
  867. The same function is in TextCtrlAutoComplete class (prompt.py).
  868. """
  869. wx.CallAfter(self.Copy)
  870. event.Skip()
  871. def SetStyle(self):
  872. """!Set styles for styled text output windows with type face
  873. and point size selected by user (Courier New 10 is default)"""
  874. typeface = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  875. if typeface == "":
  876. typeface = "Courier New"
  877. typesize = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  878. if typesize == None or typesize <= 0:
  879. typesize = 10
  880. typesize = float(typesize)
  881. self.StyleDefault = 0
  882. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  883. self.StyleCommand = 1
  884. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  885. self.StyleOutput = 2
  886. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  887. # fatal error
  888. self.StyleError = 3
  889. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  890. # warning
  891. self.StyleWarning = 4
  892. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  893. # message
  894. self.StyleMessage = 5
  895. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  896. # unknown
  897. self.StyleUnknown = 6
  898. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  899. # default and clear => init
  900. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  901. self.StyleClearAll()
  902. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  903. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  904. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  905. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  906. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  907. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  908. def OnDestroy(self, evt):
  909. """!The clipboard contents can be preserved after
  910. the app has exited"""
  911. wx.TheClipboard.Flush()
  912. evt.Skip()
  913. def AddTextWrapped(self, txt, wrap = None):
  914. """!Add string to text area.
  915. String is wrapped and linesep is also added to the end
  916. of the string"""
  917. # allow writing to output window
  918. self.SetReadOnly(False)
  919. if wrap:
  920. txt = textwrap.fill(txt, wrap) + '\n'
  921. else:
  922. if txt[-1] != '\n':
  923. txt += '\n'
  924. if '\r' in txt:
  925. self.linePos = -1
  926. for seg in txt.split('\r'):
  927. if self.linePos > -1:
  928. self.SetCurrentPos(self.linePos)
  929. self.ReplaceSelection(seg)
  930. else:
  931. self.linePos = self.GetCurrentPos()
  932. self.AddText(seg)
  933. else:
  934. self.linePos = self.GetCurrentPos()
  935. try:
  936. self.AddText(txt)
  937. except UnicodeDecodeError:
  938. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  939. if enc:
  940. txt = unicode(txt, enc)
  941. elif 'GRASS_DB_ENCODING' in os.environ:
  942. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  943. else:
  944. txt = EncodeString(txt)
  945. self.AddText(txt)
  946. # reset output window to read only
  947. self.SetReadOnly(True)
  948. def AddStyledMessage(self, message, style = None):
  949. """!Add message to text area.
  950. Handles messages with progress percentages.
  951. @param message message to be added
  952. @param style style of message, allowed values: 'message', 'warning', 'error' or None
  953. """
  954. # message prefix
  955. if style == 'warning':
  956. message = 'WARNING: ' + message
  957. elif style == 'error':
  958. message = 'ERROR: ' + message
  959. p1 = self.GetEndStyled()
  960. self.GotoPos(p1)
  961. # is this still needed?
  962. if '\b' in message:
  963. if self.linePos < 0:
  964. self.linePos = p1
  965. last_c = ''
  966. for c in message:
  967. if c == '\b':
  968. self.linePos -= 1
  969. else:
  970. if c == '\r':
  971. pos = self.GetCurLine()[1]
  972. # self.SetCurrentPos(pos)
  973. else:
  974. self.SetCurrentPos(self.linePos)
  975. self.ReplaceSelection(c)
  976. self.linePos = self.GetCurrentPos()
  977. if c != ' ':
  978. last_c = c
  979. if last_c not in ('0123456789'):
  980. self.AddTextWrapped('\n', wrap = None)
  981. self.linePos = -1
  982. else:
  983. self.linePos = -1 # don't force position
  984. if '\n' not in message:
  985. self.AddTextWrapped(message, wrap = 60)
  986. else:
  987. self.AddTextWrapped(message, wrap = None)
  988. p2 = self.GetCurrentPos()
  989. if p2 >= p1:
  990. self.StartStyling(p1, 0xff)
  991. if style == 'error':
  992. self.SetStyling(p2 - p1, self.StyleError)
  993. elif style == 'warning':
  994. self.SetStyling(p2 - p1, self.StyleWarning)
  995. elif style == 'message':
  996. self.SetStyling(p2 - p1, self.StyleMessage)
  997. else: # unknown
  998. self.SetStyling(p2 - p1, self.StyleUnknown)
  999. self.EnsureCaretVisible()
  1000. class GConsoleFrame(wx.Frame):
  1001. """!Standalone GConsole for testing only"""
  1002. def __init__(self, parent, id = wx.ID_ANY, title = "GConsole Test Frame",
  1003. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  1004. wx.Frame.__init__(self, parent = parent, id = id, title = title)
  1005. panel = wx.Panel(self, id = wx.ID_ANY)
  1006. self.goutput = GConsole(parent = panel, gcstyle = GC_SEARCH | GC_PROMPT)
  1007. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1008. mainSizer.Add(item = self.goutput, proportion = 1, flag = wx.EXPAND, border = 0)
  1009. panel.SetSizer(mainSizer)
  1010. mainSizer.Fit(panel)
  1011. self.SetMinSize((550, 500))
  1012. def testGConsole():
  1013. app = wx.PySimpleApp()
  1014. frame = GConsoleFrame(parent = None)
  1015. frame.Show()
  1016. app.MainLoop()
  1017. if __name__ == '__main__':
  1018. testGConsole()