goutput.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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
  31. from core.settings import UserSettings
  32. from core.utils import _
  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 = wx.StaticBox(
  124. parent=self.panelOutput,
  125. id=wx.ID_ANY,
  126. label=" %s " %
  127. _("Output window"))
  128. self.cmdBox = wx.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. if not self._gcstyle & GC_PROMPT:
  149. self.btnCmdClear.Hide()
  150. self.btnCmdProtocol.Hide()
  151. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  152. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  153. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  154. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self._gconsole.OnCmdAbort)
  155. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  156. self._layout()
  157. def _layout(self):
  158. """Do layout"""
  159. self.outputSizer = wx.BoxSizer(wx.VERTICAL)
  160. progressSizer = wx.BoxSizer(wx.HORIZONTAL)
  161. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  162. if self._gcstyle & GC_PROMPT:
  163. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  164. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  165. else:
  166. outBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
  167. cmdBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
  168. if self._gcstyle & GC_PROMPT:
  169. promptSizer = wx.BoxSizer(wx.VERTICAL)
  170. promptSizer.Add(self.cmdPrompt, proportion=1,
  171. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
  172. border=3)
  173. helpText = wx.StaticText(
  174. self.panelPrompt, id=wx.ID_ANY,
  175. label="Press Tab to display command help, Ctrl+Space to autocomplete")
  176. helpText.SetForegroundColour(
  177. wx.SystemSettings.GetColour(
  178. wx.SYS_COLOUR_GRAYTEXT))
  179. promptSizer.Add(helpText,
  180. proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
  181. if self._gcstyle & GC_SEARCH:
  182. self.outputSizer.Add(self.searchPane, proportion=0,
  183. flag=wx.EXPAND | wx.ALL, border=3)
  184. self.outputSizer.Add(self.cmdOutput, proportion=1,
  185. flag=wx.EXPAND | wx.ALL, border=3)
  186. if self._gcstyle & GC_PROMPT:
  187. proportion = 1
  188. else:
  189. proportion = 0
  190. outBtnSizer.AddStretchSpacer()
  191. outBtnSizer.Add(
  192. self.btnOutputClear,
  193. proportion=proportion,
  194. flag=wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  195. border=5)
  196. outBtnSizer.Add(self.btnOutputSave, proportion=proportion,
  197. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, border=5)
  198. cmdBtnSizer.Add(
  199. self.btnCmdProtocol,
  200. proportion=1,
  201. flag=wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  202. border=5)
  203. cmdBtnSizer.Add(self.btnCmdClear, proportion=1,
  204. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.BOTTOM, border=5)
  205. progressSizer.Add(self.btnCmdAbort, proportion=0,
  206. flag=wx.ALL | wx.ALIGN_CENTER, border=5)
  207. progressSizer.Add(
  208. self.progressbar,
  209. proportion=1,
  210. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.TOP | wx.BOTTOM,
  211. border=5)
  212. self.panelProgress.SetSizer(progressSizer)
  213. progressSizer.Fit(self.panelProgress)
  214. btnSizer.Add(outBtnSizer, proportion=1,
  215. flag=wx.ALL | wx.ALIGN_CENTER, border=5)
  216. btnSizer.Add(
  217. cmdBtnSizer,
  218. proportion=1,
  219. flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT,
  220. border=5)
  221. self.outputSizer.Add(self.panelProgress, proportion=0,
  222. flag=wx.EXPAND)
  223. self.outputSizer.Add(btnSizer, proportion=0,
  224. flag=wx.EXPAND)
  225. self.outputSizer.Fit(self)
  226. self.outputSizer.SetSizeHints(self)
  227. self.panelOutput.SetSizer(self.outputSizer)
  228. # eliminate gtk_widget_size_allocate() warnings
  229. # avoid to use a deprecated method in wxPython >= 2.9
  230. getattr(self.outputSizer, 'FitInside',
  231. self.outputSizer.SetVirtualSizeHints)(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. self.cmdOutput.StartStyling(p1, 0xff)
  302. self.cmdOutput.SetStyling(p2 - p1, style)
  303. self.cmdOutput.EnsureCaretVisible()
  304. self.contentChanged.emit(notification=notification)
  305. def WriteCmdLog(self, text, pid=None,
  306. notification=Notification.MAKE_VISIBLE):
  307. """Write message in selected style
  308. :param text: message to be printed
  309. :param pid: process pid or None
  310. :param switchPage: True to switch page
  311. """
  312. if pid:
  313. text = '(' + str(pid) + ') ' + text
  314. self.WriteLog(
  315. text,
  316. style=self.cmdOutput.StyleCommand,
  317. notification=notification)
  318. def WriteWarning(self, text):
  319. """Write message in warning style"""
  320. self.WriteLog(text, style=self.cmdOutput.StyleWarning,
  321. notification=Notification.MAKE_VISIBLE)
  322. def WriteError(self, text):
  323. """Write message in error style"""
  324. self.WriteLog(text, style=self.cmdOutput.StyleError,
  325. notification=Notification.MAKE_VISIBLE)
  326. def OnOutputClear(self, event):
  327. """Clear content of output window"""
  328. self.cmdOutput.SetReadOnly(False)
  329. self.cmdOutput.ClearAll()
  330. self.cmdOutput.SetReadOnly(True)
  331. self.progressbar.SetValue(0)
  332. def GetProgressBar(self):
  333. """Return progress bar widget"""
  334. return self.progressbar
  335. def OnOutputSave(self, event):
  336. """Save (selected) text from output window to the file"""
  337. text = self.cmdOutput.GetSelectedText()
  338. if not text:
  339. text = self.cmdOutput.GetText()
  340. # add newline if needed
  341. if len(text) > 0 and text[-1] != '\n':
  342. text += '\n'
  343. dlg = wx.FileDialog(
  344. self, message=_("Save file as..."),
  345. defaultFile="grass_cmd_output.txt",
  346. wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  347. {'txt': _("Text files"),
  348. 'files': _("Files")},
  349. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  350. # Show the dialog and retrieve the user response. If it is the OK response,
  351. # process the data.
  352. if dlg.ShowModal() == wx.ID_OK:
  353. path = dlg.GetPath()
  354. try:
  355. output = open(path, "w")
  356. output.write(EncodeString(text))
  357. except IOError as e:
  358. GError(
  359. _("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {
  360. 'path': path,
  361. 'error': e})
  362. finally:
  363. output.close()
  364. message = _("Command output saved into '%s'") % path
  365. self.showNotification.emit(message=message)
  366. dlg.Destroy()
  367. def SetCopyingOfSelectedText(self, copy):
  368. """Enable or disable copying of selected text in to clipboard.
  369. Effects prompt and output.
  370. :param bool copy: True for enable, False for disable
  371. """
  372. if copy:
  373. self.cmdPrompt.Bind(
  374. stc.EVT_STC_PAINTED,
  375. self.cmdPrompt.OnTextSelectionChanged)
  376. self.cmdOutput.Bind(
  377. stc.EVT_STC_PAINTED,
  378. self.cmdOutput.OnTextSelectionChanged)
  379. else:
  380. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  381. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  382. def OnCmdOutput(self, event):
  383. """Prints command output.
  384. Emits contentChanged signal.
  385. """
  386. message = event.text
  387. type = event.type
  388. self.cmdOutput.AddStyledMessage(message, type)
  389. if event.type in ('warning', 'error'):
  390. self.contentChanged.emit(notification=Notification.MAKE_VISIBLE)
  391. else:
  392. self.contentChanged.emit(notification=Notification.HIGHLIGHT)
  393. def OnCmdProgress(self, event):
  394. """Update progress message info"""
  395. self.progressbar.SetValue(event.value)
  396. event.Skip()
  397. def CmdProtocolSave(self):
  398. """Save list of manually entered commands into a text log file"""
  399. if not hasattr(self, 'cmdFileProtocol'):
  400. return # it should not happen
  401. try:
  402. output = open(self.cmdFileProtocol, "a")
  403. cmds = self.cmdPrompt.GetCommands()
  404. output.write('\n'.join(cmds))
  405. if len(cmds) > 0:
  406. output.write('\n')
  407. except IOError as e:
  408. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  409. {'filePath': self.cmdFileProtocol, 'error': e})
  410. finally:
  411. output.close()
  412. message = _("Command log saved to '%s'") % self.cmdFileProtocol
  413. self.showNotification.emit(message=message)
  414. del self.cmdFileProtocol
  415. def OnCmdProtocol(self, event=None):
  416. """Save commands into file"""
  417. if not event.IsChecked():
  418. # stop capturing commands, save list of commands to the
  419. # protocol file
  420. self.CmdProtocolSave()
  421. else:
  422. # start capturing commands
  423. self.cmdPrompt.ClearCommands()
  424. # ask for the file
  425. dlg = wx.FileDialog(
  426. self, message=_("Save file as..."),
  427. defaultFile="grass_cmd_log.txt",
  428. wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  429. {'txt': _("Text files"),
  430. 'files': _("Files")},
  431. style=wx.FD_SAVE)
  432. if dlg.ShowModal() == wx.ID_OK:
  433. self.cmdFileProtocol = dlg.GetPath()
  434. else:
  435. wx.CallAfter(self.btnCmdProtocol.SetValue, False)
  436. dlg.Destroy()
  437. event.Skip()
  438. def OnCmdRun(self, event):
  439. """Run command"""
  440. self.outputSizer.Show(self.panelProgress)
  441. self.outputSizer.Layout()
  442. event.Skip()
  443. def OnCmdDone(self, event):
  444. """Command done (or aborted)
  445. """
  446. self.progressbar.SetValue(0) # reset progress bar on '0%'
  447. wx.CallLater(100, self._hideProgress)
  448. event.Skip()
  449. def _hideProgress(self):
  450. self.outputSizer.Hide(self.panelProgress)
  451. self.outputSizer.Layout()
  452. def ResetFocus(self):
  453. """Reset focus"""
  454. self.cmdPrompt.SetFocus()
  455. def GetPrompt(self):
  456. """Get prompt"""
  457. return self.cmdPrompt
  458. class GStc(stc.StyledTextCtrl):
  459. """Styled text control for GRASS stdout and stderr.
  460. Based on FrameOutErr.py
  461. Name: FrameOutErr.py
  462. Purpose: Redirecting stdout / stderr
  463. Author: Jean-Michel Fauth, Switzerland
  464. Copyright: (c) 2005-2007 Jean-Michel Fauth
  465. Licence: GPL
  466. """
  467. def __init__(self, parent, id, margin=False, wrap=None):
  468. stc.StyledTextCtrl.__init__(self, parent, id)
  469. self.parent = parent
  470. self.SetUndoCollection(True)
  471. self.SetReadOnly(True)
  472. # remember position of line beginning (used for '\r')
  473. self.linePos = -1
  474. #
  475. # styles
  476. #
  477. self.SetStyle()
  478. #
  479. # line margins
  480. #
  481. # TODO print number only from cmdlog
  482. self.SetMarginWidth(1, 0)
  483. self.SetMarginWidth(2, 0)
  484. if margin:
  485. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  486. self.SetMarginWidth(0, 30)
  487. else:
  488. self.SetMarginWidth(0, 0)
  489. #
  490. # miscellaneous
  491. #
  492. self.SetViewWhiteSpace(False)
  493. self.SetTabWidth(4)
  494. self.SetUseTabs(False)
  495. self.UsePopUp(True)
  496. self.SetSelBackground(True, "#FFFF00")
  497. self.SetUseHorizontalScrollBar(True)
  498. #
  499. # bindings
  500. #
  501. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  502. def OnTextSelectionChanged(self, event):
  503. """Copy selected text to clipboard and skip event.
  504. The same function is in TextCtrlAutoComplete class (prompt.py).
  505. """
  506. wx.CallAfter(self.Copy)
  507. event.Skip()
  508. def SetStyle(self):
  509. """Set styles for styled text output windows with type face
  510. and point size selected by user (Courier New 10 is default)"""
  511. typeface = UserSettings.Get(
  512. group='appearance',
  513. key='outputfont',
  514. subkey='type')
  515. if typeface == "":
  516. typeface = "Courier New"
  517. typesize = UserSettings.Get(
  518. group='appearance',
  519. key='outputfont',
  520. subkey='size')
  521. if typesize is None or typesize <= 0:
  522. typesize = 10
  523. typesize = float(typesize)
  524. self.StyleDefault = 0
  525. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (
  526. typeface,
  527. typesize)
  528. self.StyleCommand = 1
  529. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (
  530. typeface, typesize)
  531. self.StyleOutput = 2
  532. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (
  533. typeface,
  534. typesize)
  535. # fatal error
  536. self.StyleError = 3
  537. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (
  538. typeface,
  539. typesize)
  540. # warning
  541. self.StyleWarning = 4
  542. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (
  543. typeface, typesize)
  544. # message
  545. self.StyleMessage = 5
  546. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (
  547. typeface, typesize)
  548. # unknown
  549. self.StyleUnknown = 6
  550. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (
  551. typeface, typesize)
  552. # default and clear => init
  553. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  554. self.StyleClearAll()
  555. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  556. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  557. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  558. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  559. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  560. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  561. def OnDestroy(self, evt):
  562. """The clipboard contents can be preserved after
  563. the app has exited"""
  564. wx.TheClipboard.Flush()
  565. evt.Skip()
  566. def AddTextWrapped(self, txt, wrap=None):
  567. """Add string to text area.
  568. String is wrapped and linesep is also added to the end
  569. of the string"""
  570. # allow writing to output window
  571. self.SetReadOnly(False)
  572. if wrap:
  573. txt = textwrap.fill(txt, wrap) + '\n'
  574. else:
  575. if txt[-1] != '\n':
  576. txt += '\n'
  577. if '\r' in txt:
  578. self.linePos = -1
  579. for seg in txt.split('\r'):
  580. if self.linePos > -1:
  581. self.SetCurrentPos(self.linePos)
  582. self.ReplaceSelection(seg)
  583. else:
  584. self.linePos = self.GetCurrentPos()
  585. self.AddText(seg)
  586. else:
  587. self.linePos = self.GetCurrentPos()
  588. try:
  589. self.AddText(txt)
  590. except UnicodeDecodeError:
  591. enc = UserSettings.Get(
  592. group='atm', key='encoding', subkey='value')
  593. if enc:
  594. txt = unicode(txt, enc, errors='replace')
  595. elif 'GRASS_DB_ENCODING' in os.environ:
  596. txt = unicode(
  597. txt, os.environ['GRASS_DB_ENCODING'],
  598. errors='replace')
  599. else:
  600. txt = EncodeString(txt)
  601. self.AddText(txt)
  602. # reset output window to read only
  603. self.SetReadOnly(True)
  604. def AddStyledMessage(self, message, style=None):
  605. """Add message to text area.
  606. Handles messages with progress percentages.
  607. :param message: message to be added
  608. :param style: style of message, allowed values: 'message',
  609. 'warning', 'error' or None
  610. """
  611. # message prefix
  612. if style == 'warning':
  613. message = 'WARNING: ' + message
  614. elif style == 'error':
  615. message = 'ERROR: ' + message
  616. p1 = self.GetEndStyled()
  617. self.GotoPos(p1)
  618. # is this still needed?
  619. if '\b' in message:
  620. if self.linePos < 0:
  621. self.linePos = p1
  622. last_c = ''
  623. for c in message:
  624. if c == '\b':
  625. self.linePos -= 1
  626. else:
  627. if c == '\r':
  628. pos = self.GetCurLine()[1]
  629. # self.SetCurrentPos(pos)
  630. else:
  631. self.SetCurrentPos(self.linePos)
  632. self.ReplaceSelection(c)
  633. self.linePos = self.GetCurrentPos()
  634. if c != ' ':
  635. last_c = c
  636. if last_c not in ('0123456789'):
  637. self.AddTextWrapped('\n', wrap=None)
  638. self.linePos = -1
  639. else:
  640. self.linePos = -1 # don't force position
  641. if '\n' not in message:
  642. self.AddTextWrapped(message, wrap=60)
  643. else:
  644. self.AddTextWrapped(message, wrap=None)
  645. p2 = self.GetCurrentPos()
  646. if p2 >= p1:
  647. self.StartStyling(p1, 0xff)
  648. if style == 'error':
  649. self.SetStyling(p2 - p1, self.StyleError)
  650. elif style == 'warning':
  651. self.SetStyling(p2 - p1, self.StyleWarning)
  652. elif style == 'message':
  653. self.SetStyling(p2 - p1, self.StyleMessage)
  654. else: # unknown
  655. self.SetStyling(p2 - p1, self.StyleUnknown)
  656. self.EnsureCaretVisible()
  657. class GConsoleFrame(wx.Frame):
  658. """Standalone GConsole for testing only"""
  659. def __init__(self, parent, id=wx.ID_ANY, title="GConsole Test Frame",
  660. style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  661. wx.Frame.__init__(self, parent=parent, id=id, title=title, style=style)
  662. panel = wx.Panel(self, id=wx.ID_ANY)
  663. from lmgr.menudata import LayerManagerMenuData
  664. menuTreeBuilder = LayerManagerMenuData()
  665. self.gconsole = GConsole(guiparent=self)
  666. self.goutput = GConsoleWindow(parent=panel, gconsole=self.gconsole,
  667. menuModel=menuTreeBuilder.GetModel(),
  668. gcstyle=GC_SEARCH | GC_PROMPT)
  669. mainSizer = wx.BoxSizer(wx.VERTICAL)
  670. mainSizer.Add(
  671. self.goutput,
  672. proportion=1,
  673. flag=wx.EXPAND,
  674. border=0)
  675. panel.SetSizer(mainSizer)
  676. mainSizer.Fit(panel)
  677. self.SetMinSize((550, 500))
  678. def testGConsole():
  679. app = wx.App()
  680. frame = GConsoleFrame(parent=None)
  681. frame.Show()
  682. app.MainLoop()
  683. if __name__ == '__main__':
  684. testGConsole()