goutput.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. """!
  2. @package goutput
  3. @brief Command output log widget
  4. Classes:
  5. - GMConsole
  6. - GMStc
  7. - GMStdout
  8. - GMStderr
  9. (C) 2007-2010 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Martin Landa <landa.martin gmail.com>
  15. """
  16. import os
  17. import sys
  18. import textwrap
  19. import time
  20. import threading
  21. import Queue
  22. import wx
  23. import wx.stc
  24. from wx.lib.newevent import NewEvent
  25. import grass.script as grass
  26. import globalvar
  27. import gcmd
  28. import utils
  29. import preferences
  30. import menuform
  31. import prompt
  32. from debug import Debug
  33. from preferences import globalSettings as UserSettings
  34. from ghelp import SearchModuleWindow
  35. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  36. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  37. wxCmdRun, EVT_CMD_RUN = NewEvent()
  38. wxCmdDone, EVT_CMD_DONE = NewEvent()
  39. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  40. def GrassCmd(cmd, stdout, stderr):
  41. """!Return GRASS command thread"""
  42. return gcmd.CommandThread(cmd,
  43. stdout=stdout, stderr=stderr)
  44. class CmdThread(threading.Thread):
  45. """!Thread for GRASS commands"""
  46. requestId = 0
  47. def __init__(self, parent, requestQ, resultQ, **kwds):
  48. threading.Thread.__init__(self, **kwds)
  49. self.setDaemon(True)
  50. self.parent = parent # GMConsole
  51. self._want_abort_all = False
  52. self.requestQ = requestQ
  53. self.resultQ = resultQ
  54. self.start()
  55. def RunCmd(self, callable, onDone, *args, **kwds):
  56. CmdThread.requestId += 1
  57. self.requestCmd = None
  58. self.requestQ.put((CmdThread.requestId, callable, onDone, args, kwds))
  59. return CmdThread.requestId
  60. def SetId(self, id):
  61. """!Set starting id"""
  62. CmdThread.requestId = id
  63. def run(self):
  64. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  65. while True:
  66. requestId, callable, onDone, args, kwds = self.requestQ.get()
  67. requestTime = time.time()
  68. event = wxCmdRun(cmd=args[0],
  69. pid=requestId)
  70. wx.PostEvent(self.parent, event)
  71. time.sleep(.1)
  72. self.requestCmd = callable(*args, **kwds)
  73. if self._want_abort_all:
  74. self.requestCmd.abort()
  75. if self.requestQ.empty():
  76. self._want_abort_all = False
  77. self.resultQ.put((requestId, self.requestCmd.run()))
  78. try:
  79. returncode = self.requestCmd.module.returncode
  80. except AttributeError:
  81. returncode = 0 # being optimistic
  82. try:
  83. aborted = self.requestCmd.aborted
  84. except AttributeError:
  85. aborted = False
  86. time.sleep(.1)
  87. # set default color table for raster data
  88. if UserSettings.Get(group='cmd', key='rasterColorTable', subkey='enabled') and \
  89. args[0][0][:2] == 'r.':
  90. moduleInterface = menuform.GUI().ParseCommand(args[0], show = None)
  91. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  92. colorTable = UserSettings.Get(group='cmd', key='rasterColorTable', subkey='selection')
  93. if outputParam and outputParam['prompt'] == 'raster':
  94. argsColor = list(args)
  95. argsColor[0] = [ 'r.colors',
  96. 'map=%s' % outputParam['value'],
  97. 'color=%s' % colorTable ]
  98. self.requestCmdColor = callable(*argsColor, **kwds)
  99. self.resultQ.put((requestId, self.requestCmdColor.run()))
  100. event = wxCmdDone(aborted = aborted,
  101. returncode = returncode,
  102. time = requestTime,
  103. pid = requestId,
  104. onDone = onDone)
  105. # send event
  106. wx.PostEvent(self.parent, event)
  107. def abort(self, abortall = True):
  108. """!Abort command(s)"""
  109. if abortall:
  110. self._want_abort_all = True
  111. self.requestCmd.abort()
  112. if self.requestQ.empty():
  113. self._want_abort_all = False
  114. class GMConsole(wx.SplitterWindow):
  115. """!Create and manage output console for commands run by GUI.
  116. """
  117. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  118. notebook = None,
  119. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  120. **kwargs):
  121. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  122. self.SetName("GMConsole")
  123. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  124. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  125. # initialize variables
  126. self.Map = None
  127. self.parent = parent # GMFrame | CmdPanel | ?
  128. if notebook:
  129. self._notebook = notebook
  130. else:
  131. self._notebook = self.parent.notebook
  132. self.lineWidth = 80
  133. self.pageid = pageid
  134. # remember position of line begining (used for '\r')
  135. self.linePos = -1
  136. #
  137. # create queues
  138. #
  139. self.requestQ = Queue.Queue()
  140. self.resultQ = Queue.Queue()
  141. #
  142. # progress bar
  143. #
  144. self.console_progressbar = wx.Gauge(parent=self.panelOutput, id=wx.ID_ANY,
  145. range=100, pos=(110, 50), size=(-1, 25),
  146. style=wx.GA_HORIZONTAL)
  147. self.console_progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  148. #
  149. # text control for command output
  150. #
  151. self.cmd_output = GMStc(parent=self.panelOutput, id=wx.ID_ANY, margin=margin,
  152. wrap=None)
  153. self.cmd_output_timer = wx.Timer(self.cmd_output, id=wx.ID_ANY)
  154. self.cmd_output.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  155. self.cmd_output.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  156. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  157. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  158. # search & command prompt
  159. self.cmd_prompt = prompt.GPromptSTC(parent = self)
  160. if self.parent.GetName() != 'LayerManager':
  161. self.search = None
  162. self.cmd_prompt.Hide()
  163. else:
  164. self.infoCollapseLabelExp = _("Click here to show search module engine")
  165. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  166. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  167. label = self.infoCollapseLabelExp,
  168. style = wx.CP_DEFAULT_STYLE |
  169. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  170. self.MakeSearchPaneContent(self.searchPane.GetPane())
  171. self.searchPane.Collapse(True)
  172. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  173. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  174. #
  175. # stream redirection
  176. #
  177. self.cmd_stdout = GMStdout(self)
  178. self.cmd_stderr = GMStderr(self)
  179. #
  180. # thread
  181. #
  182. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  183. #
  184. # buttons
  185. #
  186. self.btn_console_clear = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY,
  187. label = _("C&lear output"), size=(125,-1))
  188. self.btn_cmd_clear = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY,
  189. label = _("&Clear command"), size=(125,-1))
  190. if self.parent.GetName() != 'LayerManager':
  191. self.btn_cmd_clear.Hide()
  192. self.btn_console_save = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY,
  193. label = _("&Save output"), size=(125,-1))
  194. # abort
  195. self.btn_abort = wx.Button(parent = self.panelPrompt, id = wx.ID_ANY, label = _("&Abort command"),
  196. size=(125,-1))
  197. self.btn_abort.SetToolTipString(_("Abort the running command"))
  198. self.btn_abort.Enable(False)
  199. self.btn_cmd_clear.Bind(wx.EVT_BUTTON, self.cmd_prompt.OnCmdErase)
  200. self.btn_console_clear.Bind(wx.EVT_BUTTON, self.ClearHistory)
  201. self.btn_console_save.Bind(wx.EVT_BUTTON, self.SaveHistory)
  202. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  203. self.btn_abort.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  204. self.__layout()
  205. def __layout(self):
  206. """!Do layout"""
  207. OutputSizer = wx.BoxSizer(wx.VERTICAL)
  208. PromptSizer = wx.BoxSizer(wx.VERTICAL)
  209. ButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
  210. if self.search and self.search.IsShown():
  211. OutputSizer.Add(item=self.searchPane, proportion=0,
  212. flag=wx.EXPAND | wx.ALL, border=3)
  213. OutputSizer.Add(item=self.cmd_output, proportion=1,
  214. flag=wx.EXPAND | wx.ALL, border=3)
  215. OutputSizer.Add(item=self.console_progressbar, proportion=0,
  216. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=3)
  217. PromptSizer.Add(item=self.cmd_prompt, proportion=1,
  218. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=3)
  219. ButtonSizer.Add(item=self.btn_console_clear, proportion=0,
  220. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  221. ButtonSizer.Add(item=self.btn_console_save, proportion=0,
  222. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  223. ButtonSizer.Add(item=self.btn_cmd_clear, proportion=0,
  224. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  225. ButtonSizer.Add(item=self.btn_abort, proportion=0,
  226. flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE | wx.ALL, border=5)
  227. PromptSizer.Add(item=ButtonSizer, proportion=0,
  228. flag=wx.ALIGN_CENTER)
  229. OutputSizer.Fit(self)
  230. OutputSizer.SetSizeHints(self)
  231. PromptSizer.Fit(self)
  232. PromptSizer.SetSizeHints(self)
  233. self.panelOutput.SetSizer(OutputSizer)
  234. self.panelPrompt.SetSizer(PromptSizer)
  235. # split window
  236. if self.parent.GetName() == 'LayerManager':
  237. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  238. self.SetMinimumPaneSize(self.btn_cmd_clear.GetSize()[1] + 50)
  239. else:
  240. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  241. self.SetMinimumPaneSize(self.btn_cmd_clear.GetSize()[1] + 10)
  242. self.SetSashGravity(1.0)
  243. # layout
  244. self.SetAutoLayout(True)
  245. self.Layout()
  246. def MakeSearchPaneContent(self, pane):
  247. """!Create search pane"""
  248. border = wx.BoxSizer(wx.VERTICAL)
  249. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmd_prompt)
  250. border.Add(item = self.search, proportion = 0,
  251. flag = wx.EXPAND | wx.ALL, border = 1)
  252. pane.SetSizer(border)
  253. border.Fit(pane)
  254. def OnSearchPaneChanged(self, event):
  255. """!Collapse search module box"""
  256. if self.searchPane.IsExpanded():
  257. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  258. else:
  259. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  260. self.panelOutput.Layout()
  261. self.panelOutput.SendSizeEvent()
  262. def GetPanel(self, prompt = True):
  263. """!Get panel
  264. @param prompt get prompt / output panel
  265. @return wx.Panel reference
  266. """
  267. if prompt:
  268. return self.panelPrompt
  269. return self.panelOutput
  270. def Redirect(self):
  271. """!Redirect stderr
  272. @return True redirected
  273. @return False failed
  274. """
  275. if Debug.get_level() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  276. # don't redirect when debugging is enabled
  277. sys.stdout = self.cmd_stdout
  278. sys.stderr = self.cmd_stderr
  279. return True
  280. return False
  281. def WriteLog(self, text, style = None, wrap = None,
  282. switchPage = False):
  283. """!Generic method for writing log message in
  284. given style
  285. @param line text line
  286. @param style text style (see GMStc)
  287. @param stdout write to stdout or stderr
  288. """
  289. self.cmd_output.SetStyle()
  290. if switchPage and \
  291. self._notebook.GetSelection() != self.parent.goutput.pageid:
  292. self._notebook.SetSelection(self.parent.goutput.pageid)
  293. if not style:
  294. style = self.cmd_output.StyleDefault
  295. # p1 = self.cmd_output.GetCurrentPos()
  296. p1 = self.cmd_output.GetEndStyled()
  297. # self.cmd_output.GotoPos(p1)
  298. self.cmd_output.DocumentEnd()
  299. for line in text.splitlines():
  300. # fill space
  301. if len(line) < self.lineWidth:
  302. diff = self.lineWidth - len(line)
  303. line += diff * ' '
  304. self.cmd_output.AddTextWrapped(line, wrap=wrap) # adds '\n'
  305. p2 = self.cmd_output.GetCurrentPos()
  306. self.cmd_output.StartStyling(p1, 0xff)
  307. self.cmd_output.SetStyling(p2 - p1, style)
  308. self.cmd_output.EnsureCaretVisible()
  309. def WriteCmdLog(self, line, pid=None):
  310. """!Write message in selected style"""
  311. if pid:
  312. line = '(' + str(pid) + ') ' + line
  313. self.WriteLog(line, style=self.cmd_output.StyleCommand, switchPage = True)
  314. def WriteWarning(self, line):
  315. """!Write message in warning style"""
  316. self.WriteLog(line, style=self.cmd_output.StyleWarning, switchPage = True)
  317. def WriteError(self, line):
  318. """!Write message in error style"""
  319. self.WriteLog(line, style=self.cmd_output.StyleError, switchPage = True)
  320. def RunCmd(self, command, compReg = True, switchPage = False,
  321. onDone = None):
  322. """!Run in GUI GRASS (or other) commands typed into console
  323. command text widget, and send stdout output to output text
  324. widget.
  325. Command is transformed into a list for processing.
  326. @todo Display commands (*.d) are captured and processed
  327. separately by mapdisp.py. Display commands are rendered in map
  328. display widget that currently has the focus (as indicted by
  329. mdidx).
  330. @param command command (list)
  331. @param compReg if true use computation region
  332. @param switchPage switch to output page
  333. @param onDone function to be called when command is finished
  334. """
  335. # map display window available ?
  336. try:
  337. curr_disp = self.parent.curr_page.maptree.mapdisplay
  338. self.Map = curr_disp.GetRender()
  339. except:
  340. curr_disp = None
  341. # command given as a string ?
  342. try:
  343. cmdlist = command.strip().split(' ')
  344. except:
  345. cmdlist = command
  346. # update history file
  347. env = grass.gisenv()
  348. fileHistory = open(os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'],
  349. '.bash_history'), 'a')
  350. cmdString = ' '.join(cmdlist)
  351. try:
  352. fileHistory.write(cmdString + '\n')
  353. finally:
  354. fileHistory.close()
  355. # update history items
  356. if self.parent.GetName() == 'LayerManager':
  357. try:
  358. self.parent.cmdinput.SetHistoryItems()
  359. except AttributeError:
  360. pass
  361. if cmdlist[0] in globalvar.grassCmd['all']:
  362. # send GRASS command without arguments to GUI command interface
  363. # except display commands (they are handled differently)
  364. if self.parent.GetName() == "LayerManager" and cmdlist[0][0:2] == "d.":
  365. #
  366. # display GRASS commands
  367. #
  368. try:
  369. layertype = {'d.rast' : 'raster',
  370. 'd.rast3d' : '3d-raster',
  371. 'd.rgb' : 'rgb',
  372. 'd.his' : 'his',
  373. 'd.shaded' : 'shaded',
  374. 'd.legend' : 'rastleg',
  375. 'd.rast.arrow' : 'rastarrow',
  376. 'd.rast.num' : 'rastnum',
  377. 'd.vect' : 'vector',
  378. 'd.thematic.area': 'thememap',
  379. 'd.vect.chart' : 'themechart',
  380. 'd.grid' : 'grid',
  381. 'd.geodesic' : 'geodesic',
  382. 'd.rhumbline' : 'rhumb',
  383. 'd.labels' : 'labels'}[cmdlist[0]]
  384. except KeyError:
  385. gcmd.GMessage(parent = self.parent,
  386. message = _("Command '%s' not yet implemented in the WxGUI. "
  387. "Try adding it as a command layer instead.") % cmdlist[0])
  388. return None
  389. # add layer into layer tree
  390. if cmdlist[0] == 'd.rast':
  391. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  392. layerType = 'raster')
  393. elif cmdlist[0] == 'd.vect':
  394. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  395. layerType = 'vector')
  396. else:
  397. lname = None
  398. if self.parent.GetName() == "LayerManager":
  399. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  400. lname=lname,
  401. lcmd=cmdlist)
  402. else:
  403. #
  404. # other GRASS commands (r|v|g|...)
  405. #
  406. # switch to 'Command output'
  407. if switchPage:
  408. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  409. self._notebook.SetSelection(self.parent.goutput.pageid)
  410. self.parent.SetFocus() # -> set focus
  411. self.parent.Raise()
  412. # activate computational region (set with g.region)
  413. # for all non-display commands.
  414. if compReg:
  415. tmpreg = os.getenv("GRASS_REGION")
  416. if os.environ.has_key("GRASS_REGION"):
  417. del os.environ["GRASS_REGION"]
  418. if len(cmdlist) == 1 and cmdlist[0] not in ('v.krige'):
  419. import menuform
  420. # process GRASS command without argument
  421. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  422. else:
  423. # process GRASS command with argument
  424. self.cmdThread.RunCmd(GrassCmd,
  425. onDone,
  426. cmdlist,
  427. self.cmd_stdout, self.cmd_stderr)
  428. self.cmd_output_timer.Start(50)
  429. return None
  430. # deactivate computational region and return to display settings
  431. if compReg and tmpreg:
  432. os.environ["GRASS_REGION"] = tmpreg
  433. else:
  434. # Send any other command to the shell. Send output to
  435. # console output window
  436. self.cmdThread.RunCmd(GrassCmd,
  437. onDone,
  438. cmdlist,
  439. self.cmd_stdout, self.cmd_stderr)
  440. self.cmd_output_timer.Start(50)
  441. return None
  442. def ClearHistory(self, event):
  443. """!Clear history of commands"""
  444. self.cmd_output.SetReadOnly(False)
  445. self.cmd_output.ClearAll()
  446. self.cmd_output.SetReadOnly(True)
  447. self.console_progressbar.SetValue(0)
  448. def SaveHistory(self, event):
  449. """!Save history of commands"""
  450. self.history = self.cmd_output.GetSelectedText()
  451. if self.history == '':
  452. self.history = self.cmd_output.GetText()
  453. # add newline if needed
  454. if len(self.history) > 0 and self.history[-1] != '\n':
  455. self.history += '\n'
  456. wildcard = "Text file (*.txt)|*.txt"
  457. dlg = wx.FileDialog(
  458. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  459. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  460. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  461. # Show the dialog and retrieve the user response. If it is the OK response,
  462. # process the data.
  463. if dlg.ShowModal() == wx.ID_OK:
  464. path = dlg.GetPath()
  465. output = open(path, "w")
  466. output.write(self.history)
  467. output.close()
  468. dlg.Destroy()
  469. def GetCmd(self):
  470. """!Get running command or None"""
  471. return self.requestQ.get()
  472. def OnUpdateStatusBar(self, event):
  473. """!Update statusbar text"""
  474. if event.GetString():
  475. nItems = len(self.cmd_prompt.GetCommandItems())
  476. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  477. else:
  478. self.parent.SetStatusText('', 0)
  479. event.Skip()
  480. def OnCmdOutput(self, event):
  481. """!Print command output"""
  482. message = event.text
  483. type = event.type
  484. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  485. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  486. if textP[-1] != ')':
  487. textP += ' (...)'
  488. self._notebook.SetPageText(self.parent.goutput.pageid,
  489. textP)
  490. # message prefix
  491. if type == 'warning':
  492. messege = 'WARNING: ' + message
  493. elif type == 'error':
  494. message = 'ERROR: ' + message
  495. p1 = self.cmd_output.GetEndStyled()
  496. self.cmd_output.GotoPos(p1)
  497. if '\b' in message:
  498. if self.linepos < 0:
  499. self.linepos = p1
  500. last_c = ''
  501. for c in message:
  502. if c == '\b':
  503. self.linepos -= 1
  504. else:
  505. if c == '\r':
  506. pos = self.cmd_output.GetCurLine()[1]
  507. # self.cmd_output.SetCurrentPos(pos)
  508. else:
  509. self.cmd_output.SetCurrentPos(self.linepos)
  510. self.cmd_output.ReplaceSelection(c)
  511. self.linepos = self.cmd_output.GetCurrentPos()
  512. if c != ' ':
  513. last_c = c
  514. if last_c not in ('0123456789'):
  515. self.cmd_output.AddTextWrapped('\n', wrap=None)
  516. self.linepos = -1
  517. else:
  518. self.linepos = -1 # don't force position
  519. if '\n' not in message:
  520. self.cmd_output.AddTextWrapped(message, wrap=60)
  521. else:
  522. self.cmd_output.AddTextWrapped(message, wrap=None)
  523. p2 = self.cmd_output.GetCurrentPos()
  524. if p2 >= p1:
  525. self.cmd_output.StartStyling(p1, 0xff)
  526. if type == 'error':
  527. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  528. elif type == 'warning':
  529. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  530. elif type == 'message':
  531. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  532. else: # unknown
  533. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  534. self.cmd_output.EnsureCaretVisible()
  535. def OnCmdProgress(self, event):
  536. """!Update progress message info"""
  537. self.console_progressbar.SetValue(event.value)
  538. def OnCmdAbort(self, event):
  539. """!Abort running command"""
  540. self.cmdThread.abort()
  541. def OnCmdRun(self, event):
  542. """!Run command"""
  543. if self.parent.GetName() == 'Modeler':
  544. self.parent.OnCmdRun(event)
  545. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  546. self.btn_abort.Enable()
  547. def OnCmdDone(self, event):
  548. """!Command done (or aborted)"""
  549. if self.parent.GetName() == 'Modeler':
  550. self.parent.OnCmdDone(event)
  551. if event.aborted:
  552. # Thread aborted (using our convention of None return)
  553. self.WriteLog(_('Please note that the data are left in incosistent stage '
  554. 'and can be corrupted'), self.cmd_output.StyleWarning)
  555. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  556. _('Command aborted'),
  557. (time.time() - event.time)))
  558. # pid=self.cmdThread.requestId)
  559. self.btn_abort.Enable(False)
  560. else:
  561. try:
  562. # Process results here
  563. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  564. _('Command finished'),
  565. (time.time() - event.time)))
  566. except KeyError:
  567. # stopped deamon
  568. pass
  569. self.btn_abort.Enable(False)
  570. if event.onDone:
  571. event.onDone(returncode = event.returncode)
  572. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  573. self.cmd_output_timer.Stop()
  574. # set focus on prompt
  575. if self.parent.GetName() == "LayerManager":
  576. self.btn_abort.Enable(False)
  577. else:
  578. # updated command dialog
  579. dialog = self.parent.parent
  580. if hasattr(self.parent.parent, "btn_abort"):
  581. dialog.btn_abort.Enable(False)
  582. if hasattr(self.parent.parent, "btn_cancel"):
  583. dialog.btn_cancel.Enable(True)
  584. if hasattr(self.parent.parent, "btn_clipboard"):
  585. dialog.btn_clipboard.Enable(True)
  586. if hasattr(self.parent.parent, "btn_help"):
  587. dialog.btn_help.Enable(True)
  588. if hasattr(self.parent.parent, "btn_run"):
  589. dialog.btn_run.Enable(True)
  590. if event.returncode == 0 and \
  591. not event.aborted and hasattr(dialog, "addbox") and \
  592. dialog.addbox.IsChecked():
  593. # add created maps into layer tree
  594. winName = self.parent.parent.parent.GetName()
  595. if winName == 'LayerManager':
  596. mapTree = self.parent.parent.parent.curr_page.maptree
  597. else: # GMConsole
  598. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  599. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  600. for p in dialog.task.get_options()['params']:
  601. prompt = p.get('prompt', '')
  602. if prompt in ('raster', 'vector', '3d-raster') and \
  603. p.get('age', 'old') == 'new' and \
  604. p.get('value', None):
  605. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param = p.get('name', ''))
  606. if mapTree.GetMap().GetListOfLayers(l_name = name):
  607. continue
  608. if prompt == 'raster':
  609. lcmd = ['d.rast',
  610. 'map=%s' % name]
  611. else:
  612. lcmd = ['d.vect',
  613. 'map=%s' % name]
  614. mapTree.AddLayer(ltype = prompt,
  615. lcmd = lcmd,
  616. lname = name)
  617. if hasattr(dialog, "get_dcmd") and \
  618. dialog.get_dcmd is None and \
  619. dialog.closebox.IsChecked():
  620. time.sleep(1)
  621. dialog.Close()
  622. event.Skip()
  623. def OnProcessPendingOutputWindowEvents(self, event):
  624. self.ProcessPendingEvents()
  625. class GMStdout:
  626. """!GMConsole standard output
  627. Based on FrameOutErr.py
  628. Name: FrameOutErr.py
  629. Purpose: Redirecting stdout / stderr
  630. Author: Jean-Michel Fauth, Switzerland
  631. Copyright: (c) 2005-2007 Jean-Michel Fauth
  632. Licence: GPL
  633. """
  634. def __init__(self, parent):
  635. self.parent = parent # GMConsole
  636. def write(self, s):
  637. if len(s) == 0 or s == '\n':
  638. return
  639. for line in s.splitlines():
  640. if len(line) == 0:
  641. continue
  642. evt = wxCmdOutput(text=line + '\n',
  643. type='')
  644. wx.PostEvent(self.parent.cmd_output, evt)
  645. class GMStderr:
  646. """!GMConsole standard error output
  647. Based on FrameOutErr.py
  648. Name: FrameOutErr.py
  649. Purpose: Redirecting stdout / stderr
  650. Author: Jean-Michel Fauth, Switzerland
  651. Copyright: (c) 2005-2007 Jean-Michel Fauth
  652. Licence: GPL
  653. """
  654. def __init__(self, parent):
  655. self.parent = parent # GMConsole
  656. self.type = ''
  657. self.message = ''
  658. self.printMessage = False
  659. def flush(self):
  660. pass
  661. def write(self, s):
  662. if "GtkPizza" in s:
  663. return
  664. # remove/replace escape sequences '\b' or '\r' from stream
  665. progressValue = -1
  666. for line in s.splitlines():
  667. if len(line) == 0:
  668. continue
  669. if 'GRASS_INFO_PERCENT' in line:
  670. value = int(line.rsplit(':', 1)[1].strip())
  671. if value >= 0 and value < 100:
  672. progressValue = value
  673. else:
  674. progressValue = 0
  675. elif 'GRASS_INFO_MESSAGE' in line:
  676. self.type = 'message'
  677. self.message += line.split(':', 1)[1].strip() + '\n'
  678. elif 'GRASS_INFO_WARNING' in line:
  679. self.type = 'warning'
  680. self.message += line.split(':', 1)[1].strip() + '\n'
  681. elif 'GRASS_INFO_ERROR' in line:
  682. self.type = 'error'
  683. self.message += line.split(':', 1)[1].strip() + '\n'
  684. elif 'GRASS_INFO_END' in line:
  685. self.printMessage = True
  686. elif self.type == '':
  687. if len(line) == 0:
  688. continue
  689. evt = wxCmdOutput(text=line,
  690. type='')
  691. wx.PostEvent(self.parent.cmd_output, evt)
  692. elif len(line) > 0:
  693. self.message += line.strip() + '\n'
  694. if self.printMessage and len(self.message) > 0:
  695. evt = wxCmdOutput(text=self.message,
  696. type=self.type)
  697. wx.PostEvent(self.parent.cmd_output, evt)
  698. self.type = ''
  699. self.message = ''
  700. self.printMessage = False
  701. # update progress message
  702. if progressValue > -1:
  703. # self.gmgauge.SetValue(progressValue)
  704. evt = wxCmdProgress(value=progressValue)
  705. wx.PostEvent(self.parent.console_progressbar, evt)
  706. class GMStc(wx.stc.StyledTextCtrl):
  707. """!Styled GMConsole
  708. Based on FrameOutErr.py
  709. Name: FrameOutErr.py
  710. Purpose: Redirecting stdout / stderr
  711. Author: Jean-Michel Fauth, Switzerland
  712. Copyright: (c) 2005-2007 Jean-Michel Fauth
  713. Licence: GPL
  714. """
  715. def __init__(self, parent, id, margin=False, wrap=None):
  716. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  717. self.parent = parent
  718. self.SetUndoCollection(True)
  719. self.SetReadOnly(True)
  720. #
  721. # styles
  722. #
  723. self.SetStyle()
  724. #
  725. # line margins
  726. #
  727. # TODO print number only from cmdlog
  728. self.SetMarginWidth(1, 0)
  729. self.SetMarginWidth(2, 0)
  730. if margin:
  731. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  732. self.SetMarginWidth(0, 30)
  733. else:
  734. self.SetMarginWidth(0, 0)
  735. #
  736. # miscellaneous
  737. #
  738. self.SetViewWhiteSpace(False)
  739. self.SetTabWidth(4)
  740. self.SetUseTabs(False)
  741. self.UsePopUp(True)
  742. self.SetSelBackground(True, "#FFFF00")
  743. self.SetUseHorizontalScrollBar(True)
  744. #
  745. # bindings
  746. #
  747. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  748. def SetStyle(self):
  749. """!Set styles for styled text output windows with type face
  750. and point size selected by user (Courier New 10 is default)"""
  751. settings = preferences.Settings()
  752. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  753. if typeface == "": typeface = "Courier New"
  754. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  755. if typesize == None or typesize <= 0: typesize = 10
  756. typesize = float(typesize)
  757. self.StyleDefault = 0
  758. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  759. self.StyleCommand = 1
  760. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  761. self.StyleOutput = 2
  762. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  763. # fatal error
  764. self.StyleError = 3
  765. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  766. # warning
  767. self.StyleWarning = 4
  768. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  769. # message
  770. self.StyleMessage = 5
  771. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  772. # unknown
  773. self.StyleUnknown = 6
  774. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  775. # default and clear => init
  776. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  777. self.StyleClearAll()
  778. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  779. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  780. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  781. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  782. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  783. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  784. def OnDestroy(self, evt):
  785. """!The clipboard contents can be preserved after
  786. the app has exited"""
  787. wx.TheClipboard.Flush()
  788. evt.Skip()
  789. def AddTextWrapped(self, txt, wrap=None):
  790. """!Add string to text area.
  791. String is wrapped and linesep is also added to the end
  792. of the string"""
  793. # allow writing to output window
  794. self.SetReadOnly(False)
  795. if wrap:
  796. txt = textwrap.fill(txt, wrap) + '\n'
  797. else:
  798. if txt[-1] != '\n':
  799. txt += '\n'
  800. if '\r' in txt:
  801. self.parent.linePos = -1
  802. for seg in txt.split('\r'):
  803. if self.parent.linePos > -1:
  804. self.SetCurrentPos(self.parent.linePos)
  805. self.ReplaceSelection(seg)
  806. else:
  807. self.parent.linePos = self.GetCurrentPos()
  808. self.AddText(seg)
  809. else:
  810. self.parent.linePos = self.GetCurrentPos()
  811. try:
  812. self.AddText(txt)
  813. except UnicodeDecodeError:
  814. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  815. if enc:
  816. txt = unicode(txt, enc)
  817. elif os.environ.has_key('GRASS_DB_ENCODING'):
  818. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  819. else:
  820. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  821. self.AddText(txt)
  822. # reset output window to read only
  823. self.SetReadOnly(True)