goutput.py 29 KB

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