goutput.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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(cmd = args[0],
  101. aborted = aborted,
  102. returncode = returncode,
  103. time = requestTime,
  104. pid = requestId,
  105. onDone = onDone)
  106. # send event
  107. wx.PostEvent(self.parent, event)
  108. def abort(self, abortall = True):
  109. """!Abort command(s)"""
  110. if abortall:
  111. self._want_abort_all = True
  112. self.requestCmd.abort()
  113. if self.requestQ.empty():
  114. self._want_abort_all = False
  115. class GMConsole(wx.SplitterWindow):
  116. """!Create and manage output console for commands run by GUI.
  117. """
  118. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  119. notebook = None,
  120. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  121. **kwargs):
  122. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  123. self.SetName("GMConsole")
  124. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  125. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  126. # initialize variables
  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 command typed into console command prompt (GPrompt).
  323. @todo Display commands (*.d) are captured and processed
  324. separately by mapdisp.py. Display commands are rendered in map
  325. display widget that currently has the focus (as indicted by
  326. mdidx).
  327. @param command command given as a list (produced e.g. by shlex.split())
  328. @param compReg True use computation region
  329. @param switchPage switch to output page
  330. @param onDone function to be called when command is finished
  331. """
  332. if len(command) == 0:
  333. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  334. return
  335. # update history file
  336. env = grass.gisenv()
  337. try:
  338. fileHistory = open(os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'],
  339. '.bash_history'), 'a')
  340. except IOError, e:
  341. self.WriteError(str(e))
  342. fileHistory = None
  343. if fileHistory:
  344. try:
  345. fileHistory.write(' '.join(command) + os.linesep)
  346. finally:
  347. fileHistory.close()
  348. # update history items
  349. if self.parent.GetName() == 'LayerManager':
  350. try:
  351. self.parent.cmdinput.SetHistoryItems()
  352. except AttributeError:
  353. pass
  354. if command[0] in globalvar.grassCmd['all']:
  355. # send GRASS command without arguments to GUI command interface
  356. # except display commands (they are handled differently)
  357. if self.parent.GetName() == "LayerManager" and \
  358. command[0][0:2] == "d.":
  359. # display GRASS commands
  360. try:
  361. layertype = {'d.rast' : 'raster',
  362. 'd.rast3d' : '3d-raster',
  363. 'd.rgb' : 'rgb',
  364. 'd.his' : 'his',
  365. 'd.shaded' : 'shaded',
  366. 'd.legend' : 'rastleg',
  367. 'd.rast.arrow' : 'rastarrow',
  368. 'd.rast.num' : 'rastnum',
  369. 'd.vect' : 'vector',
  370. 'd.thematic.area': 'thememap',
  371. 'd.vect.chart' : 'themechart',
  372. 'd.grid' : 'grid',
  373. 'd.geodesic' : 'geodesic',
  374. 'd.rhumbline' : 'rhumb',
  375. 'd.labels' : 'labels'}[command[0]]
  376. except KeyError:
  377. gcmd.GMessage(parent = self.parent,
  378. message = _("Command '%s' not yet implemented in the WxGUI. "
  379. "Try adding it as a command layer instead.") % command[0])
  380. return None
  381. # add layer into layer tree
  382. if command[0] == 'd.rast':
  383. lname = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  384. layerType = 'raster')
  385. elif command[0] == 'd.vect':
  386. lname = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  387. layerType = 'vector')
  388. else:
  389. lname = None
  390. if self.parent.GetName() == "LayerManager":
  391. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  392. lname=lname,
  393. lcmd=command)
  394. else:
  395. # other GRASS commands (r|v|g|...)
  396. # switch to 'Command output' if required
  397. if switchPage:
  398. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  399. self._notebook.SetSelection(self.parent.goutput.pageid)
  400. self.parent.SetFocus()
  401. self.parent.Raise()
  402. # activate computational region (set with g.region)
  403. # for all non-display commands.
  404. if compReg:
  405. tmpreg = os.getenv("GRASS_REGION")
  406. if os.environ.has_key("GRASS_REGION"):
  407. del os.environ["GRASS_REGION"]
  408. if len(command) == 1:
  409. import menuform
  410. task = menuform.GUI().ParseInterface(command)
  411. # if not task.has_required():
  412. # task = None # run command
  413. else:
  414. task = None
  415. if task and command[0] not in ('v.krige'):
  416. # process GRASS command without argument
  417. menuform.GUI().ParseCommand(command, parentframe = self)
  418. else:
  419. # process GRASS command with argument
  420. self.cmdThread.RunCmd(GrassCmd,
  421. onDone,
  422. command,
  423. self.cmd_stdout, self.cmd_stderr)
  424. self.cmd_output_timer.Start(50)
  425. return None
  426. # deactivate computational region and return to display settings
  427. if compReg and tmpreg:
  428. os.environ["GRASS_REGION"] = tmpreg
  429. else:
  430. # Send any other command to the shell. Send output to
  431. # console output window
  432. if len(command) == 1:
  433. import menuform
  434. try:
  435. task = menuform.GUI().ParseInterface(command)
  436. except:
  437. task = None
  438. # if not task.has_required():
  439. # task = None # run command
  440. else:
  441. task = None
  442. if task:
  443. # process GRASS command without argument
  444. menuform.GUI().ParseCommand(command, parentframe = self)
  445. else:
  446. self.cmdThread.RunCmd(GrassCmd,
  447. onDone,
  448. command,
  449. self.cmd_stdout, self.cmd_stderr)
  450. self.cmd_output_timer.Start(50)
  451. return None
  452. def ClearHistory(self, event):
  453. """!Clear history of commands"""
  454. self.cmd_output.SetReadOnly(False)
  455. self.cmd_output.ClearAll()
  456. self.cmd_output.SetReadOnly(True)
  457. self.console_progressbar.SetValue(0)
  458. def SaveHistory(self, event):
  459. """!Save history of commands"""
  460. self.history = self.cmd_output.GetSelectedText()
  461. if self.history == '':
  462. self.history = self.cmd_output.GetText()
  463. # add newline if needed
  464. if len(self.history) > 0 and self.history[-1] != '\n':
  465. self.history += '\n'
  466. wildcard = "Text file (*.txt)|*.txt"
  467. dlg = wx.FileDialog(
  468. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  469. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  470. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  471. # Show the dialog and retrieve the user response. If it is the OK response,
  472. # process the data.
  473. if dlg.ShowModal() == wx.ID_OK:
  474. path = dlg.GetPath()
  475. output = open(path, "w")
  476. output.write(self.history)
  477. output.close()
  478. dlg.Destroy()
  479. def GetCmd(self):
  480. """!Get running command or None"""
  481. return self.requestQ.get()
  482. def OnUpdateStatusBar(self, event):
  483. """!Update statusbar text"""
  484. if event.GetString():
  485. nItems = len(self.cmd_prompt.GetCommandItems())
  486. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  487. else:
  488. self.parent.SetStatusText('', 0)
  489. event.Skip()
  490. def OnCmdOutput(self, event):
  491. """!Print command output"""
  492. message = event.text
  493. type = event.type
  494. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  495. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  496. if textP[-1] != ')':
  497. textP += ' (...)'
  498. self._notebook.SetPageText(self.parent.goutput.pageid,
  499. textP)
  500. # message prefix
  501. if type == 'warning':
  502. messege = 'WARNING: ' + message
  503. elif type == 'error':
  504. message = 'ERROR: ' + message
  505. p1 = self.cmd_output.GetEndStyled()
  506. self.cmd_output.GotoPos(p1)
  507. if '\b' in message:
  508. if self.linepos < 0:
  509. self.linepos = p1
  510. last_c = ''
  511. for c in message:
  512. if c == '\b':
  513. self.linepos -= 1
  514. else:
  515. if c == '\r':
  516. pos = self.cmd_output.GetCurLine()[1]
  517. # self.cmd_output.SetCurrentPos(pos)
  518. else:
  519. self.cmd_output.SetCurrentPos(self.linepos)
  520. self.cmd_output.ReplaceSelection(c)
  521. self.linepos = self.cmd_output.GetCurrentPos()
  522. if c != ' ':
  523. last_c = c
  524. if last_c not in ('0123456789'):
  525. self.cmd_output.AddTextWrapped('\n', wrap=None)
  526. self.linepos = -1
  527. else:
  528. self.linepos = -1 # don't force position
  529. if '\n' not in message:
  530. self.cmd_output.AddTextWrapped(message, wrap=60)
  531. else:
  532. self.cmd_output.AddTextWrapped(message, wrap=None)
  533. p2 = self.cmd_output.GetCurrentPos()
  534. if p2 >= p1:
  535. self.cmd_output.StartStyling(p1, 0xff)
  536. if type == 'error':
  537. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  538. elif type == 'warning':
  539. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  540. elif type == 'message':
  541. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  542. else: # unknown
  543. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  544. self.cmd_output.EnsureCaretVisible()
  545. def OnCmdProgress(self, event):
  546. """!Update progress message info"""
  547. self.console_progressbar.SetValue(event.value)
  548. def OnCmdAbort(self, event):
  549. """!Abort running command"""
  550. self.cmdThread.abort()
  551. def OnCmdRun(self, event):
  552. """!Run command"""
  553. if self.parent.GetName() == 'Modeler':
  554. self.parent.OnCmdRun(event)
  555. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  556. self.btn_abort.Enable()
  557. def OnCmdDone(self, event):
  558. """!Command done (or aborted)"""
  559. if self.parent.GetName() == 'Modeler':
  560. self.parent.OnCmdDone(event)
  561. if event.aborted:
  562. # Thread aborted (using our convention of None return)
  563. self.WriteLog(_('Please note that the data are left in inconsistent state '
  564. 'and may be corrupted'), self.cmd_output.StyleWarning)
  565. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  566. _('Command aborted'),
  567. (time.time() - event.time)))
  568. # pid=self.cmdThread.requestId)
  569. self.btn_abort.Enable(False)
  570. else:
  571. try:
  572. # Process results here
  573. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  574. _('Command finished'),
  575. (time.time() - event.time)))
  576. except KeyError:
  577. # stopped deamon
  578. pass
  579. self.btn_abort.Enable(False)
  580. if event.onDone:
  581. event.onDone(cmd = event.cmd, returncode = event.returncode)
  582. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  583. self.cmd_output_timer.Stop()
  584. if self.parent.GetName() == "LayerManager":
  585. self.btn_abort.Enable(False)
  586. if event.cmd[0] not in globalvar.grassCmd['all'] or \
  587. event.cmd[0] == 'r.mapcalc':
  588. return
  589. display = self.parent.GetLayerTree().GetMapDisplay()
  590. if not display or not display.IsAutoRendered():
  591. return
  592. mapLayers = map(lambda x: x.GetName(),
  593. display.GetRender().GetListOfLayers(l_type = 'raster') +
  594. display.GetRender().GetListOfLayers(l_type = 'vector'))
  595. task = menuform.GUI().ParseCommand(event.cmd, show = None)
  596. for p in task.get_options()['params']:
  597. if p.get('prompt', '') not in ('raster', 'vector'):
  598. continue
  599. mapName = p.get('value', '')
  600. if '@' not in mapName:
  601. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  602. if mapName in mapLayers:
  603. display.GetWindow().UpdateMap(render = True)
  604. return
  605. else: # standalone dialogs
  606. dialog = self.parent.parent
  607. if hasattr(self.parent.parent, "btn_abort"):
  608. dialog.btn_abort.Enable(False)
  609. if hasattr(self.parent.parent, "btn_cancel"):
  610. dialog.btn_cancel.Enable(True)
  611. if hasattr(self.parent.parent, "btn_clipboard"):
  612. dialog.btn_clipboard.Enable(True)
  613. if hasattr(self.parent.parent, "btn_help"):
  614. dialog.btn_help.Enable(True)
  615. if hasattr(self.parent.parent, "btn_run"):
  616. dialog.btn_run.Enable(True)
  617. if event.returncode == 0 and not event.aborted:
  618. try:
  619. winName = self.parent.parent.parent.GetName()
  620. except AttributeError:
  621. winName = ''
  622. if winName == 'LayerManager':
  623. mapTree = self.parent.parent.parent.GetLayerTree()
  624. elif winName == 'LayerTree':
  625. mapTree = self.parent.parent.parent
  626. elif winName: # GMConsole
  627. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  628. else:
  629. mapTree = None
  630. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  631. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  632. # add created maps into layer tree
  633. for p in dialog.task.get_options()['params']:
  634. prompt = p.get('prompt', '')
  635. if prompt in ('raster', 'vector', '3d-raster') and \
  636. p.get('age', 'old') == 'new' and \
  637. p.get('value', None):
  638. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param = p.get('name', ''))
  639. if mapTree.GetMap().GetListOfLayers(l_name = name):
  640. continue
  641. if prompt == 'raster':
  642. lcmd = ['d.rast',
  643. 'map=%s' % name]
  644. else:
  645. lcmd = ['d.vect',
  646. 'map=%s' % name]
  647. mapTree.AddLayer(ltype = prompt,
  648. lcmd = lcmd,
  649. lname = name)
  650. if hasattr(dialog, "get_dcmd") and \
  651. dialog.get_dcmd is None and \
  652. dialog.closebox.IsChecked():
  653. time.sleep(1)
  654. dialog.Close()
  655. def OnProcessPendingOutputWindowEvents(self, event):
  656. self.ProcessPendingEvents()
  657. class GMStdout:
  658. """!GMConsole standard output
  659. Based on FrameOutErr.py
  660. Name: FrameOutErr.py
  661. Purpose: Redirecting stdout / stderr
  662. Author: Jean-Michel Fauth, Switzerland
  663. Copyright: (c) 2005-2007 Jean-Michel Fauth
  664. Licence: GPL
  665. """
  666. def __init__(self, parent):
  667. self.parent = parent # GMConsole
  668. def write(self, s):
  669. if len(s) == 0 or s == '\n':
  670. return
  671. for line in s.splitlines():
  672. if len(line) == 0:
  673. continue
  674. evt = wxCmdOutput(text=line + '\n',
  675. type='')
  676. wx.PostEvent(self.parent.cmd_output, evt)
  677. class GMStderr:
  678. """!GMConsole standard error output
  679. Based on FrameOutErr.py
  680. Name: FrameOutErr.py
  681. Purpose: Redirecting stdout / stderr
  682. Author: Jean-Michel Fauth, Switzerland
  683. Copyright: (c) 2005-2007 Jean-Michel Fauth
  684. Licence: GPL
  685. """
  686. def __init__(self, parent):
  687. self.parent = parent # GMConsole
  688. self.type = ''
  689. self.message = ''
  690. self.printMessage = False
  691. def flush(self):
  692. pass
  693. def write(self, s):
  694. if "GtkPizza" in s:
  695. return
  696. # remove/replace escape sequences '\b' or '\r' from stream
  697. progressValue = -1
  698. for line in s.splitlines():
  699. if len(line) == 0:
  700. continue
  701. if 'GRASS_INFO_PERCENT' in line:
  702. value = int(line.rsplit(':', 1)[1].strip())
  703. if value >= 0 and value < 100:
  704. progressValue = value
  705. else:
  706. progressValue = 0
  707. elif 'GRASS_INFO_MESSAGE' in line:
  708. self.type = 'message'
  709. self.message += line.split(':', 1)[1].strip() + '\n'
  710. elif 'GRASS_INFO_WARNING' in line:
  711. self.type = 'warning'
  712. self.message += line.split(':', 1)[1].strip() + '\n'
  713. elif 'GRASS_INFO_ERROR' in line:
  714. self.type = 'error'
  715. self.message += line.split(':', 1)[1].strip() + '\n'
  716. elif 'GRASS_INFO_END' in line:
  717. self.printMessage = True
  718. elif self.type == '':
  719. if len(line) == 0:
  720. continue
  721. evt = wxCmdOutput(text=line,
  722. type='')
  723. wx.PostEvent(self.parent.cmd_output, evt)
  724. elif len(line) > 0:
  725. self.message += line.strip() + '\n'
  726. if self.printMessage and len(self.message) > 0:
  727. evt = wxCmdOutput(text=self.message,
  728. type=self.type)
  729. wx.PostEvent(self.parent.cmd_output, evt)
  730. self.type = ''
  731. self.message = ''
  732. self.printMessage = False
  733. # update progress message
  734. if progressValue > -1:
  735. # self.gmgauge.SetValue(progressValue)
  736. evt = wxCmdProgress(value=progressValue)
  737. wx.PostEvent(self.parent.console_progressbar, evt)
  738. class GMStc(wx.stc.StyledTextCtrl):
  739. """!Styled GMConsole
  740. Based on FrameOutErr.py
  741. Name: FrameOutErr.py
  742. Purpose: Redirecting stdout / stderr
  743. Author: Jean-Michel Fauth, Switzerland
  744. Copyright: (c) 2005-2007 Jean-Michel Fauth
  745. Licence: GPL
  746. """
  747. def __init__(self, parent, id, margin=False, wrap=None):
  748. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  749. self.parent = parent
  750. self.SetUndoCollection(True)
  751. self.SetReadOnly(True)
  752. #
  753. # styles
  754. #
  755. self.SetStyle()
  756. #
  757. # line margins
  758. #
  759. # TODO print number only from cmdlog
  760. self.SetMarginWidth(1, 0)
  761. self.SetMarginWidth(2, 0)
  762. if margin:
  763. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  764. self.SetMarginWidth(0, 30)
  765. else:
  766. self.SetMarginWidth(0, 0)
  767. #
  768. # miscellaneous
  769. #
  770. self.SetViewWhiteSpace(False)
  771. self.SetTabWidth(4)
  772. self.SetUseTabs(False)
  773. self.UsePopUp(True)
  774. self.SetSelBackground(True, "#FFFF00")
  775. self.SetUseHorizontalScrollBar(True)
  776. #
  777. # bindings
  778. #
  779. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  780. def SetStyle(self):
  781. """!Set styles for styled text output windows with type face
  782. and point size selected by user (Courier New 10 is default)"""
  783. settings = preferences.Settings()
  784. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  785. if typeface == "": typeface = "Courier New"
  786. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  787. if typesize == None or typesize <= 0: typesize = 10
  788. typesize = float(typesize)
  789. self.StyleDefault = 0
  790. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  791. self.StyleCommand = 1
  792. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  793. self.StyleOutput = 2
  794. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  795. # fatal error
  796. self.StyleError = 3
  797. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  798. # warning
  799. self.StyleWarning = 4
  800. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  801. # message
  802. self.StyleMessage = 5
  803. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  804. # unknown
  805. self.StyleUnknown = 6
  806. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  807. # default and clear => init
  808. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  809. self.StyleClearAll()
  810. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  811. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  812. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  813. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  814. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  815. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  816. def OnDestroy(self, evt):
  817. """!The clipboard contents can be preserved after
  818. the app has exited"""
  819. wx.TheClipboard.Flush()
  820. evt.Skip()
  821. def AddTextWrapped(self, txt, wrap=None):
  822. """!Add string to text area.
  823. String is wrapped and linesep is also added to the end
  824. of the string"""
  825. # allow writing to output window
  826. self.SetReadOnly(False)
  827. if wrap:
  828. txt = textwrap.fill(txt, wrap) + '\n'
  829. else:
  830. if txt[-1] != '\n':
  831. txt += '\n'
  832. if '\r' in txt:
  833. self.parent.linePos = -1
  834. for seg in txt.split('\r'):
  835. if self.parent.linePos > -1:
  836. self.SetCurrentPos(self.parent.linePos)
  837. self.ReplaceSelection(seg)
  838. else:
  839. self.parent.linePos = self.GetCurrentPos()
  840. self.AddText(seg)
  841. else:
  842. self.parent.linePos = self.GetCurrentPos()
  843. try:
  844. self.AddText(txt)
  845. except UnicodeDecodeError:
  846. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  847. if enc:
  848. txt = unicode(txt, enc)
  849. elif os.environ.has_key('GRASS_DB_ENCODING'):
  850. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  851. else:
  852. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  853. self.AddText(txt)
  854. # reset output window to read only
  855. self.SetReadOnly(True)