goutput.py 49 KB

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