goutput.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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, Notification
  30. from gui_core.prompt import GPromptSTC
  31. from core.settings import UserSettings
  32. from core.utils import _
  33. from gui_core.widgets import SearchModuleWidget
  34. GC_EMPTY = 0
  35. GC_SEARCH = 1
  36. GC_PROMPT = 2
  37. class GConsoleWindow(wx.SplitterWindow):
  38. """!Create and manage output console for commands run by GUI.
  39. """
  40. def __init__(self, parent, gconsole, menuModel = None, margin = False,
  41. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  42. gcstyle = GC_EMPTY,
  43. **kwargs):
  44. """!
  45. @param parent gui parent
  46. @param gconsole console logic
  47. @param menuModel tree model of modules (from menu)
  48. @param margin use margin in output pane (GStc)
  49. @param style wx.SplitterWindow style
  50. @param gcstyle GConsole style
  51. (GC_EMPTY, GC_PROMPT to show command prompt,
  52. GC_SEARCH to show search widget)
  53. """
  54. wx.SplitterWindow.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  55. self.SetName("GConsole")
  56. self.panelOutput = wx.Panel(parent=self, id=wx.ID_ANY)
  57. self.panelProgress = wx.Panel(parent=self.panelOutput, id=wx.ID_ANY, name='progressPanel')
  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._menuModel = menuModel
  63. self._gcstyle = gcstyle
  64. self.lineWidth = 80
  65. # signal which requests showing of a notification
  66. self.showNotification = Signal("GConsoleWindow.showNotification")
  67. # signal emitted when text appears in the console
  68. # parameter 'notification' suggests form of notification (according to
  69. # core.giface.Notification)
  70. self.contentChanged = Signal("GConsoleWindow.contentChanged")
  71. # progress bar
  72. self.progressbar = wx.Gauge(parent = self.panelProgress, id = wx.ID_ANY,
  73. range = 100, pos = (110, 50), size = (-1, 25),
  74. style = wx.GA_HORIZONTAL)
  75. self._gconsole.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  76. self._gconsole.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  77. self._gconsole.Bind(EVT_CMD_RUN, self.OnCmdRun)
  78. self._gconsole.Bind(EVT_CMD_DONE, self.OnCmdDone)
  79. self._gconsole.Bind(EVT_WRITE_LOG,
  80. lambda event:
  81. self.WriteLog(text = event.text,
  82. wrap = event.wrap,
  83. notification=event.notification))
  84. self._gconsole.Bind(EVT_WRITE_CMD_LOG,
  85. lambda event:
  86. self.WriteCmdLog(line = event.line,
  87. pid = event.pid,
  88. notification=event.notification))
  89. self._gconsole.Bind(EVT_WRITE_WARNING,
  90. lambda event:
  91. self.WriteWarning(line = event.line))
  92. self._gconsole.Bind(EVT_WRITE_ERROR,
  93. lambda event:
  94. self.WriteError(line = event.line))
  95. # text control for command output
  96. self.cmdOutput = GStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  97. wrap = None)
  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. notification=Notification.HIGHLIGHT):
  251. """!Generic method for writing log message in
  252. given style.
  253. Emits contentChanged signal.
  254. @param line text line
  255. @param style text style (see GStc)
  256. @param stdout write to stdout or stderr
  257. @param notification form of notification
  258. """
  259. self.cmdOutput.SetStyle()
  260. # documenting old behavior/implementation:
  261. # switch notebook if required
  262. # now, let user to bind to the old event
  263. if not style:
  264. style = self.cmdOutput.StyleDefault
  265. # p1 = self.cmdOutput.GetCurrentPos()
  266. p1 = self.cmdOutput.GetEndStyled()
  267. # self.cmdOutput.GotoPos(p1)
  268. self.cmdOutput.DocumentEnd()
  269. for line in text.splitlines():
  270. # fill space
  271. if len(line) < self.lineWidth:
  272. diff = self.lineWidth - len(line)
  273. line += diff * ' '
  274. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  275. p2 = self.cmdOutput.GetCurrentPos()
  276. self.cmdOutput.StartStyling(p1, 0xff)
  277. self.cmdOutput.SetStyling(p2 - p1, style)
  278. self.cmdOutput.EnsureCaretVisible()
  279. self.contentChanged.emit(notification=notification)
  280. def WriteCmdLog(self, line, pid=None, notification=Notification.MAKE_VISIBLE):
  281. """!Write message in selected style
  282. @param line message to be printed
  283. @param pid process pid or None
  284. @param switchPage True to switch page
  285. """
  286. if pid:
  287. line = '(' + str(pid) + ') ' + line
  288. self.WriteLog(line, style = self.cmdOutput.StyleCommand, notification=notification)
  289. def WriteWarning(self, line):
  290. """!Write message in warning style"""
  291. self.WriteLog(line, style = self.cmdOutput.StyleWarning, notification=Notification.MAKE_VISIBLE)
  292. def WriteError(self, line):
  293. """!Write message in error style"""
  294. self.WriteLog(line, style = self.cmdOutput.StyleError, notification=Notification.MAKE_VISIBLE)
  295. def OnOutputClear(self, event):
  296. """!Clear content of output window"""
  297. self.cmdOutput.SetReadOnly(False)
  298. self.cmdOutput.ClearAll()
  299. self.cmdOutput.SetReadOnly(True)
  300. self.progressbar.SetValue(0)
  301. def GetProgressBar(self):
  302. """!Return progress bar widget"""
  303. return self.progressbar
  304. def OnOutputSave(self, event):
  305. """!Save (selected) text from output window to the file"""
  306. text = self.cmdOutput.GetSelectedText()
  307. if not text:
  308. text = self.cmdOutput.GetText()
  309. # add newline if needed
  310. if len(text) > 0 and text[-1] != '\n':
  311. text += '\n'
  312. dlg = wx.FileDialog(self, message = _("Save file as..."),
  313. defaultFile = "grass_cmd_output.txt",
  314. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  315. {'txt': _("Text files"), 'files': _("Files")},
  316. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  317. # Show the dialog and retrieve the user response. If it is the OK response,
  318. # process the data.
  319. if dlg.ShowModal() == wx.ID_OK:
  320. path = dlg.GetPath()
  321. try:
  322. output = open(path, "w")
  323. output.write(text)
  324. except IOError, e:
  325. GError(_("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {'path': path, 'error': e})
  326. finally:
  327. output.close()
  328. message = _("Command output saved into '%s'") % path
  329. self.showNotification.emit(message = message)
  330. dlg.Destroy()
  331. def SetCopyingOfSelectedText(self, copy):
  332. """!Enable or disable copying of selected text in to clipboard.
  333. Effects prompt and output.
  334. @param copy True for enable, False for disable
  335. """
  336. if copy:
  337. self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  338. self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  339. else:
  340. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  341. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  342. def OnCmdOutput(self, event):
  343. """!Prints command output.
  344. Emits contentChanged signal.
  345. """
  346. message = event.text
  347. type = event.type
  348. self.cmdOutput.AddStyledMessage(message, type)
  349. if event.type in ('warning', 'error'):
  350. self.contentChanged.emit(notification=Notification.MAKE_VISIBLE)
  351. else:
  352. self.contentChanged.emit(notification=Notification.HIGHLIGHT)
  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 ResetFocus(self):
  412. """!Reset focus"""
  413. self.cmdPrompt.SetFocus()
  414. def GetPrompt(self):
  415. """!Get prompt"""
  416. return self.cmdPrompt
  417. class GStc(stc.StyledTextCtrl):
  418. """!Styled text control for GRASS stdout and stderr.
  419. Based on FrameOutErr.py
  420. Name: FrameOutErr.py
  421. Purpose: Redirecting stdout / stderr
  422. Author: Jean-Michel Fauth, Switzerland
  423. Copyright: (c) 2005-2007 Jean-Michel Fauth
  424. Licence: GPL
  425. """
  426. def __init__(self, parent, id, margin = False, wrap = None):
  427. stc.StyledTextCtrl.__init__(self, parent, id)
  428. self.parent = parent
  429. self.SetUndoCollection(True)
  430. self.SetReadOnly(True)
  431. # remember position of line begining (used for '\r')
  432. self.linePos = -1
  433. #
  434. # styles
  435. #
  436. self.SetStyle()
  437. #
  438. # line margins
  439. #
  440. # TODO print number only from cmdlog
  441. self.SetMarginWidth(1, 0)
  442. self.SetMarginWidth(2, 0)
  443. if margin:
  444. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  445. self.SetMarginWidth(0, 30)
  446. else:
  447. self.SetMarginWidth(0, 0)
  448. #
  449. # miscellaneous
  450. #
  451. self.SetViewWhiteSpace(False)
  452. self.SetTabWidth(4)
  453. self.SetUseTabs(False)
  454. self.UsePopUp(True)
  455. self.SetSelBackground(True, "#FFFF00")
  456. self.SetUseHorizontalScrollBar(True)
  457. #
  458. # bindings
  459. #
  460. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  461. def OnTextSelectionChanged(self, event):
  462. """!Copy selected text to clipboard and skip event.
  463. The same function is in TextCtrlAutoComplete class (prompt.py).
  464. """
  465. wx.CallAfter(self.Copy)
  466. event.Skip()
  467. def SetStyle(self):
  468. """!Set styles for styled text output windows with type face
  469. and point size selected by user (Courier New 10 is default)"""
  470. typeface = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  471. if typeface == "":
  472. typeface = "Courier New"
  473. typesize = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  474. if typesize == None or typesize <= 0:
  475. typesize = 10
  476. typesize = float(typesize)
  477. self.StyleDefault = 0
  478. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  479. self.StyleCommand = 1
  480. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  481. self.StyleOutput = 2
  482. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  483. # fatal error
  484. self.StyleError = 3
  485. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  486. # warning
  487. self.StyleWarning = 4
  488. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  489. # message
  490. self.StyleMessage = 5
  491. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  492. # unknown
  493. self.StyleUnknown = 6
  494. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  495. # default and clear => init
  496. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  497. self.StyleClearAll()
  498. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  499. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  500. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  501. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  502. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  503. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  504. def OnDestroy(self, evt):
  505. """!The clipboard contents can be preserved after
  506. the app has exited"""
  507. wx.TheClipboard.Flush()
  508. evt.Skip()
  509. def AddTextWrapped(self, txt, wrap = None):
  510. """!Add string to text area.
  511. String is wrapped and linesep is also added to the end
  512. of the string"""
  513. # allow writing to output window
  514. self.SetReadOnly(False)
  515. if wrap:
  516. txt = textwrap.fill(txt, wrap) + '\n'
  517. else:
  518. if txt[-1] != '\n':
  519. txt += '\n'
  520. if '\r' in txt:
  521. self.linePos = -1
  522. for seg in txt.split('\r'):
  523. if self.linePos > -1:
  524. self.SetCurrentPos(self.linePos)
  525. self.ReplaceSelection(seg)
  526. else:
  527. self.linePos = self.GetCurrentPos()
  528. self.AddText(seg)
  529. else:
  530. self.linePos = self.GetCurrentPos()
  531. try:
  532. self.AddText(txt)
  533. except UnicodeDecodeError:
  534. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  535. if enc:
  536. txt = unicode(txt, enc, errors = 'replace')
  537. elif 'GRASS_DB_ENCODING' in os.environ:
  538. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'], errors = 'replace')
  539. else:
  540. txt = EncodeString(txt)
  541. self.AddText(txt)
  542. # reset output window to read only
  543. self.SetReadOnly(True)
  544. def AddStyledMessage(self, message, style = None):
  545. """!Add message to text area.
  546. Handles messages with progress percentages.
  547. @param message message to be added
  548. @param style style of message, allowed values: 'message', 'warning', 'error' or None
  549. """
  550. # message prefix
  551. if style == 'warning':
  552. message = 'WARNING: ' + message
  553. elif style == 'error':
  554. message = 'ERROR: ' + message
  555. p1 = self.GetEndStyled()
  556. self.GotoPos(p1)
  557. # is this still needed?
  558. if '\b' in message:
  559. if self.linePos < 0:
  560. self.linePos = p1
  561. last_c = ''
  562. for c in message:
  563. if c == '\b':
  564. self.linePos -= 1
  565. else:
  566. if c == '\r':
  567. pos = self.GetCurLine()[1]
  568. # self.SetCurrentPos(pos)
  569. else:
  570. self.SetCurrentPos(self.linePos)
  571. self.ReplaceSelection(c)
  572. self.linePos = self.GetCurrentPos()
  573. if c != ' ':
  574. last_c = c
  575. if last_c not in ('0123456789'):
  576. self.AddTextWrapped('\n', wrap = None)
  577. self.linePos = -1
  578. else:
  579. self.linePos = -1 # don't force position
  580. if '\n' not in message:
  581. self.AddTextWrapped(message, wrap = 60)
  582. else:
  583. self.AddTextWrapped(message, wrap = None)
  584. p2 = self.GetCurrentPos()
  585. if p2 >= p1:
  586. self.StartStyling(p1, 0xff)
  587. if style == 'error':
  588. self.SetStyling(p2 - p1, self.StyleError)
  589. elif style == 'warning':
  590. self.SetStyling(p2 - p1, self.StyleWarning)
  591. elif style == 'message':
  592. self.SetStyling(p2 - p1, self.StyleMessage)
  593. else: # unknown
  594. self.SetStyling(p2 - p1, self.StyleUnknown)
  595. self.EnsureCaretVisible()
  596. class GConsoleFrame(wx.Frame):
  597. """!Standalone GConsole for testing only"""
  598. def __init__(self, parent, id = wx.ID_ANY, title = "GConsole Test Frame",
  599. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  600. wx.Frame.__init__(self, parent = parent, id = id, title = title, style = style)
  601. panel = wx.Panel(self, id = wx.ID_ANY)
  602. from lmgr.menudata import LayerManagerMenuData
  603. menuTreeBuilder = LayerManagerMenuData()
  604. self.gconsole = GConsole(guiparent=self)
  605. self.goutput = GConsoleWindow(parent = panel, gconsole = self.gconsole,
  606. menuModel=menuTreeBuilder.GetModel(),
  607. gcstyle = GC_SEARCH | GC_PROMPT)
  608. mainSizer = wx.BoxSizer(wx.VERTICAL)
  609. mainSizer.Add(item = self.goutput, proportion = 1, flag = wx.EXPAND, border = 0)
  610. panel.SetSizer(mainSizer)
  611. mainSizer.Fit(panel)
  612. self.SetMinSize((550, 500))
  613. def testGConsole():
  614. app = wx.PySimpleApp()
  615. frame = GConsoleFrame(parent = None)
  616. frame.Show()
  617. app.MainLoop()
  618. if __name__ == '__main__':
  619. testGConsole()