goutput.py 36 KB

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