goutput.py 36 KB

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