goutput.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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 core.settings import UserSettings
  31. from core.utils import _
  32. from gui_core.widgets import SearchModuleWidget
  33. GC_EMPTY = 0
  34. GC_SEARCH = 1
  35. GC_PROMPT = 2
  36. class GConsoleWindow(wx.SplitterWindow):
  37. """Create and manage output console for commands run by GUI.
  38. """
  39. def __init__(self, parent, gconsole, menuModel=None, margin=False,
  40. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  41. gcstyle=GC_EMPTY,
  42. **kwargs):
  43. """
  44. :param parent: gui parent
  45. :param gconsole: console logic
  46. :param menuModel: tree model of modules (from menu)
  47. :param margin: use margin in output pane (GStc)
  48. :param style: wx.SplitterWindow style
  49. :param gcstyle: GConsole style
  50. (GC_EMPTY, GC_PROMPT to show command prompt,
  51. GC_SEARCH to show search widget)
  52. """
  53. wx.SplitterWindow.__init__(
  54. self, parent, id=wx.ID_ANY, style=style, **kwargs)
  55. self.SetName("GConsole")
  56. self.panelOutput = wx.Panel(parent=self, id=wx.ID_ANY)
  57. self.panelProgress = wx.Panel(
  58. parent=self.panelOutput,
  59. id=wx.ID_ANY,
  60. name='progressPanel')
  61. self.panelPrompt = wx.Panel(parent=self, id=wx.ID_ANY)
  62. # initialize variables
  63. self.parent = parent # GMFrame | CmdPanel | ?
  64. self._gconsole = gconsole
  65. self._menuModel = menuModel
  66. self._gcstyle = gcstyle
  67. self.lineWidth = 80
  68. # signal which requests showing of a notification
  69. self.showNotification = Signal("GConsoleWindow.showNotification")
  70. # signal emitted when text appears in the console
  71. # parameter 'notification' suggests form of notification (according to
  72. # core.giface.Notification)
  73. self.contentChanged = Signal("GConsoleWindow.contentChanged")
  74. # progress bar
  75. self.progressbar = wx.Gauge(parent=self.panelProgress, id=wx.ID_ANY,
  76. range=100, pos=(110, 50), size=(-1, 25),
  77. style=wx.GA_HORIZONTAL)
  78. self._gconsole.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  79. self._gconsole.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  80. self._gconsole.Bind(EVT_CMD_RUN, self.OnCmdRun)
  81. self._gconsole.Bind(EVT_CMD_DONE, self.OnCmdDone)
  82. self._gconsole.writeLog.connect(self.WriteLog)
  83. self._gconsole.writeCmdLog.connect(self.WriteCmdLog)
  84. self._gconsole.writeWarning.connect(self.WriteWarning)
  85. self._gconsole.writeError.connect(self.WriteError)
  86. # text control for command output
  87. self.cmdOutput = GStc(
  88. parent=self.panelOutput,
  89. id=wx.ID_ANY,
  90. margin=margin,
  91. wrap=None)
  92. # search & command prompt
  93. # move to the if below
  94. # search depends on cmd prompt
  95. self.cmdPrompt = GPromptSTC(parent=self, menuModel=self._menuModel)
  96. self.cmdPrompt.promptRunCmd.connect(lambda cmd:
  97. self._gconsole.RunCmd(command=cmd))
  98. self.cmdPrompt.showNotification.connect(self.showNotification)
  99. if not self._gcstyle & GC_PROMPT:
  100. self.cmdPrompt.Hide()
  101. if self._gcstyle & GC_SEARCH:
  102. self.infoCollapseLabelExp = _(
  103. "Click here to show search module engine")
  104. self.infoCollapseLabelCol = _(
  105. "Click here to hide search module engine")
  106. self.searchPane = wx.CollapsiblePane(
  107. parent=self.panelOutput, label=self.infoCollapseLabelExp,
  108. style=wx.CP_DEFAULT_STYLE | wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  109. self.MakeSearchPaneContent(
  110. self.searchPane.GetPane(), self._menuModel)
  111. self.searchPane.Collapse(True)
  112. self.Bind(
  113. wx.EVT_COLLAPSIBLEPANE_CHANGED,
  114. self.OnSearchPaneChanged,
  115. self.searchPane)
  116. self.search.moduleSelected.connect(
  117. lambda name: self.cmdPrompt.SetTextAndFocus(name + ' '))
  118. else:
  119. self.search = None
  120. if self._gcstyle & GC_PROMPT:
  121. cmdLabel = _("Command prompt")
  122. self.outputBox = wx.StaticBox(
  123. parent=self.panelOutput,
  124. id=wx.ID_ANY,
  125. label=" %s " %
  126. _("Output window"))
  127. self.cmdBox = wx.StaticBox(parent=self.panelOutput, id=wx.ID_ANY,
  128. label=" %s " % cmdLabel)
  129. # buttons
  130. self.btnOutputClear = wx.Button(
  131. parent=self.panelOutput, id=wx.ID_CLEAR)
  132. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  133. self.btnCmdClear = wx.Button(parent=self.panelOutput, id=wx.ID_CLEAR)
  134. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  135. self.btnOutputSave = wx.Button(parent=self.panelOutput, id=wx.ID_SAVE)
  136. self.btnOutputSave.SetToolTipString(
  137. _("Save output window content to the file"))
  138. self.btnCmdAbort = wx.Button(parent=self.panelProgress, id=wx.ID_STOP)
  139. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  140. self.btnCmdProtocol = wx.ToggleButton(
  141. parent=self.panelOutput,
  142. id=wx.ID_ANY,
  143. label=_("&Log file"),
  144. size=self.btnCmdClear.GetSize())
  145. self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into "
  146. "a file; content saved when switching off."))
  147. if not self._gcstyle & GC_PROMPT:
  148. self.btnCmdClear.Hide()
  149. self.btnCmdProtocol.Hide()
  150. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  151. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  152. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  153. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self._gconsole.OnCmdAbort)
  154. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  155. self._layout()
  156. def _layout(self):
  157. """Do layout"""
  158. self.outputSizer = wx.BoxSizer(wx.VERTICAL)
  159. progressSizer = wx.BoxSizer(wx.HORIZONTAL)
  160. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  161. if self._gcstyle & GC_PROMPT:
  162. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  163. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  164. else:
  165. outBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
  166. cmdBtnSizer = wx.BoxSizer(wx.HORIZONTAL)
  167. if self._gcstyle & GC_PROMPT:
  168. promptSizer = wx.BoxSizer(wx.VERTICAL)
  169. promptSizer.Add(
  170. item=self.cmdPrompt,
  171. proportion=1,
  172. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
  173. border=3)
  174. helpText = wx.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(item=helpText,
  181. proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
  182. if self._gcstyle & GC_SEARCH:
  183. self.outputSizer.Add(item=self.searchPane, proportion=0,
  184. flag=wx.EXPAND | wx.ALL, border=3)
  185. self.outputSizer.Add(item=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. item=self.btnOutputClear,
  194. proportion=proportion,
  195. flag=wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  196. border=5)
  197. outBtnSizer.Add(item=self.btnOutputSave, proportion=proportion,
  198. flag=wx.ALIGN_RIGHT | wx.RIGHT | wx.BOTTOM, border=5)
  199. cmdBtnSizer.Add(
  200. item=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(item=self.btnCmdClear, proportion=1,
  205. flag=wx.ALIGN_CENTER | wx.RIGHT | wx.BOTTOM, border=5)
  206. progressSizer.Add(item=self.btnCmdAbort, proportion=0,
  207. flag=wx.ALL | wx.ALIGN_CENTER, border=5)
  208. progressSizer.Add(
  209. item=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(item=outBtnSizer, proportion=1,
  216. flag=wx.ALL | wx.ALIGN_CENTER, border=5)
  217. btnSizer.Add(
  218. item=cmdBtnSizer,
  219. proportion=1,
  220. flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT,
  221. border=5)
  222. self.outputSizer.Add(item=self.panelProgress, proportion=0,
  223. flag=wx.EXPAND)
  224. self.outputSizer.Add(item=btnSizer, proportion=0,
  225. flag=wx.EXPAND)
  226. self.outputSizer.Fit(self)
  227. self.outputSizer.SetSizeHints(self)
  228. self.panelOutput.SetSizer(self.outputSizer)
  229. # eliminate gtk_widget_size_allocate() warnings
  230. # avoid to use a deprecated method in wxPython >= 2.9
  231. getattr(self.outputSizer, 'FitInside',
  232. self.outputSizer.SetVirtualSizeHints)(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(item=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. self.cmdOutput.StartStyling(p1, 0xff)
  303. self.cmdOutput.SetStyling(p2 - p1, style)
  304. self.cmdOutput.EnsureCaretVisible()
  305. self.contentChanged.emit(notification=notification)
  306. def WriteCmdLog(self, text, pid=None,
  307. notification=Notification.MAKE_VISIBLE):
  308. """Write message in selected style
  309. :param text: message to be printed
  310. :param pid: process pid or None
  311. :param switchPage: True to switch page
  312. """
  313. if pid:
  314. text = '(' + str(pid) + ') ' + text
  315. self.WriteLog(
  316. text,
  317. style=self.cmdOutput.StyleCommand,
  318. notification=notification)
  319. def WriteWarning(self, text):
  320. """Write message in warning style"""
  321. self.WriteLog(text, style=self.cmdOutput.StyleWarning,
  322. notification=Notification.MAKE_VISIBLE)
  323. def WriteError(self, text):
  324. """Write message in error style"""
  325. self.WriteLog(text, style=self.cmdOutput.StyleError,
  326. notification=Notification.MAKE_VISIBLE)
  327. def OnOutputClear(self, event):
  328. """Clear content of output window"""
  329. self.cmdOutput.SetReadOnly(False)
  330. self.cmdOutput.ClearAll()
  331. self.cmdOutput.SetReadOnly(True)
  332. self.progressbar.SetValue(0)
  333. def GetProgressBar(self):
  334. """Return progress bar widget"""
  335. return self.progressbar
  336. def OnOutputSave(self, event):
  337. """Save (selected) text from output window to the file"""
  338. text = self.cmdOutput.GetSelectedText()
  339. if not text:
  340. text = self.cmdOutput.GetText()
  341. # add newline if needed
  342. if len(text) > 0 and text[-1] != '\n':
  343. text += '\n'
  344. dlg = wx.FileDialog(
  345. self, message=_("Save file as..."),
  346. defaultFile="grass_cmd_output.txt",
  347. wildcard=_("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  348. {'txt': _("Text files"),
  349. 'files': _("Files")},
  350. style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  351. # Show the dialog and retrieve the user response. If it is the OK response,
  352. # process the data.
  353. if dlg.ShowModal() == wx.ID_OK:
  354. path = dlg.GetPath()
  355. try:
  356. output = open(path, "w")
  357. output.write(EncodeString(text))
  358. except IOError as e:
  359. GError(
  360. _("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {
  361. 'path': path,
  362. 'error': e})
  363. finally:
  364. output.close()
  365. message = _("Command output saved into '%s'") % path
  366. self.showNotification.emit(message=message)
  367. dlg.Destroy()
  368. def SetCopyingOfSelectedText(self, copy):
  369. """Enable or disable copying of selected text in to clipboard.
  370. Effects prompt and output.
  371. :param bool copy: True for enable, False for disable
  372. """
  373. if copy:
  374. self.cmdPrompt.Bind(
  375. stc.EVT_STC_PAINTED,
  376. self.cmdPrompt.OnTextSelectionChanged)
  377. self.cmdOutput.Bind(
  378. stc.EVT_STC_PAINTED,
  379. self.cmdOutput.OnTextSelectionChanged)
  380. else:
  381. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  382. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  383. def OnCmdOutput(self, event):
  384. """Prints command output.
  385. Emits contentChanged signal.
  386. """
  387. message = event.text
  388. type = event.type
  389. self.cmdOutput.AddStyledMessage(message, type)
  390. if event.type in ('warning', 'error'):
  391. self.contentChanged.emit(notification=Notification.MAKE_VISIBLE)
  392. else:
  393. self.contentChanged.emit(notification=Notification.HIGHLIGHT)
  394. def OnCmdProgress(self, event):
  395. """Update progress message info"""
  396. self.progressbar.SetValue(event.value)
  397. event.Skip()
  398. def CmdProtocolSave(self):
  399. """Save list of manually entered commands into a text log file"""
  400. if not hasattr(self, 'cmdFileProtocol'):
  401. return # it should not happen
  402. try:
  403. output = open(self.cmdFileProtocol, "a")
  404. cmds = self.cmdPrompt.GetCommands()
  405. output.write('\n'.join(cmds))
  406. if len(cmds) > 0:
  407. output.write('\n')
  408. except IOError as e:
  409. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  410. {'filePath': self.cmdFileProtocol, 'error': e})
  411. finally:
  412. output.close()
  413. message = _("Command log saved to '%s'") % self.cmdFileProtocol
  414. self.showNotification.emit(message=message)
  415. del self.cmdFileProtocol
  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 begining (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 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. enc = UserSettings.Get(
  593. group='atm', key='encoding', subkey='value')
  594. if enc:
  595. txt = unicode(txt, enc, errors='replace')
  596. elif 'GRASS_DB_ENCODING' in os.environ:
  597. txt = unicode(
  598. txt, os.environ['GRASS_DB_ENCODING'],
  599. errors='replace')
  600. else:
  601. txt = EncodeString(txt)
  602. self.AddText(txt)
  603. # reset output window to read only
  604. self.SetReadOnly(True)
  605. def AddStyledMessage(self, message, style=None):
  606. """Add message to text area.
  607. Handles messages with progress percentages.
  608. :param message: message to be added
  609. :param style: style of message, allowed values: 'message',
  610. 'warning', 'error' or None
  611. """
  612. # message prefix
  613. if style == 'warning':
  614. message = 'WARNING: ' + message
  615. elif style == 'error':
  616. message = 'ERROR: ' + message
  617. p1 = self.GetEndStyled()
  618. self.GotoPos(p1)
  619. # is this still needed?
  620. if '\b' in message:
  621. if self.linePos < 0:
  622. self.linePos = p1
  623. last_c = ''
  624. for c in message:
  625. if c == '\b':
  626. self.linePos -= 1
  627. else:
  628. if c == '\r':
  629. pos = self.GetCurLine()[1]
  630. # self.SetCurrentPos(pos)
  631. else:
  632. self.SetCurrentPos(self.linePos)
  633. self.ReplaceSelection(c)
  634. self.linePos = self.GetCurrentPos()
  635. if c != ' ':
  636. last_c = c
  637. if last_c not in ('0123456789'):
  638. self.AddTextWrapped('\n', wrap=None)
  639. self.linePos = -1
  640. else:
  641. self.linePos = -1 # don't force position
  642. if '\n' not in message:
  643. self.AddTextWrapped(message, wrap=60)
  644. else:
  645. self.AddTextWrapped(message, wrap=None)
  646. p2 = self.GetCurrentPos()
  647. if p2 >= p1:
  648. self.StartStyling(p1, 0xff)
  649. if style == 'error':
  650. self.SetStyling(p2 - p1, self.StyleError)
  651. elif style == 'warning':
  652. self.SetStyling(p2 - p1, self.StyleWarning)
  653. elif style == 'message':
  654. self.SetStyling(p2 - p1, self.StyleMessage)
  655. else: # unknown
  656. self.SetStyling(p2 - p1, self.StyleUnknown)
  657. self.EnsureCaretVisible()
  658. class GConsoleFrame(wx.Frame):
  659. """Standalone GConsole for testing only"""
  660. def __init__(self, parent, id=wx.ID_ANY, title="GConsole Test Frame",
  661. style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  662. wx.Frame.__init__(self, parent=parent, id=id, title=title, style=style)
  663. panel = wx.Panel(self, id=wx.ID_ANY)
  664. from lmgr.menudata import LayerManagerMenuData
  665. menuTreeBuilder = LayerManagerMenuData()
  666. self.gconsole = GConsole(guiparent=self)
  667. self.goutput = GConsoleWindow(parent=panel, gconsole=self.gconsole,
  668. menuModel=menuTreeBuilder.GetModel(),
  669. gcstyle=GC_SEARCH | GC_PROMPT)
  670. mainSizer = wx.BoxSizer(wx.VERTICAL)
  671. mainSizer.Add(
  672. item=self.goutput,
  673. proportion=1,
  674. flag=wx.EXPAND,
  675. border=0)
  676. panel.SetSizer(mainSizer)
  677. mainSizer.Fit(panel)
  678. self.SetMinSize((550, 500))
  679. def testGConsole():
  680. app = wx.App()
  681. frame = GConsoleFrame(parent=None)
  682. frame.Show()
  683. app.MainLoop()
  684. if __name__ == '__main__':
  685. testGConsole()