goutput.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. """
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::GConsoleWindow
  6. - goutput::GStc
  7. - goutput::GConsoleFrame
  8. (C) 2007-2012 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Michael Barton (Arizona State University)
  12. @author Martin Landa <landa.martin gmail.com>
  13. @author Vaclav Petras <wenzeslaus gmail.com> (refactoring)
  14. @author Anna Kratochvilova <kratochanna gmail.com> (refactoring)
  15. """
  16. import os
  17. import textwrap
  18. import wx
  19. from wx import stc
  20. from grass.pydispatch.signal import Signal
  21. # needed just for testing
  22. if __name__ == '__main__':
  23. from grass.script.setup import set_gui_path
  24. set_gui_path()
  25. from core.gcmd import GError, EncodeString
  26. from core.gconsole import GConsole, \
  27. EVT_CMD_OUTPUT, EVT_CMD_PROGRESS, EVT_CMD_RUN, EVT_CMD_DONE, \
  28. Notification
  29. from core.globalvar import CheckWxVersion, wxPythonPhoenix
  30. from gui_core.prompt import GPromptSTC
  31. from gui_core.wrap import Button, ClearButton, ToggleButton, StaticText, \
  32. StaticBox
  33. from core.settings import UserSettings
  34. GC_EMPTY = 0
  35. GC_PROMPT = 1
  36. class GConsoleWindow(wx.SplitterWindow):
  37. """Create and manage output console for commands run by GUI.
  38. """
  39. def __init__(self, parent, giface, gconsole, menuModel=None, margin=False,
  40. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  41. gcstyle=GC_EMPTY,
  42. **kwargs):
  43. """
  44. :param parent: gui parent
  45. :param gconsole: console logic
  46. :param menuModel: tree model of modules (from menu)
  47. :param margin: use margin in output pane (GStc)
  48. :param style: wx.SplitterWindow style
  49. :param gcstyle: GConsole style
  50. (GC_EMPTY, GC_PROMPT to show command prompt)
  51. """
  52. wx.SplitterWindow.__init__(
  53. self, parent, id=wx.ID_ANY, style=style, **kwargs)
  54. self.SetName("GConsole")
  55. self.panelOutput = wx.Panel(parent=self, id=wx.ID_ANY)
  56. self.panelProgress = wx.Panel(
  57. parent=self.panelOutput,
  58. id=wx.ID_ANY,
  59. name='progressPanel')
  60. self.panelPrompt = wx.Panel(parent=self, id=wx.ID_ANY)
  61. # initialize variables
  62. self.parent = parent # GMFrame | CmdPanel | ?
  63. self._gconsole = gconsole
  64. self._menuModel = menuModel
  65. self._gcstyle = gcstyle
  66. self.lineWidth = 80
  67. # signal which requests showing of a notification
  68. self.showNotification = Signal("GConsoleWindow.showNotification")
  69. # signal emitted when text appears in the console
  70. # parameter 'notification' suggests form of notification (according to
  71. # core.giface.Notification)
  72. self.contentChanged = Signal("GConsoleWindow.contentChanged")
  73. # progress bar
  74. self.progressbar = wx.Gauge(parent=self.panelProgress, id=wx.ID_ANY,
  75. range=100, pos=(110, 50), size=(-1, 25),
  76. style=wx.GA_HORIZONTAL)
  77. self._gconsole.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  78. self._gconsole.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  79. self._gconsole.Bind(EVT_CMD_RUN, self.OnCmdRun)
  80. self._gconsole.Bind(EVT_CMD_DONE, self.OnCmdDone)
  81. self._gconsole.writeLog.connect(self.WriteLog)
  82. self._gconsole.writeCmdLog.connect(self.WriteCmdLog)
  83. self._gconsole.writeWarning.connect(self.WriteWarning)
  84. self._gconsole.writeError.connect(self.WriteError)
  85. # text control for command output
  86. self.cmdOutput = GStc(
  87. parent=self.panelOutput,
  88. id=wx.ID_ANY,
  89. margin=margin,
  90. wrap=None)
  91. # command prompt
  92. # move to the if below
  93. # search depends on cmd prompt
  94. self.cmdPrompt = GPromptSTC(
  95. parent=self, giface=giface, menuModel=self._menuModel
  96. )
  97. self.cmdPrompt.promptRunCmd.connect(lambda cmd:
  98. self._gconsole.RunCmd(command=cmd))
  99. self.cmdPrompt.showNotification.connect(self.showNotification)
  100. if not self._gcstyle & GC_PROMPT:
  101. self.cmdPrompt.Hide()
  102. if self._gcstyle & GC_PROMPT:
  103. cmdLabel = _("Command prompt")
  104. self.outputBox = StaticBox(
  105. parent=self.panelOutput,
  106. id=wx.ID_ANY,
  107. label=" %s " %
  108. _("Output window"))
  109. self.cmdBox = StaticBox(parent=self.panelOutput, id=wx.ID_ANY,
  110. label=" %s " % cmdLabel)
  111. # buttons
  112. self.btnOutputClear = ClearButton(parent=self.panelOutput)
  113. self.btnOutputClear.SetToolTip(_("Clear output window content"))
  114. self.btnCmdClear = ClearButton(parent=self.panelOutput)
  115. self.btnCmdClear.SetToolTip(_("Clear command prompt content"))
  116. self.btnOutputSave = Button(parent=self.panelOutput, id=wx.ID_SAVE)
  117. self.btnOutputSave.SetToolTip(
  118. _("Save output window content to the file"))
  119. self.btnCmdAbort = Button(parent=self.panelProgress, id=wx.ID_STOP)
  120. self.btnCmdAbort.SetToolTip(_("Abort running command"))
  121. self.btnCmdProtocol = ToggleButton(
  122. parent=self.panelOutput,
  123. id=wx.ID_ANY,
  124. label=_("&Log file"),
  125. size=self.btnCmdClear.GetSize())
  126. self.btnCmdProtocol.SetToolTip(_("Toggle to save list of executed commands into "
  127. "a file; content saved when switching off."))
  128. self.cmdFileProtocol = None
  129. if not self._gcstyle & GC_PROMPT:
  130. self.btnCmdClear.Hide()
  131. self.btnCmdProtocol.Hide()
  132. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  133. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  134. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  135. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self._gconsole.OnCmdAbort)
  136. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  137. self._layout()
  138. def _layout(self):
  139. """Do layout"""
  140. self.outputSizer = wx.BoxSizer(wx.VERTICAL)
  141. progressSizer = wx.BoxSizer(wx.HORIZONTAL)
  142. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  143. if self._gcstyle & GC_PROMPT:
  144. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  145. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  146. else:
  147. outBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
  148. cmdBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
  149. if self._gcstyle & GC_PROMPT:
  150. promptSizer = wx.BoxSizer(wx.VERTICAL)
  151. promptSizer.Add(self.cmdPrompt, proportion=1,
  152. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
  153. border=3)
  154. helpText = StaticText(
  155. self.panelPrompt, id=wx.ID_ANY,
  156. label="Press Tab to display command help, Ctrl+Space to autocomplete")
  157. helpText.SetForegroundColour(
  158. wx.SystemSettings.GetColour(
  159. wx.SYS_COLOUR_GRAYTEXT))
  160. promptSizer.Add(helpText,
  161. proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
  162. self.outputSizer.Add(self.cmdOutput, proportion=1,
  163. flag=wx.EXPAND | wx.ALL, border=3)
  164. if self._gcstyle & GC_PROMPT:
  165. proportion = 1
  166. else:
  167. proportion = 0
  168. outBtnSizer.AddStretchSpacer()
  169. outBtnSizer.Add(
  170. self.btnOutputClear,
  171. proportion=proportion,
  172. flag=wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  173. border=5)
  174. outBtnSizer.Add(self.btnOutputSave, proportion=proportion,
  175. flag=wx.RIGHT | wx.BOTTOM, border=5)
  176. cmdBtnSizer.Add(
  177. self.btnCmdProtocol,
  178. proportion=1,
  179. flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  180. border=5)
  181. cmdBtnSizer.Add(self.btnCmdClear, proportion=1,
  182. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.BOTTOM, border=5)
  183. progressSizer.Add(self.btnCmdAbort, proportion=0,
  184. flag=wx.ALL | wx.ALIGN_CENTER, border=5)
  185. progressSizer.Add(
  186. self.progressbar,
  187. proportion=1,
  188. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.TOP | wx.BOTTOM,
  189. border=5)
  190. self.panelProgress.SetSizer(progressSizer)
  191. progressSizer.Fit(self.panelProgress)
  192. btnSizer.Add(outBtnSizer, proportion=1,
  193. flag=wx.ALL | wx.ALIGN_CENTER, border=5)
  194. btnSizer.Add(
  195. cmdBtnSizer,
  196. proportion=1,
  197. flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT,
  198. border=5)
  199. self.outputSizer.Add(self.panelProgress, proportion=0,
  200. flag=wx.EXPAND)
  201. self.outputSizer.Add(btnSizer, proportion=0,
  202. flag=wx.EXPAND)
  203. self.outputSizer.Fit(self)
  204. self.outputSizer.SetSizeHints(self)
  205. self.panelOutput.SetSizer(self.outputSizer)
  206. self.outputSizer.FitInside(self.panelOutput)
  207. if self._gcstyle & GC_PROMPT:
  208. promptSizer.Fit(self)
  209. promptSizer.SetSizeHints(self)
  210. self.panelPrompt.SetSizer(promptSizer)
  211. # split window
  212. if self._gcstyle & GC_PROMPT:
  213. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  214. else:
  215. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  216. self.Unsplit()
  217. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  218. self.SetSashGravity(1.0)
  219. self.outputSizer.Hide(self.panelProgress)
  220. # layout
  221. self.SetAutoLayout(True)
  222. self.Layout()
  223. def GetPanel(self, prompt=True):
  224. """Get panel
  225. :param prompt: get prompt / output panel
  226. :return: wx.Panel reference
  227. """
  228. if prompt:
  229. return self.panelPrompt
  230. return self.panelOutput
  231. def WriteLog(self, text, style=None, wrap=None,
  232. notification=Notification.HIGHLIGHT):
  233. """Generic method for writing log message in
  234. given style.
  235. Emits contentChanged signal.
  236. :param line: text line
  237. :param style: text style (see GStc)
  238. :param stdout: write to stdout or stderr
  239. :param notification: form of notification
  240. """
  241. self.cmdOutput.SetStyle()
  242. # documenting old behavior/implementation:
  243. # switch notebook if required
  244. # now, let user to bind to the old event
  245. if not style:
  246. style = self.cmdOutput.StyleDefault
  247. # p1 = self.cmdOutput.GetCurrentPos()
  248. p1 = self.cmdOutput.GetEndStyled()
  249. # self.cmdOutput.GotoPos(p1)
  250. self.cmdOutput.DocumentEnd()
  251. for line in text.splitlines():
  252. # fill space
  253. if len(line) < self.lineWidth:
  254. diff = self.lineWidth - len(line)
  255. line += diff * ' '
  256. self.cmdOutput.AddTextWrapped(line, wrap=wrap) # adds '\n'
  257. p2 = self.cmdOutput.GetCurrentPos()
  258. # between wxWidgets 3.0 and 3.1 they dropped mask param
  259. try:
  260. self.cmdOutput.StartStyling(p1)
  261. except TypeError:
  262. self.cmdOutput.StartStyling(p1, 0xff)
  263. self.cmdOutput.SetStyling(p2 - p1, style)
  264. self.cmdOutput.EnsureCaretVisible()
  265. self.contentChanged.emit(notification=notification)
  266. def WriteCmdLog(self, text, pid=None,
  267. notification=Notification.MAKE_VISIBLE):
  268. """Write message in selected style
  269. :param text: message to be printed
  270. :param pid: process pid or None
  271. :param switchPage: True to switch page
  272. """
  273. if pid:
  274. text = '(' + str(pid) + ') ' + text
  275. self.WriteLog(
  276. text,
  277. style=self.cmdOutput.StyleCommand,
  278. notification=notification)
  279. def WriteWarning(self, text):
  280. """Write message in warning style"""
  281. self.WriteLog(text, style=self.cmdOutput.StyleWarning,
  282. notification=Notification.MAKE_VISIBLE)
  283. def WriteError(self, text):
  284. """Write message in error style"""
  285. self.WriteLog(text, style=self.cmdOutput.StyleError,
  286. notification=Notification.MAKE_VISIBLE)
  287. def OnOutputClear(self, event):
  288. """Clear content of output window"""
  289. self.cmdOutput.SetReadOnly(False)
  290. self.cmdOutput.ClearAll()
  291. self.cmdOutput.SetReadOnly(True)
  292. self.progressbar.SetValue(0)
  293. def GetProgressBar(self):
  294. """Return progress bar widget"""
  295. return self.progressbar
  296. def OnOutputSave(self, event):
  297. """Save (selected) text from output window to the file"""
  298. text = self.cmdOutput.GetSelectedText()
  299. if not text:
  300. text = self.cmdOutput.GetText()
  301. # add newline if needed
  302. if len(text) > 0 and text[-1] != '\n':
  303. text += '\n'
  304. dlg = wx.FileDialog(
  305. self, message=_("Save file as..."),
  306. defaultFile="grass_cmd_output.txt",
  307. wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  308. {'txt': _("Text files"),
  309. 'files': _("Files")},
  310. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  311. # Show the dialog and retrieve the user response. If it is the OK response,
  312. # process the data.
  313. if dlg.ShowModal() == wx.ID_OK:
  314. path = dlg.GetPath()
  315. try:
  316. output = open(path, "w")
  317. output.write(text)
  318. except IOError as e:
  319. GError(
  320. _("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {
  321. 'path': path,
  322. 'error': e})
  323. finally:
  324. output.close()
  325. message = _("Command output saved into '%s'") % path
  326. self.showNotification.emit(message=message)
  327. dlg.Destroy()
  328. def SetCopyingOfSelectedText(self, copy):
  329. """Enable or disable copying of selected text in to clipboard.
  330. Effects prompt and output.
  331. :param bool copy: True for enable, False for disable
  332. """
  333. if copy:
  334. self.cmdPrompt.Bind(
  335. stc.EVT_STC_PAINTED,
  336. self.cmdPrompt.OnTextSelectionChanged)
  337. self.cmdOutput.Bind(
  338. stc.EVT_STC_PAINTED,
  339. self.cmdOutput.OnTextSelectionChanged)
  340. else:
  341. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  342. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  343. def OnCmdOutput(self, event):
  344. """Prints command output.
  345. Emits contentChanged signal.
  346. """
  347. message = event.text
  348. type = event.type
  349. self.cmdOutput.AddStyledMessage(message, type)
  350. if event.type in ('warning', 'error'):
  351. self.contentChanged.emit(notification=Notification.MAKE_VISIBLE)
  352. else:
  353. self.contentChanged.emit(notification=Notification.HIGHLIGHT)
  354. def OnCmdProgress(self, event):
  355. """Update progress message info"""
  356. self.progressbar.SetValue(event.value)
  357. event.Skip()
  358. def CmdProtocolSave(self):
  359. """Save list of manually entered commands into a text log file"""
  360. if self.cmdFileProtocol is None:
  361. return # it should not happen
  362. try:
  363. with open(self.cmdFileProtocol, "a") as output:
  364. cmds = self.cmdPrompt.GetCommands()
  365. output.write('\n'.join(cmds))
  366. if len(cmds) > 0:
  367. output.write('\n')
  368. except IOError as e:
  369. GError(_("Unable to write file '{filePath}'.\n\nDetails: {error}").format(
  370. filePath=self.cmdFileProtocol, error=e))
  371. self.showNotification.emit(
  372. message=_("Command log saved to '{}'".format(self.cmdFileProtocol))
  373. )
  374. self.cmdFileProtocol = None
  375. def OnCmdProtocol(self, event=None):
  376. """Save commands into file"""
  377. if not event.IsChecked():
  378. # stop capturing commands, save list of commands to the
  379. # protocol file
  380. self.CmdProtocolSave()
  381. else:
  382. # start capturing commands
  383. self.cmdPrompt.ClearCommands()
  384. # ask for the file
  385. dlg = wx.FileDialog(
  386. self, message=_("Save file as..."),
  387. defaultFile="grass_cmd_log.txt",
  388. wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  389. {'txt': _("Text files"),
  390. 'files': _("Files")},
  391. style=wx.FD_SAVE)
  392. if dlg.ShowModal() == wx.ID_OK:
  393. self.cmdFileProtocol = dlg.GetPath()
  394. else:
  395. wx.CallAfter(self.btnCmdProtocol.SetValue, False)
  396. dlg.Destroy()
  397. event.Skip()
  398. def OnCmdRun(self, event):
  399. """Run command"""
  400. self.outputSizer.Show(self.panelProgress)
  401. self.outputSizer.Layout()
  402. event.Skip()
  403. def OnCmdDone(self, event):
  404. """Command done (or aborted)
  405. """
  406. self.progressbar.SetValue(0) # reset progress bar on '0%'
  407. wx.CallLater(100, self._hideProgress)
  408. event.Skip()
  409. def _hideProgress(self):
  410. self.outputSizer.Hide(self.panelProgress)
  411. self.outputSizer.Layout()
  412. def ResetFocus(self):
  413. """Reset focus"""
  414. self.cmdPrompt.SetFocus()
  415. def GetPrompt(self):
  416. """Get prompt"""
  417. return self.cmdPrompt
  418. class GStc(stc.StyledTextCtrl):
  419. """Styled text control for GRASS stdout and stderr.
  420. Based on FrameOutErr.py
  421. Name: FrameOutErr.py
  422. Purpose: Redirecting stdout / stderr
  423. Author: Jean-Michel Fauth, Switzerland
  424. Copyright: (c) 2005-2007 Jean-Michel Fauth
  425. Licence: GPL
  426. """
  427. def __init__(self, parent, id, margin=False, wrap=None):
  428. stc.StyledTextCtrl.__init__(self, parent, id)
  429. self.parent = parent
  430. self.SetUndoCollection(True)
  431. self.SetReadOnly(True)
  432. # remember position of line beginning (used for '\r')
  433. self.linePos = -1
  434. #
  435. # styles
  436. #
  437. self.SetStyle()
  438. #
  439. # line margins
  440. #
  441. # TODO print number only from cmdlog
  442. self.SetMarginWidth(1, 0)
  443. self.SetMarginWidth(2, 0)
  444. if margin:
  445. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  446. self.SetMarginWidth(0, 30)
  447. else:
  448. self.SetMarginWidth(0, 0)
  449. #
  450. # miscellaneous
  451. #
  452. self.SetViewWhiteSpace(False)
  453. self.SetTabWidth(4)
  454. self.SetUseTabs(False)
  455. self.UsePopUp(True)
  456. self.SetSelBackground(True,
  457. wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
  458. self.SetUseHorizontalScrollBar(True)
  459. #
  460. # bindings
  461. #
  462. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  463. def OnTextSelectionChanged(self, event):
  464. """Copy selected text to clipboard and skip event.
  465. The same function is in TextCtrlAutoComplete class (prompt.py).
  466. """
  467. wx.CallAfter(self.Copy)
  468. event.Skip()
  469. def SetStyle(self):
  470. """Set styles for styled text output windows with type face
  471. and point size selected by user (Courier New 10 is default)"""
  472. typeface = UserSettings.Get(
  473. group='appearance',
  474. key='outputfont',
  475. subkey='type')
  476. if typeface == "":
  477. typeface = "Courier New"
  478. typesize = UserSettings.Get(
  479. group='appearance',
  480. key='outputfont',
  481. subkey='size')
  482. if typesize is None or int(typesize) <= 0:
  483. typesize = 10
  484. typesize = float(typesize)
  485. fontInfo = wx.FontInfo(typesize)
  486. fontInfo.FaceName(typeface)
  487. fontInfo.Family(wx.FONTFAMILY_TELETYPE)
  488. defaultFont = wx.Font(fontInfo)
  489. self.StyleClearAll()
  490. isDarkMode = False
  491. if wxPythonPhoenix and CheckWxVersion([4, 1, 0]):
  492. isDarkMode = wx.SystemSettings.GetAppearance().IsDark()
  493. defaultBackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  494. defaultTextColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
  495. self.StyleDefault = 0
  496. self.StyleSetFont(stc.STC_STYLE_DEFAULT, defaultFont)
  497. self.StyleSetBackground(stc.STC_STYLE_DEFAULT, defaultBackgroundColour)
  498. self.StyleSetForeground(stc.STC_STYLE_DEFAULT, defaultTextColour)
  499. self.StyleCommand = 1
  500. self.StyleSetBackground(self.StyleCommand, wx.Colour(154, 154, 154, 255))
  501. self.StyleSetForeground(self.StyleCommand, defaultTextColour)
  502. self.StyleOutput = 2
  503. self.StyleSetBackground(self.StyleOutput, defaultBackgroundColour)
  504. self.StyleSetForeground(self.StyleOutput, defaultTextColour)
  505. # fatal error
  506. self.StyleError = 3
  507. errorColour = wx.Colour(127, 0, 0)
  508. if isDarkMode:
  509. errorColour = wx.Colour(230, 0, 0)
  510. self.StyleSetBackground(self.StyleError, defaultBackgroundColour)
  511. self.StyleSetForeground(self.StyleError, errorColour)
  512. # warning
  513. self.StyleWarning = 4
  514. warningColour = wx.Colour(0, 0, 255)
  515. if isDarkMode:
  516. warningColour = wx.Colour(0, 102, 255)
  517. self.StyleSetBackground(self.StyleWarning, defaultBackgroundColour)
  518. self.StyleSetForeground(self.StyleWarning, warningColour)
  519. # message
  520. self.StyleMessage = 5
  521. self.StyleSetBackground(self.StyleMessage, defaultBackgroundColour)
  522. self.StyleSetForeground(self.StyleMessage, defaultTextColour)
  523. # unknown
  524. self.StyleUnknown = 6
  525. self.StyleSetBackground(self.StyleUnknown, defaultBackgroundColour)
  526. self.StyleSetForeground(self.StyleUnknown, defaultTextColour)
  527. def OnDestroy(self, evt):
  528. """The clipboard contents can be preserved after
  529. the app has exited"""
  530. if wx.TheClipboard.IsOpened():
  531. wx.TheClipboard.Flush()
  532. evt.Skip()
  533. def AddTextWrapped(self, txt, wrap=None):
  534. """Add string to text area.
  535. String is wrapped and linesep is also added to the end
  536. of the string"""
  537. # allow writing to output window
  538. self.SetReadOnly(False)
  539. if wrap:
  540. txt = textwrap.fill(txt, wrap) + '\n'
  541. else:
  542. if txt[-1] != '\n':
  543. txt += '\n'
  544. if '\r' in txt:
  545. self.linePos = -1
  546. for seg in txt.split('\r'):
  547. if self.linePos > -1:
  548. self.SetCurrentPos(self.linePos)
  549. self.ReplaceSelection(seg)
  550. else:
  551. self.linePos = self.GetCurrentPos()
  552. self.AddText(seg)
  553. else:
  554. self.linePos = self.GetCurrentPos()
  555. try:
  556. self.AddText(txt)
  557. except UnicodeDecodeError:
  558. # TODO: this might be dead code for Py3, txt is already unicode?
  559. enc = UserSettings.Get(
  560. group='atm', key='encoding', subkey='value')
  561. if enc:
  562. txt = unicode(txt, enc, errors='replace')
  563. elif 'GRASS_DB_ENCODING' in os.environ:
  564. txt = unicode(
  565. txt, os.environ['GRASS_DB_ENCODING'],
  566. errors='replace')
  567. else:
  568. txt = EncodeString(txt)
  569. self.AddText(txt)
  570. # reset output window to read only
  571. self.SetReadOnly(True)
  572. def AddStyledMessage(self, message, style=None):
  573. """Add message to text area.
  574. Handles messages with progress percentages.
  575. :param message: message to be added
  576. :param style: style of message, allowed values: 'message',
  577. 'warning', 'error' or None
  578. """
  579. # message prefix
  580. if style == 'warning':
  581. message = 'WARNING: ' + message
  582. elif style == 'error':
  583. message = 'ERROR: ' + message
  584. p1 = self.GetEndStyled()
  585. self.GotoPos(p1)
  586. # is this still needed?
  587. if '\b' in message:
  588. if self.linePos < 0:
  589. self.linePos = p1
  590. last_c = ''
  591. for c in message:
  592. if c == '\b':
  593. self.linePos -= 1
  594. else:
  595. if c == '\r':
  596. pos = self.GetCurLine()[1]
  597. # self.SetCurrentPos(pos)
  598. else:
  599. self.SetCurrentPos(self.linePos)
  600. self.ReplaceSelection(c)
  601. self.linePos = self.GetCurrentPos()
  602. if c != ' ':
  603. last_c = c
  604. if last_c not in ('0123456789'):
  605. self.AddTextWrapped('\n', wrap=None)
  606. self.linePos = -1
  607. else:
  608. self.linePos = -1 # don't force position
  609. if '\n' not in message:
  610. self.AddTextWrapped(message, wrap=60)
  611. else:
  612. self.AddTextWrapped(message, wrap=None)
  613. p2 = self.GetCurrentPos()
  614. if p2 >= p1:
  615. try:
  616. self.StartStyling(p1)
  617. except TypeError:
  618. self.StartStyling(p1, 0xff)
  619. if style == 'error':
  620. self.SetStyling(p2 - p1, self.StyleError)
  621. elif style == 'warning':
  622. self.SetStyling(p2 - p1, self.StyleWarning)
  623. elif style == 'message':
  624. self.SetStyling(p2 - p1, self.StyleMessage)
  625. else: # unknown
  626. self.SetStyling(p2 - p1, self.StyleUnknown)
  627. self.EnsureCaretVisible()
  628. class GConsoleFrame(wx.Frame):
  629. """Standalone GConsole for testing only"""
  630. def __init__(self, parent, id=wx.ID_ANY, title="GConsole Test Frame",
  631. style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  632. wx.Frame.__init__(self, parent=parent, id=id, title=title, style=style)
  633. panel = wx.Panel(self, id=wx.ID_ANY)
  634. from lmgr.menudata import LayerManagerMenuData
  635. menuTreeBuilder = LayerManagerMenuData()
  636. self.gconsole = GConsole(guiparent=self)
  637. self.goutput = GConsoleWindow(parent=panel, gconsole=self.gconsole,
  638. menuModel=menuTreeBuilder.GetModel(),
  639. gcstyle=GC_PROMPT)
  640. mainSizer = wx.BoxSizer(wx.VERTICAL)
  641. mainSizer.Add(
  642. self.goutput,
  643. proportion=1,
  644. flag=wx.EXPAND,
  645. border=0)
  646. panel.SetSizer(mainSizer)
  647. mainSizer.Fit(panel)
  648. self.SetMinSize((550, 500))
  649. def testGConsole():
  650. app = wx.App()
  651. frame = GConsoleFrame(parent=None)
  652. frame.Show()
  653. app.MainLoop()
  654. if __name__ == '__main__':
  655. testGConsole()