goutput.py 37 KB

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