goutput.py 29 KB

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