goutput.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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' : '3d-raster',
  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. self.parent.OnCmdRun(event)
  545. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  546. self.btn_abort.Enable()
  547. def OnCmdDone(self, event):
  548. """!Command done (or aborted)"""
  549. if self.parent.GetName() == 'Modeler':
  550. self.parent.OnCmdDone(event)
  551. if event.aborted:
  552. # Thread aborted (using our convention of None return)
  553. self.WriteLog(_('Please note that the data are left in incosistent stage '
  554. 'and can be corrupted'), self.cmd_output.StyleWarning)
  555. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  556. _('Command aborted'),
  557. (time.time() - event.time)))
  558. # pid=self.cmdThread.requestId)
  559. self.btn_abort.Enable(False)
  560. else:
  561. try:
  562. # Process results here
  563. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  564. _('Command finished'),
  565. (time.time() - event.time)))
  566. except KeyError:
  567. # stopped deamon
  568. pass
  569. self.btn_abort.Enable(False)
  570. if event.onDone:
  571. event.onDone(returncode = event.returncode)
  572. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  573. self.cmd_output_timer.Stop()
  574. # set focus on prompt
  575. if self.parent.GetName() == "LayerManager":
  576. self.cmd_prompt.SetFocus()
  577. self.btn_abort.Enable(False)
  578. else:
  579. # updated command dialog
  580. dialog = self.parent.parent
  581. if hasattr(self.parent.parent, "btn_abort"):
  582. dialog.btn_abort.Enable(False)
  583. if hasattr(self.parent.parent, "btn_cancel"):
  584. dialog.btn_cancel.Enable(True)
  585. if hasattr(self.parent.parent, "btn_clipboard"):
  586. dialog.btn_clipboard.Enable(True)
  587. if hasattr(self.parent.parent, "btn_help"):
  588. dialog.btn_help.Enable(True)
  589. if hasattr(self.parent.parent, "btn_run"):
  590. dialog.btn_run.Enable(True)
  591. if event.returncode == 0 and \
  592. not event.aborted and hasattr(dialog, "addbox") and \
  593. dialog.addbox.IsChecked():
  594. # add created maps into layer tree
  595. winName = self.parent.parent.parent.GetName()
  596. if winName == 'LayerManager':
  597. mapTree = self.parent.parent.parent.curr_page.maptree
  598. else: # GMConsole
  599. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  600. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  601. for p in dialog.task.get_options()['params']:
  602. prompt = p.get('prompt', '')
  603. if prompt in ('raster', 'vector', '3d-raster') and \
  604. p.get('age', 'old') == 'new' and \
  605. p.get('value', None):
  606. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param = p.get('name', ''))
  607. if mapTree.GetMap().GetListOfLayers(l_name = name):
  608. continue
  609. if prompt == 'raster':
  610. lcmd = ['d.rast',
  611. 'map=%s' % name]
  612. else:
  613. lcmd = ['d.vect',
  614. 'map=%s' % name]
  615. mapTree.AddLayer(ltype = prompt,
  616. lcmd = lcmd,
  617. lname = name)
  618. if hasattr(dialog, "get_dcmd") and \
  619. dialog.get_dcmd is None and \
  620. dialog.closebox.IsChecked():
  621. time.sleep(1)
  622. dialog.Close()
  623. event.Skip()
  624. def OnProcessPendingOutputWindowEvents(self, event):
  625. self.ProcessPendingEvents()
  626. class GMStdout:
  627. """!GMConsole standard output
  628. Based on FrameOutErr.py
  629. Name: FrameOutErr.py
  630. Purpose: Redirecting stdout / stderr
  631. Author: Jean-Michel Fauth, Switzerland
  632. Copyright: (c) 2005-2007 Jean-Michel Fauth
  633. Licence: GPL
  634. """
  635. def __init__(self, parent):
  636. self.parent = parent # GMConsole
  637. def write(self, s):
  638. if len(s) == 0 or s == '\n':
  639. return
  640. for line in s.splitlines():
  641. if len(line) == 0:
  642. continue
  643. evt = wxCmdOutput(text=line + '\n',
  644. type='')
  645. wx.PostEvent(self.parent.cmd_output, evt)
  646. class GMStderr:
  647. """!GMConsole standard error output
  648. Based on FrameOutErr.py
  649. Name: FrameOutErr.py
  650. Purpose: Redirecting stdout / stderr
  651. Author: Jean-Michel Fauth, Switzerland
  652. Copyright: (c) 2005-2007 Jean-Michel Fauth
  653. Licence: GPL
  654. """
  655. def __init__(self, parent):
  656. self.parent = parent # GMConsole
  657. self.type = ''
  658. self.message = ''
  659. self.printMessage = False
  660. def flush(self):
  661. pass
  662. def write(self, s):
  663. if "GtkPizza" in s:
  664. return
  665. # remove/replace escape sequences '\b' or '\r' from stream
  666. progressValue = -1
  667. for line in s.splitlines():
  668. if len(line) == 0:
  669. continue
  670. if 'GRASS_INFO_PERCENT' in line:
  671. value = int(line.rsplit(':', 1)[1].strip())
  672. if value >= 0 and value < 100:
  673. progressValue = value
  674. else:
  675. progressValue = 0
  676. elif 'GRASS_INFO_MESSAGE' in line:
  677. self.type = 'message'
  678. self.message += line.split(':', 1)[1].strip() + '\n'
  679. elif 'GRASS_INFO_WARNING' in line:
  680. self.type = 'warning'
  681. self.message += line.split(':', 1)[1].strip() + '\n'
  682. elif 'GRASS_INFO_ERROR' in line:
  683. self.type = 'error'
  684. self.message += line.split(':', 1)[1].strip() + '\n'
  685. elif 'GRASS_INFO_END' in line:
  686. self.printMessage = True
  687. elif self.type == '':
  688. if len(line) == 0:
  689. continue
  690. evt = wxCmdOutput(text=line,
  691. type='')
  692. wx.PostEvent(self.parent.cmd_output, evt)
  693. elif len(line) > 0:
  694. self.message += line.strip() + '\n'
  695. if self.printMessage and len(self.message) > 0:
  696. evt = wxCmdOutput(text=self.message,
  697. type=self.type)
  698. wx.PostEvent(self.parent.cmd_output, evt)
  699. self.type = ''
  700. self.message = ''
  701. self.printMessage = False
  702. # update progress message
  703. if progressValue > -1:
  704. # self.gmgauge.SetValue(progressValue)
  705. evt = wxCmdProgress(value=progressValue)
  706. wx.PostEvent(self.parent.console_progressbar, evt)
  707. class GMStc(wx.stc.StyledTextCtrl):
  708. """!Styled GMConsole
  709. Based on FrameOutErr.py
  710. Name: FrameOutErr.py
  711. Purpose: Redirecting stdout / stderr
  712. Author: Jean-Michel Fauth, Switzerland
  713. Copyright: (c) 2005-2007 Jean-Michel Fauth
  714. Licence: GPL
  715. """
  716. def __init__(self, parent, id, margin=False, wrap=None):
  717. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  718. self.parent = parent
  719. self.SetUndoCollection(True)
  720. self.SetReadOnly(True)
  721. #
  722. # styles
  723. #
  724. self.SetStyle()
  725. #
  726. # line margins
  727. #
  728. # TODO print number only from cmdlog
  729. self.SetMarginWidth(1, 0)
  730. self.SetMarginWidth(2, 0)
  731. if margin:
  732. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  733. self.SetMarginWidth(0, 30)
  734. else:
  735. self.SetMarginWidth(0, 0)
  736. #
  737. # miscellaneous
  738. #
  739. self.SetViewWhiteSpace(False)
  740. self.SetTabWidth(4)
  741. self.SetUseTabs(False)
  742. self.UsePopUp(True)
  743. self.SetSelBackground(True, "#FFFF00")
  744. self.SetUseHorizontalScrollBar(True)
  745. #
  746. # bindings
  747. #
  748. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  749. def SetStyle(self):
  750. """!Set styles for styled text output windows with type face
  751. and point size selected by user (Courier New 10 is default)"""
  752. settings = preferences.Settings()
  753. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  754. if typeface == "": typeface = "Courier New"
  755. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  756. if typesize == None or typesize <= 0: typesize = 10
  757. typesize = float(typesize)
  758. self.StyleDefault = 0
  759. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  760. self.StyleCommand = 1
  761. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  762. self.StyleOutput = 2
  763. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  764. # fatal error
  765. self.StyleError = 3
  766. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  767. # warning
  768. self.StyleWarning = 4
  769. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  770. # message
  771. self.StyleMessage = 5
  772. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  773. # unknown
  774. self.StyleUnknown = 6
  775. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  776. # default and clear => init
  777. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  778. self.StyleClearAll()
  779. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  780. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  781. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  782. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  783. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  784. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  785. def OnDestroy(self, evt):
  786. """!The clipboard contents can be preserved after
  787. the app has exited"""
  788. wx.TheClipboard.Flush()
  789. evt.Skip()
  790. def AddTextWrapped(self, txt, wrap=None):
  791. """!Add string to text area.
  792. String is wrapped and linesep is also added to the end
  793. of the string"""
  794. # allow writing to output window
  795. self.SetReadOnly(False)
  796. if wrap:
  797. txt = textwrap.fill(txt, wrap) + '\n'
  798. else:
  799. if txt[-1] != '\n':
  800. txt += '\n'
  801. if '\r' in txt:
  802. self.parent.linePos = -1
  803. for seg in txt.split('\r'):
  804. if self.parent.linePos > -1:
  805. self.SetCurrentPos(self.parent.linePos)
  806. self.ReplaceSelection(seg)
  807. else:
  808. self.parent.linePos = self.GetCurrentPos()
  809. self.AddText(seg)
  810. else:
  811. self.parent.linePos = self.GetCurrentPos()
  812. try:
  813. self.AddText(txt)
  814. except UnicodeDecodeError:
  815. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  816. if enc:
  817. txt = unicode(txt, enc)
  818. elif os.environ.has_key('GRASS_DB_ENCODING'):
  819. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  820. else:
  821. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  822. self.AddText(txt)
  823. # reset output window to read only
  824. self.SetReadOnly(True)