goutput.py 39 KB

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