goutput.py 28 KB

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