goutput.py 27 KB

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