goutput.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. """!
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GConsole
  7. - goutput::GStdout
  8. - goutput::GStderr
  9. - goutput::GStc
  10. (C) 2007-2012 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Martin Landa <landa.martin gmail.com>
  15. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  16. """
  17. import os
  18. import sys
  19. import textwrap
  20. import time
  21. import threading
  22. import Queue
  23. import codecs
  24. import locale
  25. import wx
  26. from wx import stc
  27. from wx.lib.newevent import NewEvent
  28. import grass.script as grass
  29. from grass.script import task as gtask
  30. from core import globalvar
  31. from core import utils
  32. from core.gcmd import CommandThread, GMessage, GError, GException, EncodeString
  33. from gui_core.forms import GUI
  34. from gui_core.prompt import GPromptSTC
  35. from core.debug import Debug
  36. from core.settings import UserSettings, GetDisplayVectSettings
  37. from gui_core.widgets import SearchModuleWidget, EVT_MODULE_SELECTED
  38. from core.modulesdata import ModulesData
  39. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  40. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  41. wxCmdRun, EVT_CMD_RUN = NewEvent()
  42. wxCmdDone, EVT_CMD_DONE = NewEvent()
  43. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  44. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  45. GC_EMPTY = 0
  46. GC_SEARCH = 1
  47. GC_PROMPT = 2
  48. def GrassCmd(cmd, env = None, stdout = None, stderr = None):
  49. """!Return GRASS command thread"""
  50. return CommandThread(cmd, env = env,
  51. stdout = stdout, stderr = stderr)
  52. class CmdThread(threading.Thread):
  53. """!Thread for GRASS commands"""
  54. requestId = 0
  55. def __init__(self, parent, requestQ = None, resultQ = None, **kwds):
  56. threading.Thread.__init__(self, **kwds)
  57. if requestQ is None:
  58. self.requestQ = Queue.Queue()
  59. else:
  60. self.requestQ = requestQ
  61. if resultQ is None:
  62. self.resultQ = Queue.Queue()
  63. else:
  64. self.resultQ = resultQ
  65. self.setDaemon(True)
  66. self.parent = parent # GConsole
  67. self._want_abort_all = False
  68. self.start()
  69. def RunCmd(self, *args, **kwds):
  70. """!Run command in queue
  71. @param args unnamed command arguments
  72. @param kwds named command arguments
  73. @return request id in queue
  74. """
  75. CmdThread.requestId += 1
  76. self.requestCmd = None
  77. self.requestQ.put((CmdThread.requestId, args, kwds))
  78. return CmdThread.requestId
  79. def SetId(self, id):
  80. """!Set starting id"""
  81. CmdThread.requestId = id
  82. def run(self):
  83. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  84. while True:
  85. requestId, args, kwds = self.requestQ.get()
  86. for key in ('callable', 'onDone', 'onPrepare', 'userData'):
  87. if key in kwds:
  88. vars()[key] = kwds[key]
  89. del kwds[key]
  90. else:
  91. vars()[key] = None
  92. if not vars()['callable']:
  93. vars()['callable'] = GrassCmd
  94. requestTime = time.time()
  95. # prepare
  96. event = wxCmdPrepare(cmd = args[0],
  97. time = requestTime,
  98. pid = requestId,
  99. onPrepare = vars()['onPrepare'],
  100. userData = vars()['userData'])
  101. wx.PostEvent(self.parent, event)
  102. # run command
  103. event = wxCmdRun(cmd = args[0],
  104. pid = requestId)
  105. wx.PostEvent(self.parent, event)
  106. time.sleep(.1)
  107. self.requestCmd = vars()['callable'](*args, **kwds)
  108. if self._want_abort_all:
  109. self.requestCmd.abort()
  110. if self.requestQ.empty():
  111. self._want_abort_all = False
  112. self.resultQ.put((requestId, self.requestCmd.run()))
  113. try:
  114. returncode = self.requestCmd.module.returncode
  115. except AttributeError:
  116. returncode = 0 # being optimistic
  117. try:
  118. aborted = self.requestCmd.aborted
  119. except AttributeError:
  120. aborted = False
  121. time.sleep(.1)
  122. # set default color table for raster data
  123. if UserSettings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'enabled') and \
  124. args[0][0][:2] == 'r.':
  125. colorTable = UserSettings.Get(group = 'rasterLayer', key = 'colorTable', subkey = 'selection')
  126. mapName = None
  127. if args[0][0] == 'r.mapcalc':
  128. try:
  129. mapName = args[0][1].split('=', 1)[0].strip()
  130. except KeyError:
  131. pass
  132. else:
  133. moduleInterface = GUI(show = None).ParseCommand(args[0])
  134. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  135. if outputParam and outputParam['prompt'] == 'raster':
  136. mapName = outputParam['value']
  137. if mapName:
  138. argsColor = list(args)
  139. argsColor[0] = [ 'r.colors',
  140. 'map=%s' % mapName,
  141. 'color=%s' % colorTable ]
  142. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  143. self.resultQ.put((requestId, self.requestCmdColor.run()))
  144. event = wxCmdDone(cmd = args[0],
  145. aborted = aborted,
  146. returncode = returncode,
  147. time = requestTime,
  148. pid = requestId,
  149. onDone = vars()['onDone'],
  150. userData = vars()['userData'])
  151. # send event
  152. wx.PostEvent(self.parent, event)
  153. def abort(self, abortall = True):
  154. """!Abort command(s)"""
  155. if abortall:
  156. self._want_abort_all = True
  157. self.requestCmd.abort()
  158. if self.requestQ.empty():
  159. self._want_abort_all = False
  160. # Occurs event when some new text appears.
  161. # Text priority is specified by priority attribute.
  162. # Priority is 1 (lowest), 2, 3 (highest);
  163. # value 0 is currently not used and probably will not be used.
  164. # In theory, it can be used when text is completely uninteresting.
  165. # It is similar to wx.EVT_TEXT.
  166. # However, the new text or the whole text are not event attributes.
  167. gOutputText, EVT_OUTPUT_TEXT = NewEvent()
  168. class GConsole(wx.SplitterWindow):
  169. """!Create and manage output console for commands run by GUI.
  170. """
  171. def __init__(self, parent, id = wx.ID_ANY, margin = False,
  172. frame = None,
  173. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  174. gcstyle = GC_EMPTY,
  175. **kwargs):
  176. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  177. self.SetName("GConsole")
  178. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  179. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  180. # initialize variables
  181. self.parent = parent # GMFrame | CmdPanel | ?
  182. if frame:
  183. self.frame = frame
  184. else:
  185. self.frame = parent
  186. self._gcstyle = gcstyle
  187. self.lineWidth = 80
  188. # create queues
  189. self.requestQ = Queue.Queue()
  190. self.resultQ = Queue.Queue()
  191. # progress bar
  192. self.progressbar = wx.Gauge(parent = self.panelOutput, id = wx.ID_ANY,
  193. range = 100, pos = (110, 50), size = (-1, 25),
  194. style = wx.GA_HORIZONTAL)
  195. self.progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  196. # text control for command output
  197. self.cmdOutput = GStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  198. wrap = None)
  199. self.cmdOutputTimer = wx.Timer(self.cmdOutput, id = wx.ID_ANY)
  200. self.cmdOutput.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  201. self.cmdOutput.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  202. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  203. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  204. self.Bind(EVT_CMD_PREPARE, self.OnCmdPrepare)
  205. # information about available modules
  206. modulesData = ModulesData()
  207. # search & command prompt
  208. # move to the if below
  209. # search depends on cmd prompt
  210. self.cmdPrompt = GPromptSTC(parent = self, modulesData = modulesData)
  211. if not self._gcstyle & GC_PROMPT:
  212. self.cmdPrompt.Hide()
  213. if self._gcstyle & GC_SEARCH:
  214. self.infoCollapseLabelExp = _("Click here to show search module engine")
  215. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  216. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  217. label = self.infoCollapseLabelExp,
  218. style = wx.CP_DEFAULT_STYLE |
  219. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  220. self.MakeSearchPaneContent(self.searchPane.GetPane(), modulesData)
  221. self.searchPane.Collapse(True)
  222. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  223. self.search.Bind(EVT_MODULE_SELECTED,
  224. lambda event:
  225. self.cmdPrompt.SetTextAndFocus(event.name + ' '))
  226. else:
  227. self.search = None
  228. # stream redirection
  229. self.cmdStdOut = GStdout(self)
  230. self.cmdStdErr = GStderr(self)
  231. # thread
  232. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  233. self.outputBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  234. label = " %s " % _("Output window"))
  235. if self._gcstyle & GC_PROMPT:
  236. cmdLabel = _("Command prompt")
  237. else:
  238. cmdLabel = _("Command")
  239. self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  240. label = " %s " % cmdLabel)
  241. # buttons
  242. self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  243. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  244. self.btnCmdClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  245. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  246. self.btnOutputSave = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
  247. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  248. self.btnCmdAbort = wx.Button(parent = self.panelOutput, id = wx.ID_STOP)
  249. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  250. self.btnCmdAbort.Enable(False)
  251. self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
  252. label = _("&Protocol"),
  253. size = self.btnCmdClear.GetSize())
  254. self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into file; "
  255. "content saved when switching off."))
  256. if not self._gcstyle & GC_PROMPT:
  257. self.btnCmdClear.Hide()
  258. self.btnCmdProtocol.Hide()
  259. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  260. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  261. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  262. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  263. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  264. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  265. self._layout()
  266. def _layout(self):
  267. """!Do layout"""
  268. outputSizer = wx.BoxSizer(wx.VERTICAL)
  269. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  270. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  271. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  272. if self._gcstyle & GC_PROMPT:
  273. promptSizer = wx.BoxSizer(wx.VERTICAL)
  274. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  275. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  276. if self._gcstyle & GC_SEARCH:
  277. outputSizer.Add(item = self.searchPane, proportion = 0,
  278. flag = wx.EXPAND | wx.ALL, border = 3)
  279. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  280. flag = wx.EXPAND | wx.ALL, border = 3)
  281. outputSizer.Add(item = self.progressbar, proportion = 0,
  282. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  283. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  284. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  285. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  286. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  287. cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
  288. flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  289. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  290. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  291. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  292. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  293. if self._gcstyle & GC_PROMPT:
  294. proportion = (2, 3)
  295. else:
  296. proportion = (1, 1)
  297. btnSizer.Add(item = outBtnSizer, proportion = proportion[0],
  298. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  299. btnSizer.Add(item = cmdBtnSizer, proportion = proportion[1],
  300. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  301. outputSizer.Add(item = btnSizer, proportion = 0,
  302. flag = wx.EXPAND)
  303. outputSizer.Fit(self)
  304. outputSizer.SetSizeHints(self)
  305. self.panelOutput.SetSizer(outputSizer)
  306. # eliminate gtk_widget_size_allocate() warnings
  307. outputSizer.SetVirtualSizeHints(self.panelOutput)
  308. if self._gcstyle & GC_PROMPT:
  309. promptSizer.Fit(self)
  310. promptSizer.SetSizeHints(self)
  311. self.panelPrompt.SetSizer(promptSizer)
  312. # split window
  313. if self._gcstyle & GC_PROMPT:
  314. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  315. else:
  316. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  317. self.Unsplit()
  318. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  319. self.SetSashGravity(1.0)
  320. # layout
  321. self.SetAutoLayout(True)
  322. self.Layout()
  323. def MakeSearchPaneContent(self, pane, modulesData):
  324. """!Create search pane"""
  325. border = wx.BoxSizer(wx.VERTICAL)
  326. self.search = SearchModuleWidget(parent = pane,
  327. modulesData = modulesData)
  328. border.Add(item = self.search, proportion = 0,
  329. flag = wx.EXPAND | wx.ALL, border = 1)
  330. pane.SetSizer(border)
  331. border.Fit(pane)
  332. def OnSearchPaneChanged(self, event):
  333. """!Collapse search module box"""
  334. if self.searchPane.IsExpanded():
  335. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  336. else:
  337. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  338. self.panelOutput.Layout()
  339. self.panelOutput.SendSizeEvent()
  340. def GetPanel(self, prompt = True):
  341. """!Get panel
  342. @param prompt get prompt / output panel
  343. @return wx.Panel reference
  344. """
  345. if prompt:
  346. return self.panelPrompt
  347. return self.panelOutput
  348. def Redirect(self):
  349. """!Redirect stdout/stderr
  350. """
  351. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  352. # don't redirect when debugging is enabled
  353. sys.stdout = self.cmdStdOut
  354. sys.stderr = self.cmdStdErr
  355. else:
  356. enc = locale.getdefaultlocale()[1]
  357. if enc:
  358. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  359. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  360. else:
  361. sys.stdout = sys.__stdout__
  362. sys.stderr = sys.__stderr__
  363. def WriteLog(self, text, style = None, wrap = None,
  364. switchPage = False):
  365. """!Generic method for writing log message in
  366. given style
  367. @param line text line
  368. @param style text style (see GStc)
  369. @param stdout write to stdout or stderr
  370. """
  371. self.cmdOutput.SetStyle()
  372. # documenting old behavior/implementation:
  373. # switch notebook if required
  374. if switchPage:
  375. priority = 2
  376. else:
  377. priority = 1
  378. event = gOutputText(priority = priority)
  379. wx.PostEvent(self, event)
  380. if not style:
  381. style = self.cmdOutput.StyleDefault
  382. # p1 = self.cmdOutput.GetCurrentPos()
  383. p1 = self.cmdOutput.GetEndStyled()
  384. # self.cmdOutput.GotoPos(p1)
  385. self.cmdOutput.DocumentEnd()
  386. for line in text.splitlines():
  387. # fill space
  388. if len(line) < self.lineWidth:
  389. diff = self.lineWidth - len(line)
  390. line += diff * ' '
  391. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  392. p2 = self.cmdOutput.GetCurrentPos()
  393. self.cmdOutput.StartStyling(p1, 0xff)
  394. self.cmdOutput.SetStyling(p2 - p1, style)
  395. self.cmdOutput.EnsureCaretVisible()
  396. def WriteCmdLog(self, line, pid = None, switchPage = True):
  397. """!Write message in selected style
  398. @param line message to be printed
  399. @param pid process pid or None
  400. @param switchPage True to switch page
  401. """
  402. if pid:
  403. line = '(' + str(pid) + ') ' + line
  404. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  405. def WriteWarning(self, line):
  406. """!Write message in warning style"""
  407. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  408. def WriteError(self, line):
  409. """!Write message in error style"""
  410. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  411. def RunCmd(self, command, compReg = True, switchPage = False, skipInterface = False,
  412. onDone = None, onPrepare = None, userData = None):
  413. """!Run command typed into console command prompt (GPrompt).
  414. @todo Display commands (*.d) are captured and processed
  415. separately by mapdisp.py. Display commands are rendered in map
  416. display widget that currently has the focus (as indicted by
  417. mdidx).
  418. @param command command given as a list (produced e.g. by utils.split())
  419. @param compReg True use computation region
  420. @param switchPage switch to output page
  421. @param skipInterface True to do not launch GRASS interface
  422. parser when command has no arguments given
  423. @param onDone function to be called when command is finished
  424. @param onPrepare function to be called before command is launched
  425. @param userData data defined for the command
  426. """
  427. if len(command) == 0:
  428. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  429. return
  430. # update history file
  431. env = grass.gisenv()
  432. try:
  433. filePath = os.path.join(env['GISDBASE'],
  434. env['LOCATION_NAME'],
  435. env['MAPSET'],
  436. '.bash_history')
  437. fileHistory = codecs.open(filePath, encoding = 'utf-8', mode = 'a')
  438. except IOError, e:
  439. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  440. {'filePath': filePath, 'error' : e },
  441. parent = self.frame)
  442. fileHistory = None
  443. if fileHistory:
  444. try:
  445. fileHistory.write(' '.join(command) + os.linesep)
  446. finally:
  447. fileHistory.close()
  448. if command[0] in globalvar.grassCmd:
  449. # send GRASS command without arguments to GUI command interface
  450. # except display commands (they are handled differently)
  451. if self.frame.GetName() == "LayerManager" and \
  452. command[0][0:2] == "d." and \
  453. 'help' not in ' '.join(command[1:]):
  454. # display GRASS commands
  455. try:
  456. layertype = {'d.rast' : 'raster',
  457. 'd.rast3d' : '3d-raster',
  458. 'd.rgb' : 'rgb',
  459. 'd.his' : 'his',
  460. 'd.shaded' : 'shaded',
  461. 'd.legend' : 'rastleg',
  462. 'd.rast.arrow' : 'rastarrow',
  463. 'd.rast.num' : 'rastnum',
  464. 'd.rast.leg' : 'maplegend',
  465. 'd.vect' : 'vector',
  466. 'd.thematic.area': 'thememap',
  467. 'd.vect.chart' : 'themechart',
  468. 'd.grid' : 'grid',
  469. 'd.geodesic' : 'geodesic',
  470. 'd.rhumbline' : 'rhumb',
  471. 'd.labels' : 'labels',
  472. 'd.barscale' : 'barscale',
  473. 'd.redraw' : 'redraw'}[command[0]]
  474. except KeyError:
  475. GMessage(parent = self.frame,
  476. message = _("Command '%s' not yet implemented in the WxGUI. "
  477. "Try adding it as a command layer instead.") % command[0])
  478. return
  479. if layertype == 'barscale':
  480. self.frame.GetLayerTree().GetMapDisplay().OnAddBarscale(None)
  481. elif layertype == 'rastleg':
  482. self.frame.GetLayerTree().GetMapDisplay().OnAddLegend(None)
  483. elif layertype == 'redraw':
  484. self.frame.GetLayerTree().GetMapDisplay().OnRender(None)
  485. else:
  486. # add layer into layer tree
  487. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  488. layerType = layertype)
  489. if self.frame.GetName() == "LayerManager":
  490. self.frame.GetLayerTree().AddLayer(ltype = layertype,
  491. lname = lname,
  492. lcmd = command)
  493. else:
  494. # other GRASS commands (r|v|g|...)
  495. try:
  496. task = GUI(show = None).ParseCommand(command)
  497. except GException, e:
  498. GError(parent = self,
  499. message = unicode(e),
  500. showTraceback = False)
  501. return
  502. hasParams = False
  503. if task:
  504. options = task.get_options()
  505. hasParams = options['params'] and options['flags']
  506. # check for <input>=-
  507. for p in options['params']:
  508. if p.get('prompt', '') == 'input' and \
  509. p.get('element', '') == 'file' and \
  510. p.get('age', 'new') == 'old' and \
  511. p.get('value', '') == '-':
  512. GError(parent = self,
  513. message = _("Unable to run command:\n%(cmd)s\n\n"
  514. "Option <%(opt)s>: read from standard input is not "
  515. "supported by wxGUI") % { 'cmd': ' '.join(command),
  516. 'opt': p.get('name', '') })
  517. return
  518. if len(command) == 1 and hasParams and \
  519. command[0] != 'v.krige':
  520. # no arguments given
  521. try:
  522. GUI(parent = self, lmgr = self.parent).ParseCommand(command)
  523. except GException, e:
  524. print >> sys.stderr, e
  525. return
  526. # documenting old behavior/implementation:
  527. # switch and focus if required
  528. # TODO: this probably should be run command event
  529. if switchPage:
  530. priority = 3
  531. event = gOutputText(priority = priority)
  532. wx.PostEvent(self, event)
  533. # activate computational region (set with g.region)
  534. # for all non-display commands.
  535. if compReg:
  536. tmpreg = os.getenv("GRASS_REGION")
  537. if "GRASS_REGION" in os.environ:
  538. del os.environ["GRASS_REGION"]
  539. # process GRASS command with argument
  540. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  541. onDone = onDone, onPrepare = onPrepare, userData = userData,
  542. env = os.environ.copy())
  543. self.cmdOutputTimer.Start(50)
  544. # deactivate computational region and return to display settings
  545. if compReg and tmpreg:
  546. os.environ["GRASS_REGION"] = tmpreg
  547. else:
  548. # Send any other command to the shell. Send output to
  549. # console output window
  550. if len(command) == 1 and not skipInterface:
  551. try:
  552. task = gtask.parse_interface(command[0])
  553. except:
  554. task = None
  555. else:
  556. task = None
  557. if task:
  558. # process GRASS command without argument
  559. GUI(parent = self, lmgr = self.parent).ParseCommand(command)
  560. else:
  561. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  562. onDone = onDone, onPrepare = onPrepare, userData = userData)
  563. self.cmdOutputTimer.Start(50)
  564. def OnOutputClear(self, event):
  565. """!Clear content of output window"""
  566. self.cmdOutput.SetReadOnly(False)
  567. self.cmdOutput.ClearAll()
  568. self.cmdOutput.SetReadOnly(True)
  569. self.progressbar.SetValue(0)
  570. def GetProgressBar(self):
  571. """!Return progress bar widget"""
  572. return self.progressbar
  573. def GetLog(self, err = False):
  574. """!Get widget used for logging
  575. @param err True to get stderr widget
  576. """
  577. if err:
  578. return self.cmdStdErr
  579. return self.cmdStdOut
  580. def OnOutputSave(self, event):
  581. """!Save (selected) text from output window to the file"""
  582. text = self.cmdOutput.GetSelectedText()
  583. if not text:
  584. text = self.cmdOutput.GetText()
  585. # add newline if needed
  586. if len(text) > 0 and text[-1] != '\n':
  587. text += '\n'
  588. dlg = wx.FileDialog(self, message = _("Save file as..."),
  589. defaultFile = "grass_cmd_output.txt",
  590. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  591. {'txt': _("Text files"), 'files': _("Files")},
  592. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  593. # Show the dialog and retrieve the user response. If it is the OK response,
  594. # process the data.
  595. if dlg.ShowModal() == wx.ID_OK:
  596. path = dlg.GetPath()
  597. try:
  598. output = open(path, "w")
  599. output.write(text)
  600. except IOError, e:
  601. GError(_("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {'path': path, 'error': e})
  602. finally:
  603. output.close()
  604. self.frame.SetStatusText(_("Commands output saved into '%s'") % path)
  605. dlg.Destroy()
  606. def GetCmd(self):
  607. """!Get running command or None"""
  608. return self.requestQ.get()
  609. def SetCopyingOfSelectedText(self, copy):
  610. """!Enable or disable copying of selected text in to clipboard.
  611. Effects prompt and output.
  612. @param copy True for enable, False for disable
  613. """
  614. if copy:
  615. self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  616. self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  617. else:
  618. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  619. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  620. def OnCmdOutput(self, event):
  621. """!Print command output"""
  622. message = event.text
  623. type = event.type
  624. self.cmdOutput.AddStyledMessage(message, type)
  625. # documenting old behavior/implementation:
  626. # add elipses if not active
  627. event = gOutputText(priority = 1)
  628. wx.PostEvent(self, event)
  629. def OnCmdProgress(self, event):
  630. """!Update progress message info"""
  631. self.progressbar.SetValue(event.value)
  632. def CmdProtocolSave(self):
  633. """Save commands protocol into the file"""
  634. if not hasattr(self, 'cmdFileProtocol'):
  635. return # it should not happen
  636. try:
  637. output = open(self.cmdFileProtocol, "w")
  638. cmds = self.cmdPrompt.GetCommands()
  639. output.write('\n'.join(cmds))
  640. if len(cmds) > 0:
  641. output.write('\n')
  642. except IOError, e:
  643. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  644. {'filePath': self.cmdFileProtocol, 'error': e})
  645. finally:
  646. output.close()
  647. self.frame.SetStatusText(_("Commands protocol saved into '%s'") % self.cmdFileProtocol)
  648. del self.cmdFileProtocol
  649. def OnCmdProtocol(self, event = None):
  650. """!Save commands into file"""
  651. if not event.IsChecked():
  652. # stop capturing commands, save list of commands to the
  653. # protocol file
  654. self.CmdProtocolSave()
  655. else:
  656. # start capturing commands
  657. self.cmdPrompt.ClearCommands()
  658. # ask for the file
  659. dlg = wx.FileDialog(self, message = _("Save file as..."),
  660. defaultFile = "grass_cmd_protocol.txt",
  661. wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") %
  662. {'txt': _("Text files"), 'files': _("Files")},
  663. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  664. if dlg.ShowModal() == wx.ID_OK:
  665. self.cmdFileProtocol = dlg.GetPath()
  666. else:
  667. wx.CallAfter(self.btnCmdProtocol.SetValue, False)
  668. dlg.Destroy()
  669. event.Skip()
  670. def OnCmdAbort(self, event):
  671. """!Abort running command"""
  672. self.cmdThread.abort()
  673. def OnCmdRun(self, event):
  674. """!Run command"""
  675. if self.frame.GetName() == 'Modeler':
  676. self.frame.OnCmdRun(event)
  677. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  678. self.btnCmdAbort.Enable()
  679. def OnCmdPrepare(self, event):
  680. """!Prepare for running command"""
  681. if self.frame.GetName() == 'Modeler':
  682. self.frame.OnCmdPrepare(event)
  683. event.Skip()
  684. def OnCmdDone(self, event):
  685. """!Command done (or aborted)"""
  686. if self.frame.GetName() == 'Modeler':
  687. self.frame.OnCmdDone(event)
  688. # Process results here
  689. try:
  690. ctime = time.time() - event.time
  691. if ctime < 60:
  692. stime = _("%d sec") % int(ctime)
  693. else:
  694. mtime = int(ctime / 60)
  695. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  696. 'sec' : int(ctime - (mtime * 60)) }
  697. except KeyError:
  698. # stopped deamon
  699. stime = _("unknown")
  700. if event.aborted:
  701. # Thread aborted (using our convention of None return)
  702. self.WriteLog(_('Please note that the data are left in inconsistent state '
  703. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  704. msg = _('Command aborted')
  705. else:
  706. msg = _('Command finished')
  707. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  708. self.btnCmdAbort.Enable(False)
  709. if event.onDone:
  710. event.onDone(cmd = event.cmd, returncode = event.returncode)
  711. self.progressbar.SetValue(0) # reset progress bar on '0%'
  712. self.cmdOutputTimer.Stop()
  713. if event.cmd[0] == 'g.gisenv':
  714. Debug.SetLevel()
  715. self.Redirect()
  716. if self.frame.GetName() == "LayerManager":
  717. self.btnCmdAbort.Enable(False)
  718. if event.cmd[0] not in globalvar.grassCmd or \
  719. event.cmd[0] == 'r.mapcalc':
  720. return
  721. tree = self.frame.GetLayerTree()
  722. display = None
  723. if tree:
  724. display = tree.GetMapDisplay()
  725. if not display or not display.IsAutoRendered():
  726. return
  727. mapLayers = map(lambda x: x.GetName(),
  728. display.GetMap().GetListOfLayers(l_type = 'raster') +
  729. display.GetMap().GetListOfLayers(l_type = 'vector'))
  730. try:
  731. task = GUI(show = None).ParseCommand(event.cmd)
  732. except GException, e:
  733. print >> sys.stderr, e
  734. task = None
  735. return
  736. for p in task.get_options()['params']:
  737. if p.get('prompt', '') not in ('raster', 'vector'):
  738. continue
  739. mapName = p.get('value', '')
  740. if '@' not in mapName:
  741. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  742. if mapName in mapLayers:
  743. display.GetWindow().UpdateMap(render = True)
  744. return
  745. elif self.frame.GetName() == 'Modeler':
  746. pass
  747. else: # standalone dialogs
  748. dialog = self.frame
  749. if hasattr(dialog, "btn_abort"):
  750. dialog.btn_abort.Enable(False)
  751. if hasattr(dialog, "btn_cancel"):
  752. dialog.btn_cancel.Enable(True)
  753. if hasattr(dialog, "btn_clipboard"):
  754. dialog.btn_clipboard.Enable(True)
  755. if hasattr(dialog, "btn_help"):
  756. dialog.btn_help.Enable(True)
  757. if hasattr(dialog, "btn_run"):
  758. dialog.btn_run.Enable(True)
  759. if event.returncode == 0 and not event.aborted:
  760. try:
  761. winName = self.frame.parent.GetName()
  762. except AttributeError:
  763. winName = ''
  764. if winName == 'LayerManager':
  765. mapTree = self.frame.parent.GetLayerTree()
  766. elif winName == 'LayerTree':
  767. mapTree = self.frame.parent
  768. elif winName: # GConsole
  769. mapTree = self.frame.parent.parent.GetLayerTree()
  770. else:
  771. mapTree = None
  772. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  773. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  774. # add created maps into layer tree
  775. for p in dialog.task.get_options()['params']:
  776. prompt = p.get('prompt', '')
  777. if prompt in ('raster', 'vector', '3d-raster') and \
  778. p.get('age', 'old') == 'new' and \
  779. p.get('value', None):
  780. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  781. param = p.get('name', ''))
  782. if mapTree.GetMap().GetListOfLayers(l_name = name):
  783. display = mapTree.GetMapDisplay()
  784. if display and display.IsAutoRendered():
  785. display.GetWindow().UpdateMap(render = True)
  786. continue
  787. if prompt == 'raster':
  788. lcmd = ['d.rast',
  789. 'map=%s' % name]
  790. elif prompt == '3d-raster':
  791. lcmd = ['d.rast3d',
  792. 'map=%s' % name]
  793. else:
  794. defaultParams = GetDisplayVectSettings()
  795. lcmd = ['d.vect',
  796. 'map=%s' % name] + defaultParams
  797. mapTree.AddLayer(ltype = prompt,
  798. lcmd = lcmd,
  799. lname = name)
  800. if hasattr(dialog, "get_dcmd") and \
  801. dialog.get_dcmd is None and \
  802. hasattr(dialog, "closebox") and \
  803. dialog.closebox.IsChecked() and \
  804. (event.returncode == 0 or event.aborted):
  805. self.cmdOutput.Update()
  806. time.sleep(2)
  807. dialog.Close()
  808. def OnProcessPendingOutputWindowEvents(self, event):
  809. wx.GetApp().ProcessPendingEvents()
  810. def ResetFocus(self):
  811. """!Reset focus"""
  812. self.cmdPrompt.SetFocus()
  813. def GetPrompt(self):
  814. """!Get prompt"""
  815. return self.cmdPrompt
  816. class GStdout:
  817. """!GConsole standard output
  818. Based on FrameOutErr.py
  819. Name: FrameOutErr.py
  820. Purpose: Redirecting stdout / stderr
  821. Author: Jean-Michel Fauth, Switzerland
  822. Copyright: (c) 2005-2007 Jean-Michel Fauth
  823. Licence: GPL
  824. """
  825. def __init__(self, parent):
  826. self.parent = parent # GConsole
  827. def write(self, s):
  828. if len(s) == 0 or s == '\n':
  829. return
  830. for line in s.splitlines():
  831. if len(line) == 0:
  832. continue
  833. evt = wxCmdOutput(text = line + '\n',
  834. type = '')
  835. wx.PostEvent(self.parent.cmdOutput, evt)
  836. class GStderr:
  837. """!GConsole standard error output
  838. Based on FrameOutErr.py
  839. Name: FrameOutErr.py
  840. Purpose: Redirecting stdout / stderr
  841. Author: Jean-Michel Fauth, Switzerland
  842. Copyright: (c) 2005-2007 Jean-Michel Fauth
  843. Licence: GPL
  844. """
  845. def __init__(self, parent):
  846. self.parent = parent # GConsole
  847. self.type = ''
  848. self.message = ''
  849. self.printMessage = False
  850. def flush(self):
  851. pass
  852. def write(self, s):
  853. if "GtkPizza" in s:
  854. return
  855. # remove/replace escape sequences '\b' or '\r' from stream
  856. progressValue = -1
  857. for line in s.splitlines():
  858. if len(line) == 0:
  859. continue
  860. if 'GRASS_INFO_PERCENT' in line:
  861. value = int(line.rsplit(':', 1)[1].strip())
  862. if value >= 0 and value < 100:
  863. progressValue = value
  864. else:
  865. progressValue = 0
  866. elif 'GRASS_INFO_MESSAGE' in line:
  867. self.type = 'message'
  868. self.message += line.split(':', 1)[1].strip() + '\n'
  869. elif 'GRASS_INFO_WARNING' in line:
  870. self.type = 'warning'
  871. self.message += line.split(':', 1)[1].strip() + '\n'
  872. elif 'GRASS_INFO_ERROR' in line:
  873. self.type = 'error'
  874. self.message += line.split(':', 1)[1].strip() + '\n'
  875. elif 'GRASS_INFO_END' in line:
  876. self.printMessage = True
  877. elif self.type == '':
  878. if len(line) == 0:
  879. continue
  880. evt = wxCmdOutput(text = line,
  881. type = '')
  882. wx.PostEvent(self.parent.cmdOutput, evt)
  883. elif len(line) > 0:
  884. self.message += line.strip() + '\n'
  885. if self.printMessage and len(self.message) > 0:
  886. evt = wxCmdOutput(text = self.message,
  887. type = self.type)
  888. wx.PostEvent(self.parent.cmdOutput, evt)
  889. self.type = ''
  890. self.message = ''
  891. self.printMessage = False
  892. # update progress message
  893. if progressValue > -1:
  894. # self.gmgauge.SetValue(progressValue)
  895. evt = wxCmdProgress(value = progressValue)
  896. wx.PostEvent(self.parent.progressbar, evt)
  897. class GStc(stc.StyledTextCtrl):
  898. """!Styled text control for GRASS stdout and stderr.
  899. Based on FrameOutErr.py
  900. Name: FrameOutErr.py
  901. Purpose: Redirecting stdout / stderr
  902. Author: Jean-Michel Fauth, Switzerland
  903. Copyright: (c) 2005-2007 Jean-Michel Fauth
  904. Licence: GPL
  905. """
  906. def __init__(self, parent, id, margin = False, wrap = None):
  907. stc.StyledTextCtrl.__init__(self, parent, id)
  908. self.parent = parent
  909. self.SetUndoCollection(True)
  910. self.SetReadOnly(True)
  911. # remember position of line begining (used for '\r')
  912. self.linePos = -1
  913. #
  914. # styles
  915. #
  916. self.SetStyle()
  917. #
  918. # line margins
  919. #
  920. # TODO print number only from cmdlog
  921. self.SetMarginWidth(1, 0)
  922. self.SetMarginWidth(2, 0)
  923. if margin:
  924. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  925. self.SetMarginWidth(0, 30)
  926. else:
  927. self.SetMarginWidth(0, 0)
  928. #
  929. # miscellaneous
  930. #
  931. self.SetViewWhiteSpace(False)
  932. self.SetTabWidth(4)
  933. self.SetUseTabs(False)
  934. self.UsePopUp(True)
  935. self.SetSelBackground(True, "#FFFF00")
  936. self.SetUseHorizontalScrollBar(True)
  937. #
  938. # bindings
  939. #
  940. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  941. def OnTextSelectionChanged(self, event):
  942. """!Copy selected text to clipboard and skip event.
  943. The same function is in TextCtrlAutoComplete class (prompt.py).
  944. """
  945. wx.CallAfter(self.Copy)
  946. event.Skip()
  947. def SetStyle(self):
  948. """!Set styles for styled text output windows with type face
  949. and point size selected by user (Courier New 10 is default)"""
  950. typeface = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  951. if typeface == "":
  952. typeface = "Courier New"
  953. typesize = UserSettings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  954. if typesize == None or typesize <= 0:
  955. typesize = 10
  956. typesize = float(typesize)
  957. self.StyleDefault = 0
  958. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  959. self.StyleCommand = 1
  960. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  961. self.StyleOutput = 2
  962. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  963. # fatal error
  964. self.StyleError = 3
  965. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  966. # warning
  967. self.StyleWarning = 4
  968. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  969. # message
  970. self.StyleMessage = 5
  971. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  972. # unknown
  973. self.StyleUnknown = 6
  974. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  975. # default and clear => init
  976. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  977. self.StyleClearAll()
  978. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  979. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  980. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  981. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  982. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  983. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  984. def OnDestroy(self, evt):
  985. """!The clipboard contents can be preserved after
  986. the app has exited"""
  987. wx.TheClipboard.Flush()
  988. evt.Skip()
  989. def AddTextWrapped(self, txt, wrap = None):
  990. """!Add string to text area.
  991. String is wrapped and linesep is also added to the end
  992. of the string"""
  993. # allow writing to output window
  994. self.SetReadOnly(False)
  995. if wrap:
  996. txt = textwrap.fill(txt, wrap) + '\n'
  997. else:
  998. if txt[-1] != '\n':
  999. txt += '\n'
  1000. if '\r' in txt:
  1001. self.linePos = -1
  1002. for seg in txt.split('\r'):
  1003. if self.linePos > -1:
  1004. self.SetCurrentPos(self.linePos)
  1005. self.ReplaceSelection(seg)
  1006. else:
  1007. self.linePos = self.GetCurrentPos()
  1008. self.AddText(seg)
  1009. else:
  1010. self.linePos = self.GetCurrentPos()
  1011. try:
  1012. self.AddText(txt)
  1013. except UnicodeDecodeError:
  1014. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  1015. if enc:
  1016. txt = unicode(txt, enc)
  1017. elif 'GRASS_DB_ENCODING' in os.environ:
  1018. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  1019. else:
  1020. txt = EncodeString(txt)
  1021. self.AddText(txt)
  1022. # reset output window to read only
  1023. self.SetReadOnly(True)
  1024. def AddStyledMessage(self, message, style = None):
  1025. """!Add message to text area.
  1026. Handles messages with progress percentages.
  1027. @param message message to be added
  1028. @param style style of message, allowed values: 'message', 'warning', 'error' or None
  1029. """
  1030. # message prefix
  1031. if style == 'warning':
  1032. message = 'WARNING: ' + message
  1033. elif style == 'error':
  1034. message = 'ERROR: ' + message
  1035. p1 = self.GetEndStyled()
  1036. self.GotoPos(p1)
  1037. # is this still needed?
  1038. if '\b' in message:
  1039. if self.linePos < 0:
  1040. self.linePos = p1
  1041. last_c = ''
  1042. for c in message:
  1043. if c == '\b':
  1044. self.linePos -= 1
  1045. else:
  1046. if c == '\r':
  1047. pos = self.GetCurLine()[1]
  1048. # self.SetCurrentPos(pos)
  1049. else:
  1050. self.SetCurrentPos(self.linePos)
  1051. self.ReplaceSelection(c)
  1052. self.linePos = self.GetCurrentPos()
  1053. if c != ' ':
  1054. last_c = c
  1055. if last_c not in ('0123456789'):
  1056. self.AddTextWrapped('\n', wrap = None)
  1057. self.linePos = -1
  1058. else:
  1059. self.linePos = -1 # don't force position
  1060. if '\n' not in message:
  1061. self.AddTextWrapped(message, wrap = 60)
  1062. else:
  1063. self.AddTextWrapped(message, wrap = None)
  1064. p2 = self.GetCurrentPos()
  1065. if p2 >= p1:
  1066. self.StartStyling(p1, 0xff)
  1067. if style == 'error':
  1068. self.SetStyling(p2 - p1, self.StyleError)
  1069. elif style == 'warning':
  1070. self.SetStyling(p2 - p1, self.StyleWarning)
  1071. elif style == 'message':
  1072. self.SetStyling(p2 - p1, self.StyleMessage)
  1073. else: # unknown
  1074. self.SetStyling(p2 - p1, self.StyleUnknown)
  1075. self.EnsureCaretVisible()