goutput.py 49 KB

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