goutput.py 36 KB

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