goutput.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. self.cmdThread.RunCmd(GrassCmd,
  433. onDone,
  434. command,
  435. self.cmd_stdout, self.cmd_stderr)
  436. self.cmd_output_timer.Start(50)
  437. return None
  438. def ClearHistory(self, event):
  439. """!Clear history of commands"""
  440. self.cmd_output.SetReadOnly(False)
  441. self.cmd_output.ClearAll()
  442. self.cmd_output.SetReadOnly(True)
  443. self.console_progressbar.SetValue(0)
  444. def SaveHistory(self, event):
  445. """!Save history of commands"""
  446. self.history = self.cmd_output.GetSelectedText()
  447. if self.history == '':
  448. self.history = self.cmd_output.GetText()
  449. # add newline if needed
  450. if len(self.history) > 0 and self.history[-1] != '\n':
  451. self.history += '\n'
  452. wildcard = "Text file (*.txt)|*.txt"
  453. dlg = wx.FileDialog(
  454. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  455. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  456. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  457. # Show the dialog and retrieve the user response. If it is the OK response,
  458. # process the data.
  459. if dlg.ShowModal() == wx.ID_OK:
  460. path = dlg.GetPath()
  461. output = open(path, "w")
  462. output.write(self.history)
  463. output.close()
  464. dlg.Destroy()
  465. def GetCmd(self):
  466. """!Get running command or None"""
  467. return self.requestQ.get()
  468. def OnUpdateStatusBar(self, event):
  469. """!Update statusbar text"""
  470. if event.GetString():
  471. nItems = len(self.cmd_prompt.GetCommandItems())
  472. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  473. else:
  474. self.parent.SetStatusText('', 0)
  475. event.Skip()
  476. def OnCmdOutput(self, event):
  477. """!Print command output"""
  478. message = event.text
  479. type = event.type
  480. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  481. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  482. if textP[-1] != ')':
  483. textP += ' (...)'
  484. self._notebook.SetPageText(self.parent.goutput.pageid,
  485. textP)
  486. # message prefix
  487. if type == 'warning':
  488. messege = 'WARNING: ' + message
  489. elif type == 'error':
  490. message = 'ERROR: ' + message
  491. p1 = self.cmd_output.GetEndStyled()
  492. self.cmd_output.GotoPos(p1)
  493. if '\b' in message:
  494. if self.linepos < 0:
  495. self.linepos = p1
  496. last_c = ''
  497. for c in message:
  498. if c == '\b':
  499. self.linepos -= 1
  500. else:
  501. if c == '\r':
  502. pos = self.cmd_output.GetCurLine()[1]
  503. # self.cmd_output.SetCurrentPos(pos)
  504. else:
  505. self.cmd_output.SetCurrentPos(self.linepos)
  506. self.cmd_output.ReplaceSelection(c)
  507. self.linepos = self.cmd_output.GetCurrentPos()
  508. if c != ' ':
  509. last_c = c
  510. if last_c not in ('0123456789'):
  511. self.cmd_output.AddTextWrapped('\n', wrap=None)
  512. self.linepos = -1
  513. else:
  514. self.linepos = -1 # don't force position
  515. if '\n' not in message:
  516. self.cmd_output.AddTextWrapped(message, wrap=60)
  517. else:
  518. self.cmd_output.AddTextWrapped(message, wrap=None)
  519. p2 = self.cmd_output.GetCurrentPos()
  520. if p2 >= p1:
  521. self.cmd_output.StartStyling(p1, 0xff)
  522. if type == 'error':
  523. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  524. elif type == 'warning':
  525. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  526. elif type == 'message':
  527. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  528. else: # unknown
  529. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  530. self.cmd_output.EnsureCaretVisible()
  531. def OnCmdProgress(self, event):
  532. """!Update progress message info"""
  533. self.console_progressbar.SetValue(event.value)
  534. def OnCmdAbort(self, event):
  535. """!Abort running command"""
  536. self.cmdThread.abort()
  537. def OnCmdRun(self, event):
  538. """!Run command"""
  539. if self.parent.GetName() == 'Modeler':
  540. self.parent.OnCmdRun(event)
  541. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  542. self.btn_abort.Enable()
  543. def OnCmdDone(self, event):
  544. """!Command done (or aborted)"""
  545. if self.parent.GetName() == 'Modeler':
  546. self.parent.OnCmdDone(event)
  547. if event.aborted:
  548. # Thread aborted (using our convention of None return)
  549. self.WriteLog(_('Please note that the data are left in inconsistent state '
  550. 'and may be corrupted'), self.cmd_output.StyleWarning)
  551. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  552. _('Command aborted'),
  553. (time.time() - event.time)))
  554. # pid=self.cmdThread.requestId)
  555. self.btn_abort.Enable(False)
  556. else:
  557. try:
  558. # Process results here
  559. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  560. _('Command finished'),
  561. (time.time() - event.time)))
  562. except KeyError:
  563. # stopped deamon
  564. pass
  565. self.btn_abort.Enable(False)
  566. if event.onDone:
  567. event.onDone(cmd = event.cmd, returncode = event.returncode)
  568. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  569. self.cmd_output_timer.Stop()
  570. if self.parent.GetName() == "LayerManager":
  571. self.btn_abort.Enable(False)
  572. if event.cmd[0] not in globalvar.grassCmd['all'] or \
  573. event.cmd[0] == 'r.mapcalc':
  574. return
  575. display = self.parent.GetLayerTree().GetMapDisplay()
  576. if not display or not display.IsAutoRendered():
  577. return
  578. mapLayers = map(lambda x: x.GetName(),
  579. display.GetRender().GetListOfLayers(l_type = 'raster') +
  580. display.GetRender().GetListOfLayers(l_type = 'vector'))
  581. task = menuform.GUI().ParseCommand(event.cmd, show = None)
  582. for p in task.get_options()['params']:
  583. if p.get('prompt', '') not in ('raster', 'vector'):
  584. continue
  585. mapName = p.get('value', '')
  586. if '@' not in mapName:
  587. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  588. if mapName in mapLayers:
  589. display.GetWindow().UpdateMap(render = True)
  590. return
  591. else: # standalone dialogs
  592. dialog = self.parent.parent
  593. if hasattr(self.parent.parent, "btn_abort"):
  594. dialog.btn_abort.Enable(False)
  595. if hasattr(self.parent.parent, "btn_cancel"):
  596. dialog.btn_cancel.Enable(True)
  597. if hasattr(self.parent.parent, "btn_clipboard"):
  598. dialog.btn_clipboard.Enable(True)
  599. if hasattr(self.parent.parent, "btn_help"):
  600. dialog.btn_help.Enable(True)
  601. if hasattr(self.parent.parent, "btn_run"):
  602. dialog.btn_run.Enable(True)
  603. if event.returncode == 0 and not event.aborted:
  604. try:
  605. winName = self.parent.parent.parent.GetName()
  606. except AttributeError:
  607. winName = ''
  608. if winName == 'LayerManager':
  609. mapTree = self.parent.parent.parent.GetLayerTree()
  610. elif winName == 'LayerTree':
  611. mapTree = self.parent.parent.parent
  612. elif winName: # GMConsole
  613. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  614. else:
  615. mapTree = None
  616. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  617. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  618. # add created maps into layer tree
  619. for p in dialog.task.get_options()['params']:
  620. prompt = p.get('prompt', '')
  621. if prompt in ('raster', 'vector', '3d-raster') and \
  622. p.get('age', 'old') == 'new' and \
  623. p.get('value', None):
  624. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param = p.get('name', ''))
  625. if mapTree.GetMap().GetListOfLayers(l_name = name):
  626. continue
  627. if prompt == 'raster':
  628. lcmd = ['d.rast',
  629. 'map=%s' % name]
  630. else:
  631. lcmd = ['d.vect',
  632. 'map=%s' % name]
  633. mapTree.AddLayer(ltype = prompt,
  634. lcmd = lcmd,
  635. lname = name)
  636. if hasattr(dialog, "get_dcmd") and \
  637. dialog.get_dcmd is None and \
  638. dialog.closebox.IsChecked():
  639. time.sleep(1)
  640. dialog.Close()
  641. def OnProcessPendingOutputWindowEvents(self, event):
  642. self.ProcessPendingEvents()
  643. class GMStdout:
  644. """!GMConsole standard output
  645. Based on FrameOutErr.py
  646. Name: FrameOutErr.py
  647. Purpose: Redirecting stdout / stderr
  648. Author: Jean-Michel Fauth, Switzerland
  649. Copyright: (c) 2005-2007 Jean-Michel Fauth
  650. Licence: GPL
  651. """
  652. def __init__(self, parent):
  653. self.parent = parent # GMConsole
  654. def write(self, s):
  655. if len(s) == 0 or s == '\n':
  656. return
  657. for line in s.splitlines():
  658. if len(line) == 0:
  659. continue
  660. evt = wxCmdOutput(text=line + '\n',
  661. type='')
  662. wx.PostEvent(self.parent.cmd_output, evt)
  663. class GMStderr:
  664. """!GMConsole standard error output
  665. Based on FrameOutErr.py
  666. Name: FrameOutErr.py
  667. Purpose: Redirecting stdout / stderr
  668. Author: Jean-Michel Fauth, Switzerland
  669. Copyright: (c) 2005-2007 Jean-Michel Fauth
  670. Licence: GPL
  671. """
  672. def __init__(self, parent):
  673. self.parent = parent # GMConsole
  674. self.type = ''
  675. self.message = ''
  676. self.printMessage = False
  677. def flush(self):
  678. pass
  679. def write(self, s):
  680. if "GtkPizza" in s:
  681. return
  682. # remove/replace escape sequences '\b' or '\r' from stream
  683. progressValue = -1
  684. for line in s.splitlines():
  685. if len(line) == 0:
  686. continue
  687. if 'GRASS_INFO_PERCENT' in line:
  688. value = int(line.rsplit(':', 1)[1].strip())
  689. if value >= 0 and value < 100:
  690. progressValue = value
  691. else:
  692. progressValue = 0
  693. elif 'GRASS_INFO_MESSAGE' in line:
  694. self.type = 'message'
  695. self.message += line.split(':', 1)[1].strip() + '\n'
  696. elif 'GRASS_INFO_WARNING' in line:
  697. self.type = 'warning'
  698. self.message += line.split(':', 1)[1].strip() + '\n'
  699. elif 'GRASS_INFO_ERROR' in line:
  700. self.type = 'error'
  701. self.message += line.split(':', 1)[1].strip() + '\n'
  702. elif 'GRASS_INFO_END' in line:
  703. self.printMessage = True
  704. elif self.type == '':
  705. if len(line) == 0:
  706. continue
  707. evt = wxCmdOutput(text=line,
  708. type='')
  709. wx.PostEvent(self.parent.cmd_output, evt)
  710. elif len(line) > 0:
  711. self.message += line.strip() + '\n'
  712. if self.printMessage and len(self.message) > 0:
  713. evt = wxCmdOutput(text=self.message,
  714. type=self.type)
  715. wx.PostEvent(self.parent.cmd_output, evt)
  716. self.type = ''
  717. self.message = ''
  718. self.printMessage = False
  719. # update progress message
  720. if progressValue > -1:
  721. # self.gmgauge.SetValue(progressValue)
  722. evt = wxCmdProgress(value=progressValue)
  723. wx.PostEvent(self.parent.console_progressbar, evt)
  724. class GMStc(wx.stc.StyledTextCtrl):
  725. """!Styled GMConsole
  726. Based on FrameOutErr.py
  727. Name: FrameOutErr.py
  728. Purpose: Redirecting stdout / stderr
  729. Author: Jean-Michel Fauth, Switzerland
  730. Copyright: (c) 2005-2007 Jean-Michel Fauth
  731. Licence: GPL
  732. """
  733. def __init__(self, parent, id, margin=False, wrap=None):
  734. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  735. self.parent = parent
  736. self.SetUndoCollection(True)
  737. self.SetReadOnly(True)
  738. #
  739. # styles
  740. #
  741. self.SetStyle()
  742. #
  743. # line margins
  744. #
  745. # TODO print number only from cmdlog
  746. self.SetMarginWidth(1, 0)
  747. self.SetMarginWidth(2, 0)
  748. if margin:
  749. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  750. self.SetMarginWidth(0, 30)
  751. else:
  752. self.SetMarginWidth(0, 0)
  753. #
  754. # miscellaneous
  755. #
  756. self.SetViewWhiteSpace(False)
  757. self.SetTabWidth(4)
  758. self.SetUseTabs(False)
  759. self.UsePopUp(True)
  760. self.SetSelBackground(True, "#FFFF00")
  761. self.SetUseHorizontalScrollBar(True)
  762. #
  763. # bindings
  764. #
  765. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  766. def SetStyle(self):
  767. """!Set styles for styled text output windows with type face
  768. and point size selected by user (Courier New 10 is default)"""
  769. settings = preferences.Settings()
  770. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  771. if typeface == "": typeface = "Courier New"
  772. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  773. if typesize == None or typesize <= 0: typesize = 10
  774. typesize = float(typesize)
  775. self.StyleDefault = 0
  776. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  777. self.StyleCommand = 1
  778. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  779. self.StyleOutput = 2
  780. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  781. # fatal error
  782. self.StyleError = 3
  783. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  784. # warning
  785. self.StyleWarning = 4
  786. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  787. # message
  788. self.StyleMessage = 5
  789. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  790. # unknown
  791. self.StyleUnknown = 6
  792. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  793. # default and clear => init
  794. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  795. self.StyleClearAll()
  796. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  797. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  798. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  799. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  800. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  801. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  802. def OnDestroy(self, evt):
  803. """!The clipboard contents can be preserved after
  804. the app has exited"""
  805. wx.TheClipboard.Flush()
  806. evt.Skip()
  807. def AddTextWrapped(self, txt, wrap=None):
  808. """!Add string to text area.
  809. String is wrapped and linesep is also added to the end
  810. of the string"""
  811. # allow writing to output window
  812. self.SetReadOnly(False)
  813. if wrap:
  814. txt = textwrap.fill(txt, wrap) + '\n'
  815. else:
  816. if txt[-1] != '\n':
  817. txt += '\n'
  818. if '\r' in txt:
  819. self.parent.linePos = -1
  820. for seg in txt.split('\r'):
  821. if self.parent.linePos > -1:
  822. self.SetCurrentPos(self.parent.linePos)
  823. self.ReplaceSelection(seg)
  824. else:
  825. self.parent.linePos = self.GetCurrentPos()
  826. self.AddText(seg)
  827. else:
  828. self.parent.linePos = self.GetCurrentPos()
  829. try:
  830. self.AddText(txt)
  831. except UnicodeDecodeError:
  832. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  833. if enc:
  834. txt = unicode(txt, enc)
  835. elif os.environ.has_key('GRASS_DB_ENCODING'):
  836. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  837. else:
  838. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  839. self.AddText(txt)
  840. # reset output window to read only
  841. self.SetReadOnly(True)