goutput.py 28 KB

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