goutput.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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 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.vect.thematic': '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(message=_("Command '%s' not yet implemented.") % cmdlist[0])
  361. return None
  362. # add layer into layer tree
  363. if cmdlist[0] == 'd.rast':
  364. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  365. layerType = 'raster')
  366. elif cmdlist[0] == 'd.vect':
  367. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  368. layerType = 'vector')
  369. else:
  370. lname = None
  371. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  372. lname=lname,
  373. lcmd=cmdlist)
  374. else:
  375. #
  376. # other GRASS commands (r|v|g|...)
  377. #
  378. # switch to 'Command output'
  379. if switchPage:
  380. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  381. self._notebook.SetSelection(self.parent.goutput.pageid)
  382. self.parent.SetFocus() # -> set focus
  383. self.parent.Raise()
  384. # activate computational region (set with g.region)
  385. # for all non-display commands.
  386. if compReg:
  387. tmpreg = os.getenv("GRASS_REGION")
  388. if os.environ.has_key("GRASS_REGION"):
  389. del os.environ["GRASS_REGION"]
  390. if len(cmdlist) == 1 and cmdlist[0] not in ('v.krige'):
  391. import menuform
  392. # process GRASS command without argument
  393. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  394. else:
  395. # process GRASS command with argument
  396. self.cmdThread.RunCmd(GrassCmd,
  397. onDone,
  398. cmdlist,
  399. self.cmd_stdout, self.cmd_stderr)
  400. self.btn_abort.Enable()
  401. self.cmd_output_timer.Start(50)
  402. return None
  403. # deactivate computational region and return to display settings
  404. if compReg and tmpreg:
  405. os.environ["GRASS_REGION"] = tmpreg
  406. else:
  407. # Send any other command to the shell. Send output to
  408. # console output window
  409. self.cmdThread.RunCmd(GrassCmd,
  410. onDone,
  411. cmdlist,
  412. self.cmd_stdout, self.cmd_stderr)
  413. self.btn_abort.Enable()
  414. self.cmd_output_timer.Start(50)
  415. return None
  416. def ClearHistory(self, event):
  417. """!Clear history of commands"""
  418. self.cmd_output.SetReadOnly(False)
  419. self.cmd_output.ClearAll()
  420. self.cmd_output.SetReadOnly(True)
  421. self.console_progressbar.SetValue(0)
  422. def SaveHistory(self, event):
  423. """!Save history of commands"""
  424. self.history = self.cmd_output.GetSelectedText()
  425. if self.history == '':
  426. self.history = self.cmd_output.GetText()
  427. # add newline if needed
  428. if len(self.history) > 0 and self.history[-1] != '\n':
  429. self.history += '\n'
  430. wildcard = "Text file (*.txt)|*.txt"
  431. dlg = wx.FileDialog(
  432. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  433. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  434. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  435. # Show the dialog and retrieve the user response. If it is the OK response,
  436. # process the data.
  437. if dlg.ShowModal() == wx.ID_OK:
  438. path = dlg.GetPath()
  439. output = open(path, "w")
  440. output.write(self.history)
  441. output.close()
  442. dlg.Destroy()
  443. def GetCmd(self):
  444. """!Get running command or None"""
  445. return self.requestQ.get()
  446. def OnSearchModule(self, event):
  447. """!Search module by keywords or description"""
  448. text = event.GetString()
  449. if not text:
  450. self.cmd_prompt.SetFilter(None)
  451. return
  452. modules = dict()
  453. iFound = 0
  454. for module, data in self.cmd_prompt.moduleDesc.iteritems():
  455. found = False
  456. if self.searchBy.GetSelection() == 0: # -> description
  457. if text in data['desc']:
  458. found = True
  459. else: # -> keywords
  460. if self.cmd_prompt.CheckKey(text, data['keywords']):
  461. found = True
  462. if found:
  463. iFound += 1
  464. try:
  465. group, name = module.split('.')
  466. except ValueError:
  467. continue # TODO
  468. if not modules.has_key(group):
  469. modules[group] = list()
  470. modules[group].append(name)
  471. self.parent.statusbar.SetStatusText(_("%d modules found") % iFound)
  472. self.cmd_prompt.SetFilter(modules)
  473. def OnCmdOutput(self, event):
  474. """!Print command output"""
  475. message = event.text
  476. type = event.type
  477. if self._notebook.GetSelection() != self.parent.goutput.pageid:
  478. textP = self._notebook.GetPageText(self.parent.goutput.pageid)
  479. if textP[-1] != ')':
  480. textP += ' (...)'
  481. self._notebook.SetPageText(self.parent.goutput.pageid,
  482. textP)
  483. # message prefix
  484. if type == 'warning':
  485. messege = 'WARNING: ' + message
  486. elif type == 'error':
  487. message = 'ERROR: ' + message
  488. p1 = self.cmd_output.GetEndStyled()
  489. self.cmd_output.GotoPos(p1)
  490. if '\b' in message:
  491. if self.linepos < 0:
  492. self.linepos = p1
  493. last_c = ''
  494. for c in message:
  495. if c == '\b':
  496. self.linepos -= 1
  497. else:
  498. if c == '\r':
  499. pos = self.cmd_output.GetCurLine()[1]
  500. # self.cmd_output.SetCurrentPos(pos)
  501. else:
  502. self.cmd_output.SetCurrentPos(self.linepos)
  503. self.cmd_output.ReplaceSelection(c)
  504. self.linepos = self.cmd_output.GetCurrentPos()
  505. if c != ' ':
  506. last_c = c
  507. if last_c not in ('0123456789'):
  508. self.cmd_output.AddTextWrapped('\n', wrap=None)
  509. self.linepos = -1
  510. else:
  511. self.linepos = -1 # don't force position
  512. if '\n' not in message:
  513. self.cmd_output.AddTextWrapped(message, wrap=60)
  514. else:
  515. self.cmd_output.AddTextWrapped(message, wrap=None)
  516. p2 = self.cmd_output.GetCurrentPos()
  517. if p2 >= p1:
  518. self.cmd_output.StartStyling(p1, 0xff)
  519. if type == 'error':
  520. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  521. elif type == 'warning':
  522. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  523. elif type == 'message':
  524. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  525. else: # unknown
  526. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  527. self.cmd_output.EnsureCaretVisible()
  528. def OnCmdProgress(self, event):
  529. """!Update progress message info"""
  530. self.console_progressbar.SetValue(event.value)
  531. def OnCmdAbort(self, event):
  532. """!Abort running command"""
  533. self.cmdThread.abort()
  534. def OnCmdRun(self, event):
  535. """!Run command"""
  536. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  537. def OnCmdDone(self, event):
  538. """!Command done (or aborted)"""
  539. if event.aborted:
  540. # Thread aborted (using our convention of None return)
  541. self.WriteLog(_('Please note that the data are left in incosistent stage '
  542. 'and can be corrupted'), self.cmd_output.StyleWarning)
  543. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  544. _('Command aborted'),
  545. (time.time() - event.time)))
  546. # pid=self.cmdThread.requestId)
  547. self.btn_abort.Enable(False)
  548. else:
  549. try:
  550. # Process results here
  551. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  552. _('Command finished'),
  553. (time.time() - event.time)))
  554. except KeyError:
  555. # stopped deamon
  556. pass
  557. self.btn_abort.Enable(False)
  558. if event.onDone:
  559. event.onDone(returncode = event.returncode)
  560. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  561. self.cmd_output_timer.Stop()
  562. # set focus on prompt
  563. if self.parent.GetName() == "LayerManager":
  564. self.cmd_prompt.SetFocus()
  565. self.btn_abort.Enable(False)
  566. else:
  567. # updated command dialog
  568. dialog = self.parent.parent
  569. if hasattr(self.parent.parent, "btn_abort"):
  570. dialog.btn_abort.Enable(False)
  571. if hasattr(self.parent.parent, "btn_cancel"):
  572. dialog.btn_cancel.Enable(True)
  573. if hasattr(self.parent.parent, "btn_clipboard"):
  574. dialog.btn_clipboard.Enable(True)
  575. if hasattr(self.parent.parent, "btn_help"):
  576. dialog.btn_help.Enable(True)
  577. if hasattr(self.parent.parent, "btn_run"):
  578. dialog.btn_run.Enable(True)
  579. if event.returncode == 0 and \
  580. not event.aborted and hasattr(dialog, "addbox") and \
  581. dialog.addbox.IsChecked():
  582. # add new map into layer tree
  583. if dialog.outputType in ('raster', 'vector'):
  584. # add layer into layer tree
  585. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  586. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  587. winName = self.parent.parent.parent.GetName()
  588. if winName == 'LayerManager':
  589. mapTree = self.parent.parent.parent.curr_page.maptree
  590. else: # GMConsole
  591. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  592. if not mapTree.GetMap().GetListOfLayers(l_name = name):
  593. if dialog.outputType == 'raster':
  594. lcmd = ['d.rast',
  595. 'map=%s' % name]
  596. else:
  597. lcmd = ['d.vect',
  598. 'map=%s' % name]
  599. mapTree.AddLayer(ltype=dialog.outputType,
  600. lcmd=lcmd,
  601. lname=name)
  602. if hasattr(dialog, "get_dcmd") and \
  603. dialog.get_dcmd is None and \
  604. dialog.closebox.IsChecked():
  605. time.sleep(1)
  606. dialog.Close()
  607. event.Skip()
  608. def OnProcessPendingOutputWindowEvents(self, event):
  609. self.ProcessPendingEvents()
  610. class GMStdout:
  611. """!GMConsole standard output
  612. Based on FrameOutErr.py
  613. Name: FrameOutErr.py
  614. Purpose: Redirecting stdout / stderr
  615. Author: Jean-Michel Fauth, Switzerland
  616. Copyright: (c) 2005-2007 Jean-Michel Fauth
  617. Licence: GPL
  618. """
  619. def __init__(self, parent):
  620. self.parent = parent # GMConsole
  621. def write(self, s):
  622. if len(s) == 0 or s == '\n':
  623. return
  624. for line in s.splitlines():
  625. if len(line) == 0:
  626. continue
  627. evt = wxCmdOutput(text=line + '\n',
  628. type='')
  629. wx.PostEvent(self.parent.cmd_output, evt)
  630. class GMStderr:
  631. """!GMConsole standard error output
  632. Based on FrameOutErr.py
  633. Name: FrameOutErr.py
  634. Purpose: Redirecting stdout / stderr
  635. Author: Jean-Michel Fauth, Switzerland
  636. Copyright: (c) 2005-2007 Jean-Michel Fauth
  637. Licence: GPL
  638. """
  639. def __init__(self, parent):
  640. self.parent = parent # GMConsole
  641. self.type = ''
  642. self.message = ''
  643. self.printMessage = False
  644. def write(self, s):
  645. if "GtkPizza" in s:
  646. return
  647. # remove/replace escape sequences '\b' or '\r' from stream
  648. progressValue = -1
  649. for line in s.splitlines():
  650. if len(line) == 0:
  651. continue
  652. if 'GRASS_INFO_PERCENT' in line:
  653. value = int(line.rsplit(':', 1)[1].strip())
  654. if value >= 0 and value < 100:
  655. progressValue = value
  656. else:
  657. progressValue = 0
  658. elif 'GRASS_INFO_MESSAGE' in line:
  659. self.type = 'message'
  660. self.message += line.split(':', 1)[1].strip() + '\n'
  661. elif 'GRASS_INFO_WARNING' in line:
  662. self.type = 'warning'
  663. self.message += line.split(':', 1)[1].strip() + '\n'
  664. elif 'GRASS_INFO_ERROR' in line:
  665. self.type = 'error'
  666. self.message += line.split(':', 1)[1].strip() + '\n'
  667. elif 'GRASS_INFO_END' in line:
  668. self.printMessage = True
  669. elif self.type == '':
  670. if len(line) == 0:
  671. continue
  672. evt = wxCmdOutput(text=line,
  673. type='')
  674. wx.PostEvent(self.parent.cmd_output, evt)
  675. elif len(line) > 0:
  676. self.message += line.strip() + '\n'
  677. if self.printMessage and len(self.message) > 0:
  678. evt = wxCmdOutput(text=self.message,
  679. type=self.type)
  680. wx.PostEvent(self.parent.cmd_output, evt)
  681. self.type = ''
  682. self.message = ''
  683. self.printMessage = False
  684. # update progress message
  685. if progressValue > -1:
  686. # self.gmgauge.SetValue(progressValue)
  687. evt = wxCmdProgress(value=progressValue)
  688. wx.PostEvent(self.parent.console_progressbar, evt)
  689. class GMStc(wx.stc.StyledTextCtrl):
  690. """!Styled GMConsole
  691. Based on FrameOutErr.py
  692. Name: FrameOutErr.py
  693. Purpose: Redirecting stdout / stderr
  694. Author: Jean-Michel Fauth, Switzerland
  695. Copyright: (c) 2005-2007 Jean-Michel Fauth
  696. Licence: GPL
  697. """
  698. def __init__(self, parent, id, margin=False, wrap=None):
  699. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  700. self.parent = parent
  701. self.SetUndoCollection(True)
  702. self.SetReadOnly(True)
  703. #
  704. # styles
  705. #
  706. self.SetStyle()
  707. #
  708. # line margins
  709. #
  710. # TODO print number only from cmdlog
  711. self.SetMarginWidth(1, 0)
  712. self.SetMarginWidth(2, 0)
  713. if margin:
  714. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  715. self.SetMarginWidth(0, 30)
  716. else:
  717. self.SetMarginWidth(0, 0)
  718. #
  719. # miscellaneous
  720. #
  721. self.SetViewWhiteSpace(False)
  722. self.SetTabWidth(4)
  723. self.SetUseTabs(False)
  724. self.UsePopUp(True)
  725. self.SetSelBackground(True, "#FFFF00")
  726. self.SetUseHorizontalScrollBar(True)
  727. #
  728. # bindings
  729. #
  730. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  731. def SetStyle(self):
  732. """!Set styles for styled text output windows with type face
  733. and point size selected by user (Courier New 10 is default)"""
  734. settings = preferences.Settings()
  735. typeface = settings.Get(group='display', key='outputfont', subkey='type')
  736. if typeface == "": typeface = "Courier New"
  737. typesize = settings.Get(group='display', key='outputfont', subkey='size')
  738. if typesize == None or typesize <= 0: typesize = 10
  739. typesize = float(typesize)
  740. self.StyleDefault = 0
  741. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  742. self.StyleCommand = 1
  743. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  744. self.StyleOutput = 2
  745. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  746. # fatal error
  747. self.StyleError = 3
  748. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  749. # warning
  750. self.StyleWarning = 4
  751. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  752. # message
  753. self.StyleMessage = 5
  754. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  755. # unknown
  756. self.StyleUnknown = 6
  757. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  758. # default and clear => init
  759. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  760. self.StyleClearAll()
  761. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  762. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  763. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  764. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  765. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  766. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  767. def OnDestroy(self, evt):
  768. """!The clipboard contents can be preserved after
  769. the app has exited"""
  770. wx.TheClipboard.Flush()
  771. evt.Skip()
  772. def AddTextWrapped(self, txt, wrap=None):
  773. """!Add string to text area.
  774. String is wrapped and linesep is also added to the end
  775. of the string"""
  776. # allow writing to output window
  777. self.SetReadOnly(False)
  778. if wrap:
  779. txt = textwrap.fill(txt, wrap) + '\n'
  780. else:
  781. if txt[-1] != '\n':
  782. txt += '\n'
  783. if '\r' in txt:
  784. self.parent.linePos = -1
  785. for seg in txt.split('\r'):
  786. if self.parent.linePos > -1:
  787. self.SetCurrentPos(self.parent.linePos)
  788. self.ReplaceSelection(seg)
  789. else:
  790. self.parent.linePos = self.GetCurrentPos()
  791. self.AddText(seg)
  792. else:
  793. self.parent.linePos = self.GetCurrentPos()
  794. try:
  795. self.AddText(txt)
  796. except UnicodeDecodeError:
  797. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  798. if enc:
  799. txt = unicode(txt, enc)
  800. elif os.environ.has_key('GRASS_DB_ENCODING'):
  801. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  802. else:
  803. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  804. self.AddText(txt)
  805. # reset output window to read only
  806. self.SetReadOnly(True)