goutput.py 28 KB

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