goutput.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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(aborted = aborted,
  101. returncode = returncode,
  102. time = requestTime,
  103. pid = requestId,
  104. onDone = onDone)
  105. # send event
  106. wx.PostEvent(self.parent, event)
  107. def abort(self, abortall = True):
  108. """!Abort command(s)"""
  109. if abortall:
  110. self._want_abort_all = True
  111. self.requestCmd.abort()
  112. if self.requestQ.empty():
  113. self._want_abort_all = False
  114. class GMConsole(wx.SplitterWindow):
  115. """!Create and manage output console for commands run by GUI.
  116. """
  117. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  118. notebook = None,
  119. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  120. **kwargs):
  121. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  122. self.SetName("GMConsole")
  123. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  124. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  125. # initialize variables
  126. self.Map = None
  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 in GUI GRASS (or other) commands typed into console
  323. command text widget, and send stdout output to output text
  324. widget.
  325. Command is transformed into a list for processing.
  326. @todo Display commands (*.d) are captured and processed
  327. separately by mapdisp.py. Display commands are rendered in map
  328. display widget that currently has the focus (as indicted by
  329. mdidx).
  330. @param command command (list)
  331. @param compReg if true use computation region
  332. @param switchPage switch to output page
  333. @param onDone function to be called when command is finished
  334. """
  335. # map display window available ?
  336. try:
  337. curr_disp = self.parent.curr_page.maptree.mapdisplay
  338. self.Map = curr_disp.GetRender()
  339. except:
  340. curr_disp = None
  341. # command given as a string ?
  342. try:
  343. cmdlist = command.strip().split(' ')
  344. except:
  345. cmdlist = command
  346. # update history file
  347. env = grass.gisenv()
  348. fileHistory = open(os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'],
  349. '.bash_history'), 'a')
  350. cmdString = ' '.join(cmdlist)
  351. try:
  352. fileHistory.write(cmdString + '\n')
  353. finally:
  354. fileHistory.close()
  355. # update history items
  356. if self.parent.GetName() == 'LayerManager':
  357. try:
  358. self.parent.cmdinput.SetHistoryItems()
  359. except AttributeError:
  360. pass
  361. if cmdlist[0] in globalvar.grassCmd['all']:
  362. # send GRASS command without arguments to GUI command interface
  363. # except display commands (they are handled differently)
  364. if self.parent.GetName() == "LayerManager" and cmdlist[0][0:2] == "d.":
  365. #
  366. # display GRASS commands
  367. #
  368. try:
  369. layertype = {'d.rast' : 'raster',
  370. 'd.rast3d' : 'raster3d',
  371. 'd.rgb' : 'rgb',
  372. 'd.his' : 'his',
  373. 'd.shaded' : 'shaded',
  374. 'd.legend' : 'rastleg',
  375. 'd.rast.arrow' : 'rastarrow',
  376. 'd.rast.num' : 'rastnum',
  377. 'd.vect' : 'vector',
  378. 'd.thematic.area': 'thememap',
  379. 'd.vect.chart' : 'themechart',
  380. 'd.grid' : 'grid',
  381. 'd.geodesic' : 'geodesic',
  382. 'd.rhumbline' : 'rhumb',
  383. 'd.labels' : 'labels'}[cmdlist[0]]
  384. except KeyError:
  385. gcmd.GMessage(parent = self.parent,
  386. message = _("Command '%s' not yet implemented in the WxGUI. "
  387. "Try adding it as a command layer instead.") % cmdlist[0])
  388. return None
  389. # add layer into layer tree
  390. if cmdlist[0] == 'd.rast':
  391. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  392. layerType = 'raster')
  393. elif cmdlist[0] == 'd.vect':
  394. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  395. layerType = 'vector')
  396. else:
  397. lname = None
  398. if self.parent.GetName() == "LayerManager":
  399. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  400. lname=lname,
  401. lcmd=cmdlist)
  402. else:
  403. #
  404. # other GRASS commands (r|v|g|...)
  405. #
  406. # switch to 'Command output'
  407. if switchPage:
  408. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  409. self._notebook.SetSelection(self.parent.goutput.pageid)
  410. self.parent.SetFocus() # -> set focus
  411. self.parent.Raise()
  412. # activate computational region (set with g.region)
  413. # for all non-display commands.
  414. if compReg:
  415. tmpreg = os.getenv("GRASS_REGION")
  416. if os.environ.has_key("GRASS_REGION"):
  417. del os.environ["GRASS_REGION"]
  418. if len(cmdlist) == 1 and cmdlist[0] not in ('v.krige'):
  419. import menuform
  420. # process GRASS command without argument
  421. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  422. else:
  423. # process GRASS command with argument
  424. self.cmdThread.RunCmd(GrassCmd,
  425. onDone,
  426. cmdlist,
  427. self.cmd_stdout, self.cmd_stderr)
  428. self.cmd_output_timer.Start(50)
  429. return None
  430. # deactivate computational region and return to display settings
  431. if compReg and tmpreg:
  432. os.environ["GRASS_REGION"] = tmpreg
  433. else:
  434. # Send any other command to the shell. Send output to
  435. # console output window
  436. self.cmdThread.RunCmd(GrassCmd,
  437. onDone,
  438. cmdlist,
  439. self.cmd_stdout, self.cmd_stderr)
  440. self.cmd_output_timer.Start(50)
  441. return None
  442. def ClearHistory(self, event):
  443. """!Clear history of commands"""
  444. self.cmd_output.SetReadOnly(False)
  445. self.cmd_output.ClearAll()
  446. self.cmd_output.SetReadOnly(True)
  447. self.console_progressbar.SetValue(0)
  448. def SaveHistory(self, event):
  449. """!Save history of commands"""
  450. self.history = self.cmd_output.GetSelectedText()
  451. if self.history == '':
  452. self.history = self.cmd_output.GetText()
  453. # add newline if needed
  454. if len(self.history) > 0 and self.history[-1] != '\n':
  455. self.history += '\n'
  456. wildcard = "Text file (*.txt)|*.txt"
  457. dlg = wx.FileDialog(
  458. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  459. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  460. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  461. # Show the dialog and retrieve the user response. If it is the OK response,
  462. # process the data.
  463. if dlg.ShowModal() == wx.ID_OK:
  464. path = dlg.GetPath()
  465. output = open(path, "w")
  466. output.write(self.history)
  467. output.close()
  468. dlg.Destroy()
  469. def GetCmd(self):
  470. """!Get running command or None"""
  471. return self.requestQ.get()
  472. def OnUpdateStatusBar(self, event):
  473. """!Update statusbar text"""
  474. if event.GetString():
  475. nItems = len(self.cmd_prompt.GetCommandItems())
  476. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  477. else:
  478. self.parent.SetStatusText('', 0)
  479. event.Skip()
  480. def OnCmdOutput(self, event):
  481. """!Print command output"""
  482. message = event.text
  483. type = event.type
  484. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  485. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  486. if textP[-1] != ')':
  487. textP += ' (...)'
  488. self._notebook.SetPageText(self.parent.goutput.pageid,
  489. textP)
  490. # message prefix
  491. if type == 'warning':
  492. messege = 'WARNING: ' + message
  493. elif type == 'error':
  494. message = 'ERROR: ' + message
  495. p1 = self.cmd_output.GetEndStyled()
  496. self.cmd_output.GotoPos(p1)
  497. if '\b' in message:
  498. if self.linepos < 0:
  499. self.linepos = p1
  500. last_c = ''
  501. for c in message:
  502. if c == '\b':
  503. self.linepos -= 1
  504. else:
  505. if c == '\r':
  506. pos = self.cmd_output.GetCurLine()[1]
  507. # self.cmd_output.SetCurrentPos(pos)
  508. else:
  509. self.cmd_output.SetCurrentPos(self.linepos)
  510. self.cmd_output.ReplaceSelection(c)
  511. self.linepos = self.cmd_output.GetCurrentPos()
  512. if c != ' ':
  513. last_c = c
  514. if last_c not in ('0123456789'):
  515. self.cmd_output.AddTextWrapped('\n', wrap=None)
  516. self.linepos = -1
  517. else:
  518. self.linepos = -1 # don't force position
  519. if '\n' not in message:
  520. self.cmd_output.AddTextWrapped(message, wrap=60)
  521. else:
  522. self.cmd_output.AddTextWrapped(message, wrap=None)
  523. p2 = self.cmd_output.GetCurrentPos()
  524. if p2 >= p1:
  525. self.cmd_output.StartStyling(p1, 0xff)
  526. if type == 'error':
  527. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  528. elif type == 'warning':
  529. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  530. elif type == 'message':
  531. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  532. else: # unknown
  533. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  534. self.cmd_output.EnsureCaretVisible()
  535. def OnCmdProgress(self, event):
  536. """!Update progress message info"""
  537. self.console_progressbar.SetValue(event.value)
  538. def OnCmdAbort(self, event):
  539. """!Abort running command"""
  540. self.cmdThread.abort()
  541. def OnCmdRun(self, event):
  542. """!Run command"""
  543. if self.parent.GetName() == 'Modeler':
  544. try:
  545. self.parent.GetModel().GetActions()[event.pid].Update(running = True)
  546. except IndexError:
  547. pass
  548. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  549. self.btn_abort.Enable()
  550. def OnCmdDone(self, event):
  551. """!Command done (or aborted)"""
  552. if self.parent.GetName() == 'Modeler':
  553. try:
  554. self.parent.GetModel().GetActions()[event.pid].Update(running = False)
  555. except IndexError:
  556. pass
  557. if event.aborted:
  558. # Thread aborted (using our convention of None return)
  559. self.WriteLog(_('Please note that the data are left in incosistent stage '
  560. 'and can be corrupted'), self.cmd_output.StyleWarning)
  561. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  562. _('Command aborted'),
  563. (time.time() - event.time)))
  564. # pid=self.cmdThread.requestId)
  565. self.btn_abort.Enable(False)
  566. else:
  567. try:
  568. # Process results here
  569. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  570. _('Command finished'),
  571. (time.time() - event.time)))
  572. except KeyError:
  573. # stopped deamon
  574. pass
  575. self.btn_abort.Enable(False)
  576. if event.onDone:
  577. event.onDone(returncode = event.returncode)
  578. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  579. self.cmd_output_timer.Stop()
  580. # set focus on prompt
  581. if self.parent.GetName() == "LayerManager":
  582. self.cmd_prompt.SetFocus()
  583. self.btn_abort.Enable(False)
  584. else:
  585. # updated command dialog
  586. dialog = self.parent.parent
  587. if hasattr(self.parent.parent, "btn_abort"):
  588. dialog.btn_abort.Enable(False)
  589. if hasattr(self.parent.parent, "btn_cancel"):
  590. dialog.btn_cancel.Enable(True)
  591. if hasattr(self.parent.parent, "btn_clipboard"):
  592. dialog.btn_clipboard.Enable(True)
  593. if hasattr(self.parent.parent, "btn_help"):
  594. dialog.btn_help.Enable(True)
  595. if hasattr(self.parent.parent, "btn_run"):
  596. dialog.btn_run.Enable(True)
  597. if event.returncode == 0 and \
  598. not event.aborted and hasattr(dialog, "addbox") and \
  599. dialog.addbox.IsChecked():
  600. # add created maps into layer tree
  601. winName = self.parent.parent.parent.GetName()
  602. if winName == 'LayerManager':
  603. mapTree = self.parent.parent.parent.curr_page.maptree
  604. else: # GMConsole
  605. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  606. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  607. for p in dialog.task.get_options()['params']:
  608. prompt = p.get('prompt', '')
  609. if prompt in ('raster', 'vector', '3d-raster') and \
  610. p.get('age', 'old') == 'new' and \
  611. p.get('value', None):
  612. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param = p.get('name', ''))
  613. if mapTree.GetMap().GetListOfLayers(l_name = name):
  614. continue
  615. if prompt == 'raster':
  616. lcmd = ['d.rast',
  617. 'map=%s' % name]
  618. else:
  619. lcmd = ['d.vect',
  620. 'map=%s' % name]
  621. mapTree.AddLayer(ltype = prompt,
  622. lcmd = lcmd,
  623. lname = name)
  624. if hasattr(dialog, "get_dcmd") and \
  625. dialog.get_dcmd is None and \
  626. dialog.closebox.IsChecked():
  627. time.sleep(1)
  628. dialog.Close()
  629. event.Skip()
  630. def OnProcessPendingOutputWindowEvents(self, event):
  631. self.ProcessPendingEvents()
  632. class GMStdout:
  633. """!GMConsole standard output
  634. Based on FrameOutErr.py
  635. Name: FrameOutErr.py
  636. Purpose: Redirecting stdout / stderr
  637. Author: Jean-Michel Fauth, Switzerland
  638. Copyright: (c) 2005-2007 Jean-Michel Fauth
  639. Licence: GPL
  640. """
  641. def __init__(self, parent):
  642. self.parent = parent # GMConsole
  643. def write(self, s):
  644. if len(s) == 0 or s == '\n':
  645. return
  646. for line in s.splitlines():
  647. if len(line) == 0:
  648. continue
  649. evt = wxCmdOutput(text=line + '\n',
  650. type='')
  651. wx.PostEvent(self.parent.cmd_output, evt)
  652. class GMStderr:
  653. """!GMConsole standard error output
  654. Based on FrameOutErr.py
  655. Name: FrameOutErr.py
  656. Purpose: Redirecting stdout / stderr
  657. Author: Jean-Michel Fauth, Switzerland
  658. Copyright: (c) 2005-2007 Jean-Michel Fauth
  659. Licence: GPL
  660. """
  661. def __init__(self, parent):
  662. self.parent = parent # GMConsole
  663. self.type = ''
  664. self.message = ''
  665. self.printMessage = False
  666. def flush(self):
  667. pass
  668. def write(self, s):
  669. if "GtkPizza" in s:
  670. return
  671. # remove/replace escape sequences '\b' or '\r' from stream
  672. progressValue = -1
  673. for line in s.splitlines():
  674. if len(line) == 0:
  675. continue
  676. if 'GRASS_INFO_PERCENT' in line:
  677. value = int(line.rsplit(':', 1)[1].strip())
  678. if value >= 0 and value < 100:
  679. progressValue = value
  680. else:
  681. progressValue = 0
  682. elif 'GRASS_INFO_MESSAGE' in line:
  683. self.type = 'message'
  684. self.message += line.split(':', 1)[1].strip() + '\n'
  685. elif 'GRASS_INFO_WARNING' in line:
  686. self.type = 'warning'
  687. self.message += line.split(':', 1)[1].strip() + '\n'
  688. elif 'GRASS_INFO_ERROR' in line:
  689. self.type = 'error'
  690. self.message += line.split(':', 1)[1].strip() + '\n'
  691. elif 'GRASS_INFO_END' in line:
  692. self.printMessage = True
  693. elif self.type == '':
  694. if len(line) == 0:
  695. continue
  696. evt = wxCmdOutput(text=line,
  697. type='')
  698. wx.PostEvent(self.parent.cmd_output, evt)
  699. elif len(line) > 0:
  700. self.message += line.strip() + '\n'
  701. if self.printMessage and len(self.message) > 0:
  702. evt = wxCmdOutput(text=self.message,
  703. type=self.type)
  704. wx.PostEvent(self.parent.cmd_output, evt)
  705. self.type = ''
  706. self.message = ''
  707. self.printMessage = False
  708. # update progress message
  709. if progressValue > -1:
  710. # self.gmgauge.SetValue(progressValue)
  711. evt = wxCmdProgress(value=progressValue)
  712. wx.PostEvent(self.parent.console_progressbar, evt)
  713. class GMStc(wx.stc.StyledTextCtrl):
  714. """!Styled GMConsole
  715. Based on FrameOutErr.py
  716. Name: FrameOutErr.py
  717. Purpose: Redirecting stdout / stderr
  718. Author: Jean-Michel Fauth, Switzerland
  719. Copyright: (c) 2005-2007 Jean-Michel Fauth
  720. Licence: GPL
  721. """
  722. def __init__(self, parent, id, margin=False, wrap=None):
  723. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  724. self.parent = parent
  725. self.SetUndoCollection(True)
  726. self.SetReadOnly(True)
  727. #
  728. # styles
  729. #
  730. self.SetStyle()
  731. #
  732. # line margins
  733. #
  734. # TODO print number only from cmdlog
  735. self.SetMarginWidth(1, 0)
  736. self.SetMarginWidth(2, 0)
  737. if margin:
  738. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  739. self.SetMarginWidth(0, 30)
  740. else:
  741. self.SetMarginWidth(0, 0)
  742. #
  743. # miscellaneous
  744. #
  745. self.SetViewWhiteSpace(False)
  746. self.SetTabWidth(4)
  747. self.SetUseTabs(False)
  748. self.UsePopUp(True)
  749. self.SetSelBackground(True, "#FFFF00")
  750. self.SetUseHorizontalScrollBar(True)
  751. #
  752. # bindings
  753. #
  754. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  755. def SetStyle(self):
  756. """!Set styles for styled text output windows with type face
  757. and point size selected by user (Courier New 10 is default)"""
  758. settings = preferences.Settings()
  759. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  760. if typeface == "": typeface = "Courier New"
  761. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  762. if typesize == None or typesize <= 0: typesize = 10
  763. typesize = float(typesize)
  764. self.StyleDefault = 0
  765. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  766. self.StyleCommand = 1
  767. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  768. self.StyleOutput = 2
  769. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  770. # fatal error
  771. self.StyleError = 3
  772. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  773. # warning
  774. self.StyleWarning = 4
  775. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  776. # message
  777. self.StyleMessage = 5
  778. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  779. # unknown
  780. self.StyleUnknown = 6
  781. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  782. # default and clear => init
  783. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  784. self.StyleClearAll()
  785. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  786. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  787. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  788. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  789. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  790. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  791. def OnDestroy(self, evt):
  792. """!The clipboard contents can be preserved after
  793. the app has exited"""
  794. wx.TheClipboard.Flush()
  795. evt.Skip()
  796. def AddTextWrapped(self, txt, wrap=None):
  797. """!Add string to text area.
  798. String is wrapped and linesep is also added to the end
  799. of the string"""
  800. # allow writing to output window
  801. self.SetReadOnly(False)
  802. if wrap:
  803. txt = textwrap.fill(txt, wrap) + '\n'
  804. else:
  805. if txt[-1] != '\n':
  806. txt += '\n'
  807. if '\r' in txt:
  808. self.parent.linePos = -1
  809. for seg in txt.split('\r'):
  810. if self.parent.linePos > -1:
  811. self.SetCurrentPos(self.parent.linePos)
  812. self.ReplaceSelection(seg)
  813. else:
  814. self.parent.linePos = self.GetCurrentPos()
  815. self.AddText(seg)
  816. else:
  817. self.parent.linePos = self.GetCurrentPos()
  818. try:
  819. self.AddText(txt)
  820. except UnicodeDecodeError:
  821. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  822. if enc:
  823. txt = unicode(txt, enc)
  824. elif os.environ.has_key('GRASS_DB_ENCODING'):
  825. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  826. else:
  827. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  828. self.AddText(txt)
  829. # reset output window to read only
  830. self.SetReadOnly(True)