goutput.py 28 KB

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