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