goutput.py 36 KB

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