goutput.py 29 KB

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