goutput.py 37 KB

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