goutput.py 38 KB

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