goutput.py 40 KB

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