goutput.py 36 KB

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