goutput.py 41 KB

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