goutput.py 50 KB

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