goutput.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  1. """!
  2. @package gui_core.goutput
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GMConsole
  7. - goutput::GMStdout
  8. - goutput::GMStderr
  9. - goutput::GMStc
  10. - goutput::PyStc
  11. (C) 2007-2012 by the GRASS Development Team
  12. This program is free software under the GNU General Public License
  13. (>=v2). Read the file COPYING that comes with GRASS for details.
  14. @author Michael Barton (Arizona State University)
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  17. """
  18. import os
  19. import sys
  20. import textwrap
  21. import time
  22. import threading
  23. import Queue
  24. import codecs
  25. import locale
  26. import keyword
  27. import wx
  28. from wx import stc
  29. from wx.lib.newevent import NewEvent
  30. import grass.script as grass
  31. from grass.script import task as gtask
  32. from core import globalvar
  33. from core import utils
  34. from core.gcmd import CommandThread, GMessage, GError, GException, EncodeString
  35. from gui_core.forms import GUI
  36. from gui_core.prompt import GPromptSTC
  37. from core.debug import Debug
  38. from core.settings import UserSettings, Settings
  39. from gui_core.ghelp import SearchModuleWindow
  40. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  41. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  42. wxCmdRun, EVT_CMD_RUN = NewEvent()
  43. wxCmdDone, EVT_CMD_DONE = NewEvent()
  44. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  45. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  46. def GrassCmd(cmd, env = None, stdout = None, stderr = None):
  47. """!Return GRASS command thread"""
  48. return CommandThread(cmd, env = env,
  49. stdout = stdout, stderr = stderr)
  50. class CmdThread(threading.Thread):
  51. """!Thread for GRASS commands"""
  52. requestId = 0
  53. def __init__(self, parent, requestQ, resultQ, **kwds):
  54. threading.Thread.__init__(self, **kwds)
  55. self.setDaemon(True)
  56. self.parent = parent # GMConsole
  57. self._want_abort_all = False
  58. self.requestQ = requestQ
  59. self.resultQ = resultQ
  60. self.start()
  61. def RunCmd(self, *args, **kwds):
  62. CmdThread.requestId += 1
  63. self.requestCmd = None
  64. self.requestQ.put((CmdThread.requestId, args, kwds))
  65. return CmdThread.requestId
  66. def SetId(self, id):
  67. """!Set starting id"""
  68. CmdThread.requestId = id
  69. def run(self):
  70. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  71. while True:
  72. requestId, args, kwds = self.requestQ.get()
  73. for key in ('callable', 'onDone', 'onPrepare', 'userData'):
  74. if key in kwds:
  75. vars()[key] = kwds[key]
  76. del kwds[key]
  77. else:
  78. vars()[key] = None
  79. if not vars()['callable']:
  80. vars()['callable'] = GrassCmd
  81. requestTime = time.time()
  82. # prepare
  83. event = wxCmdPrepare(cmd = args[0],
  84. time = requestTime,
  85. pid = requestId,
  86. onPrepare = vars()['onPrepare'],
  87. userData = vars()['userData'])
  88. wx.PostEvent(self.parent, event)
  89. # run command
  90. event = wxCmdRun(cmd = args[0],
  91. pid = requestId)
  92. wx.PostEvent(self.parent, event)
  93. time.sleep(.1)
  94. self.requestCmd = vars()['callable'](*args, **kwds)
  95. if self._want_abort_all:
  96. self.requestCmd.abort()
  97. if self.requestQ.empty():
  98. self._want_abort_all = False
  99. self.resultQ.put((requestId, self.requestCmd.run()))
  100. try:
  101. returncode = self.requestCmd.module.returncode
  102. except AttributeError:
  103. returncode = 0 # being optimistic
  104. try:
  105. aborted = self.requestCmd.aborted
  106. except AttributeError:
  107. aborted = False
  108. time.sleep(.1)
  109. # set default color table for raster data
  110. if UserSettings.Get(group = 'cmd', key = 'rasterColorTable', subkey = 'enabled') and \
  111. args[0][0][:2] == 'r.':
  112. colorTable = UserSettings.Get(group = 'cmd', key = 'rasterColorTable', subkey = 'selection')
  113. mapName = None
  114. if args[0][0] == 'r.mapcalc':
  115. try:
  116. mapName = args[0][1].split('=', 1)[0].strip()
  117. except KeyError:
  118. pass
  119. else:
  120. moduleInterface = GUI(show = None).ParseCommand(args[0])
  121. outputParam = moduleInterface.get_param(value = 'output', raiseError = False)
  122. if outputParam and outputParam['prompt'] == 'raster':
  123. mapName = outputParam['value']
  124. if mapName:
  125. argsColor = list(args)
  126. argsColor[0] = [ 'r.colors',
  127. 'map=%s' % mapName,
  128. 'color=%s' % colorTable ]
  129. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  130. self.resultQ.put((requestId, self.requestCmdColor.run()))
  131. event = wxCmdDone(cmd = args[0],
  132. aborted = aborted,
  133. returncode = returncode,
  134. time = requestTime,
  135. pid = requestId,
  136. onDone = vars()['onDone'],
  137. userData = vars()['userData'])
  138. # send event
  139. wx.PostEvent(self.parent, event)
  140. def abort(self, abortall = True):
  141. """!Abort command(s)"""
  142. if abortall:
  143. self._want_abort_all = True
  144. self.requestCmd.abort()
  145. if self.requestQ.empty():
  146. self._want_abort_all = False
  147. class GMConsole(wx.SplitterWindow):
  148. """!Create and manage output console for commands run by GUI.
  149. """
  150. def __init__(self, parent, id = wx.ID_ANY, margin = False,
  151. notebook = None,
  152. style = wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
  153. **kwargs):
  154. wx.SplitterWindow.__init__(self, parent, id, style = style, *kwargs)
  155. self.SetName("GMConsole")
  156. self.panelOutput = wx.Panel(parent = self, id = wx.ID_ANY)
  157. self.panelPrompt = wx.Panel(parent = self, id = wx.ID_ANY)
  158. # initialize variables
  159. self.parent = parent # GMFrame | CmdPanel | ?
  160. if notebook:
  161. self._notebook = notebook
  162. else:
  163. self._notebook = self.parent.notebook
  164. self.lineWidth = 80
  165. # remember position of line begining (used for '\r')
  166. self.linePos = -1
  167. # create queues
  168. self.requestQ = Queue.Queue()
  169. self.resultQ = Queue.Queue()
  170. # progress bar
  171. self.progressbar = wx.Gauge(parent = self.panelOutput, id = wx.ID_ANY,
  172. range = 100, pos = (110, 50), size = (-1, 25),
  173. style = wx.GA_HORIZONTAL)
  174. self.progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  175. # text control for command output
  176. self.cmdOutput = GMStc(parent = self.panelOutput, id = wx.ID_ANY, margin = margin,
  177. wrap = None)
  178. self.cmdOutputTimer = wx.Timer(self.cmdOutput, id = wx.ID_ANY)
  179. self.cmdOutput.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  180. self.cmdOutput.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  181. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  182. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  183. self.Bind(EVT_CMD_PREPARE, self.OnCmdPrepare)
  184. # search & command prompt
  185. self.cmdPrompt = GPromptSTC(parent = self)
  186. if self.parent.GetName() != 'LayerManager':
  187. self.search = None
  188. self.cmdPrompt.Hide()
  189. else:
  190. self.infoCollapseLabelExp = _("Click here to show search module engine")
  191. self.infoCollapseLabelCol = _("Click here to hide search module engine")
  192. self.searchPane = wx.CollapsiblePane(parent = self.panelOutput,
  193. label = self.infoCollapseLabelExp,
  194. style = wx.CP_DEFAULT_STYLE |
  195. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  196. self.MakeSearchPaneContent(self.searchPane.GetPane())
  197. self.searchPane.Collapse(True)
  198. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane)
  199. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  200. # stream redirection
  201. self.cmdStdOut = GMStdout(self)
  202. self.cmdStdErr = GMStderr(self)
  203. # thread
  204. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  205. self.outputBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  206. label = " %s " % _("Output window"))
  207. self.cmdBox = wx.StaticBox(parent = self.panelOutput, id = wx.ID_ANY,
  208. label = " %s " % _("Command prompt"))
  209. # buttons
  210. self.btnOutputClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  211. self.btnOutputClear.SetToolTipString(_("Clear output window content"))
  212. self.btnCmdClear = wx.Button(parent = self.panelOutput, id = wx.ID_CLEAR)
  213. self.btnCmdClear.SetToolTipString(_("Clear command prompt content"))
  214. self.btnOutputSave = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
  215. self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
  216. self.btnCmdAbort = wx.Button(parent = self.panelOutput, id = wx.ID_STOP)
  217. self.btnCmdAbort.SetToolTipString(_("Abort running command"))
  218. self.btnCmdAbort.Enable(False)
  219. self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
  220. label = _("&Protocol"),
  221. size = self.btnCmdClear.GetSize())
  222. self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into file; "
  223. "content saved when switching off."))
  224. if self.parent.GetName() != 'LayerManager':
  225. self.btnCmdClear.Hide()
  226. self.btnCmdProtocol.Hide()
  227. self.btnCmdClear.Bind(wx.EVT_BUTTON, self.cmdPrompt.OnCmdErase)
  228. self.btnOutputClear.Bind(wx.EVT_BUTTON, self.OnOutputClear)
  229. self.btnOutputSave.Bind(wx.EVT_BUTTON, self.OnOutputSave)
  230. self.btnCmdAbort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  231. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  232. self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
  233. self._layout()
  234. def _layout(self):
  235. """!Do layout"""
  236. outputSizer = wx.BoxSizer(wx.VERTICAL)
  237. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  238. outBtnSizer = wx.StaticBoxSizer(self.outputBox, wx.HORIZONTAL)
  239. cmdBtnSizer = wx.StaticBoxSizer(self.cmdBox, wx.HORIZONTAL)
  240. if self.cmdPrompt.IsShown():
  241. promptSizer = wx.BoxSizer(wx.VERTICAL)
  242. promptSizer.Add(item = self.cmdPrompt, proportion = 1,
  243. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border = 3)
  244. if self.search and self.search.IsShown():
  245. outputSizer.Add(item = self.searchPane, proportion = 0,
  246. flag = wx.EXPAND | wx.ALL, border = 3)
  247. outputSizer.Add(item = self.cmdOutput, proportion = 1,
  248. flag = wx.EXPAND | wx.ALL, border = 3)
  249. outputSizer.Add(item = self.progressbar, proportion = 0,
  250. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 3)
  251. outBtnSizer.Add(item = self.btnOutputClear, proportion = 1,
  252. flag = wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT, border = 5)
  253. outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
  254. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
  255. cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
  256. flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
  257. cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
  258. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  259. cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
  260. flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
  261. if self.parent.GetName() != 'LayerManager':
  262. proportion = (1, 1)
  263. else:
  264. proportion = (2, 3)
  265. btnSizer.Add(item = outBtnSizer, proportion = proportion[0],
  266. flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
  267. btnSizer.Add(item = cmdBtnSizer, proportion = proportion[1],
  268. flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  269. outputSizer.Add(item = btnSizer, proportion = 0,
  270. flag = wx.EXPAND)
  271. outputSizer.Fit(self)
  272. outputSizer.SetSizeHints(self)
  273. self.panelOutput.SetSizer(outputSizer)
  274. if self.cmdPrompt.IsShown():
  275. promptSizer.Fit(self)
  276. promptSizer.SetSizeHints(self)
  277. self.panelPrompt.SetSizer(promptSizer)
  278. # split window
  279. if self.cmdPrompt.IsShown():
  280. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -50)
  281. else:
  282. self.SplitHorizontally(self.panelOutput, self.panelPrompt, -45)
  283. self.Unsplit()
  284. self.SetMinimumPaneSize(self.btnCmdClear.GetSize()[1] + 25)
  285. self.SetSashGravity(1.0)
  286. # layout
  287. self.SetAutoLayout(True)
  288. self.Layout()
  289. def MakeSearchPaneContent(self, pane):
  290. """!Create search pane"""
  291. border = wx.BoxSizer(wx.VERTICAL)
  292. self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmdPrompt)
  293. border.Add(item = self.search, proportion = 0,
  294. flag = wx.EXPAND | wx.ALL, border = 1)
  295. pane.SetSizer(border)
  296. border.Fit(pane)
  297. def OnSearchPaneChanged(self, event):
  298. """!Collapse search module box"""
  299. if self.searchPane.IsExpanded():
  300. self.searchPane.SetLabel(self.infoCollapseLabelCol)
  301. else:
  302. self.searchPane.SetLabel(self.infoCollapseLabelExp)
  303. self.panelOutput.Layout()
  304. self.panelOutput.SendSizeEvent()
  305. def GetPanel(self, prompt = True):
  306. """!Get panel
  307. @param prompt get prompt / output panel
  308. @return wx.Panel reference
  309. """
  310. if prompt:
  311. return self.panelPrompt
  312. return self.panelOutput
  313. def Redirect(self):
  314. """!Redirect stdout/stderr
  315. """
  316. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  317. # don't redirect when debugging is enabled
  318. sys.stdout = self.cmdStdOut
  319. sys.stderr = self.cmdStdErr
  320. else:
  321. enc = locale.getdefaultlocale()[1]
  322. if enc:
  323. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  324. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  325. else:
  326. sys.stdout = sys.__stdout__
  327. sys.stderr = sys.__stderr__
  328. def WriteLog(self, text, style = None, wrap = None,
  329. switchPage = False):
  330. """!Generic method for writing log message in
  331. given style
  332. @param line text line
  333. @param style text style (see GMStc)
  334. @param stdout write to stdout or stderr
  335. """
  336. self.cmdOutput.SetStyle()
  337. if switchPage:
  338. self._notebook.SetSelectionByName('output')
  339. if not style:
  340. style = self.cmdOutput.StyleDefault
  341. # p1 = self.cmdOutput.GetCurrentPos()
  342. p1 = self.cmdOutput.GetEndStyled()
  343. # self.cmdOutput.GotoPos(p1)
  344. self.cmdOutput.DocumentEnd()
  345. for line in text.splitlines():
  346. # fill space
  347. if len(line) < self.lineWidth:
  348. diff = self.lineWidth - len(line)
  349. line += diff * ' '
  350. self.cmdOutput.AddTextWrapped(line, wrap = wrap) # adds '\n'
  351. p2 = self.cmdOutput.GetCurrentPos()
  352. self.cmdOutput.StartStyling(p1, 0xff)
  353. self.cmdOutput.SetStyling(p2 - p1, style)
  354. self.cmdOutput.EnsureCaretVisible()
  355. def WriteCmdLog(self, line, pid = None, switchPage = True):
  356. """!Write message in selected style
  357. @param line message to be printed
  358. @param pid process pid or None
  359. @param switchPage True to switch page
  360. """
  361. if pid:
  362. line = '(' + str(pid) + ') ' + line
  363. self.WriteLog(line, style = self.cmdOutput.StyleCommand, switchPage = switchPage)
  364. def WriteWarning(self, line):
  365. """!Write message in warning style"""
  366. self.WriteLog(line, style = self.cmdOutput.StyleWarning, switchPage = True)
  367. def WriteError(self, line):
  368. """!Write message in error style"""
  369. self.WriteLog(line, style = self.cmdOutput.StyleError, switchPage = True)
  370. def RunCmd(self, command, compReg = True, switchPage = False, skipInterface = False,
  371. onDone = None, onPrepare = None, userData = None):
  372. """!Run command typed into console command prompt (GPrompt).
  373. @todo Display commands (*.d) are captured and processed
  374. separately by mapdisp.py. Display commands are rendered in map
  375. display widget that currently has the focus (as indicted by
  376. mdidx).
  377. @param command command given as a list (produced e.g. by utils.split())
  378. @param compReg True use computation region
  379. @param switchPage switch to output page
  380. @param skipInterface True to do not launch GRASS interface
  381. parser when command has no arguments given
  382. @param onDone function to be called when command is finished
  383. @param onPrepare function to be called before command is launched
  384. @param userData data defined for the command
  385. """
  386. if len(command) == 0:
  387. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  388. return
  389. # update history file
  390. env = grass.gisenv()
  391. try:
  392. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  393. env['LOCATION_NAME'],
  394. env['MAPSET'],
  395. '.bash_history'),
  396. encoding = 'utf-8', mode = 'a')
  397. except IOError, e:
  398. GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e),
  399. parent = self.parent)
  400. fileHistory = None
  401. if fileHistory:
  402. try:
  403. fileHistory.write(' '.join(command) + os.linesep)
  404. finally:
  405. fileHistory.close()
  406. if command[0] in globalvar.grassCmd:
  407. # send GRASS command without arguments to GUI command interface
  408. # except display commands (they are handled differently)
  409. if self.parent.GetName() == "LayerManager" and \
  410. command[0][0:2] == "d." and \
  411. 'help' not in ' '.join(command[1:]):
  412. # display GRASS commands
  413. try:
  414. layertype = {'d.rast' : 'raster',
  415. 'd.rast3d' : '3d-raster',
  416. 'd.rgb' : 'rgb',
  417. 'd.his' : 'his',
  418. 'd.shaded' : 'shaded',
  419. 'd.legend' : 'rastleg',
  420. 'd.rast.arrow' : 'rastarrow',
  421. 'd.rast.num' : 'rastnum',
  422. 'd.rast.leg' : 'maplegend',
  423. 'd.vect' : 'vector',
  424. 'd.thematic.area': 'thememap',
  425. 'd.vect.chart' : 'themechart',
  426. 'd.grid' : 'grid',
  427. 'd.geodesic' : 'geodesic',
  428. 'd.rhumbline' : 'rhumb',
  429. 'd.labels' : 'labels',
  430. 'd.barscale' : 'barscale',
  431. 'd.redraw' : 'redraw'}[command[0]]
  432. except KeyError:
  433. GMessage(parent = self.parent,
  434. message = _("Command '%s' not yet implemented in the WxGUI. "
  435. "Try adding it as a command layer instead.") % command[0])
  436. return
  437. if layertype == 'barscale':
  438. self.parent.curr_page.maptree.GetMapDisplay().OnAddBarscale(None)
  439. elif layertype == 'rastleg':
  440. self.parent.curr_page.maptree.GetMapDisplay().OnAddLegend(None)
  441. elif layertype == 'redraw':
  442. self.parent.curr_page.maptree.GetMapDisplay().OnRender(None)
  443. else:
  444. # add layer into layer tree
  445. lname, found = utils.GetLayerNameFromCmd(command, fullyQualified = True,
  446. layerType = layertype)
  447. if self.parent.GetName() == "LayerManager":
  448. self.parent.curr_page.maptree.AddLayer(ltype = layertype,
  449. lname = lname,
  450. lcmd = command)
  451. else:
  452. # other GRASS commands (r|v|g|...)
  453. try:
  454. task = GUI(show = None).ParseCommand(command)
  455. except GException, e:
  456. GError(parent = self,
  457. message = unicode(e),
  458. showTraceback = False)
  459. return
  460. hasParams = False
  461. if task:
  462. options = task.get_options()
  463. hasParams = options['params'] and options['flags']
  464. # check for <input>=-
  465. for p in options['params']:
  466. if p.get('prompt', '') == 'input' and \
  467. p.get('element', '') == 'file' and \
  468. p.get('age', 'new') == 'old' and \
  469. p.get('value', '') == '-':
  470. GError(parent = self,
  471. message = _("Unable to run command:\n%(cmd)s\n\n"
  472. "Option <%(opt)s>: read from standard input is not "
  473. "supported by wxGUI") % { 'cmd': ' '.join(command),
  474. 'opt': p.get('name', '') })
  475. return
  476. if len(command) == 1 and hasParams and \
  477. command[0] != 'v.krige':
  478. # no arguments given
  479. try:
  480. GUI(parent = self).ParseCommand(command)
  481. except GException, e:
  482. print >> sys.stderr, e
  483. return
  484. # switch to 'Command output' if required
  485. if switchPage:
  486. self._notebook.SetSelectionByName('output')
  487. self.parent.SetFocus()
  488. self.parent.Raise()
  489. # activate computational region (set with g.region)
  490. # for all non-display commands.
  491. if compReg:
  492. tmpreg = os.getenv("GRASS_REGION")
  493. if "GRASS_REGION" in os.environ:
  494. del os.environ["GRASS_REGION"]
  495. # process GRASS command with argument
  496. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  497. onDone = onDone, onPrepare = onPrepare, userData = userData,
  498. env = os.environ.copy())
  499. self.cmdOutputTimer.Start(50)
  500. # deactivate computational region and return to display settings
  501. if compReg and tmpreg:
  502. os.environ["GRASS_REGION"] = tmpreg
  503. else:
  504. # Send any other command to the shell. Send output to
  505. # console output window
  506. if len(command) == 1 and not skipInterface:
  507. try:
  508. task = gtask.parse_interface(command[0])
  509. except:
  510. task = None
  511. else:
  512. task = None
  513. if task:
  514. # process GRASS command without argument
  515. GUI(parent = self).ParseCommand(command)
  516. else:
  517. self.cmdThread.RunCmd(command, stdout = self.cmdStdOut, stderr = self.cmdStdErr,
  518. onDone = onDone, onPrepare = onPrepare, userData = userData)
  519. self.cmdOutputTimer.Start(50)
  520. def OnOutputClear(self, event):
  521. """!Clear content of output window"""
  522. self.cmdOutput.SetReadOnly(False)
  523. self.cmdOutput.ClearAll()
  524. self.cmdOutput.SetReadOnly(True)
  525. self.progressbar.SetValue(0)
  526. def GetProgressBar(self):
  527. """!Return progress bar widget"""
  528. return self.progressbar
  529. def GetLog(self, err = False):
  530. """!Get widget used for logging
  531. @param err True to get stderr widget
  532. """
  533. if err:
  534. return self.cmdStdErr
  535. return self.cmdStdOut
  536. def OnOutputSave(self, event):
  537. """!Save (selected) text from output window to the file"""
  538. text = self.cmdOutput.GetSelectedText()
  539. if not text:
  540. text = self.cmdOutput.GetText()
  541. # add newline if needed
  542. if len(text) > 0 and text[-1] != '\n':
  543. text += '\n'
  544. dlg = wx.FileDialog(self, message = _("Save file as..."),
  545. defaultFile = "grass_cmd_output.txt",
  546. wildcard = _("%s (*.txt)|*.txt|%s (*)|*") % (_("Text files"), _("Files")),
  547. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  548. # Show the dialog and retrieve the user response. If it is the OK response,
  549. # process the data.
  550. if dlg.ShowModal() == wx.ID_OK:
  551. path = dlg.GetPath()
  552. try:
  553. output = open(path, "w")
  554. output.write(text)
  555. except IOError, e:
  556. GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e))
  557. finally:
  558. output.close()
  559. self.parent.SetStatusText(_("Commands output saved into '%s'") % path)
  560. dlg.Destroy()
  561. def GetCmd(self):
  562. """!Get running command or None"""
  563. return self.requestQ.get()
  564. def SetCopyingOfSelectedText(self, copy):
  565. """!Enable or disable copying of selected text in to clipboard.
  566. Effects prompt and output.
  567. @param copy True for enable, False for disable
  568. """
  569. if copy:
  570. self.cmdPrompt.Bind(stc.EVT_STC_PAINTED, self.cmdPrompt.OnTextSelectionChanged)
  571. self.cmdOutput.Bind(stc.EVT_STC_PAINTED, self.cmdOutput.OnTextSelectionChanged)
  572. else:
  573. self.cmdPrompt.Unbind(stc.EVT_STC_PAINTED)
  574. self.cmdOutput.Unbind(stc.EVT_STC_PAINTED)
  575. def OnUpdateStatusBar(self, event):
  576. """!Update statusbar text"""
  577. if event.GetString():
  578. nItems = len(self.cmdPrompt.GetCommandItems())
  579. self.parent.SetStatusText(_('%d modules match') % nItems, 0)
  580. else:
  581. self.parent.SetStatusText('', 0)
  582. event.Skip()
  583. def OnCmdOutput(self, event):
  584. """!Print command output"""
  585. message = event.text
  586. type = event.type
  587. if self._notebook.GetSelection() != self._notebook.GetPageIndexByName('output'):
  588. page = self._notebook.GetPageIndexByName('output')
  589. textP = self._notebook.GetPageText(page)
  590. if textP[-1] != ')':
  591. textP += ' (...)'
  592. self._notebook.SetPageText(page, textP)
  593. # message prefix
  594. if type == 'warning':
  595. messege = 'WARNING: ' + message
  596. elif type == 'error':
  597. message = 'ERROR: ' + message
  598. p1 = self.cmdOutput.GetEndStyled()
  599. self.cmdOutput.GotoPos(p1)
  600. if '\b' in message:
  601. if self.linepos < 0:
  602. self.linepos = p1
  603. last_c = ''
  604. for c in message:
  605. if c == '\b':
  606. self.linepos -= 1
  607. else:
  608. if c == '\r':
  609. pos = self.cmdOutput.GetCurLine()[1]
  610. # self.cmdOutput.SetCurrentPos(pos)
  611. else:
  612. self.cmdOutput.SetCurrentPos(self.linepos)
  613. self.cmdOutput.ReplaceSelection(c)
  614. self.linepos = self.cmdOutput.GetCurrentPos()
  615. if c != ' ':
  616. last_c = c
  617. if last_c not in ('0123456789'):
  618. self.cmdOutput.AddTextWrapped('\n', wrap = None)
  619. self.linepos = -1
  620. else:
  621. self.linepos = -1 # don't force position
  622. if '\n' not in message:
  623. self.cmdOutput.AddTextWrapped(message, wrap = 60)
  624. else:
  625. self.cmdOutput.AddTextWrapped(message, wrap = None)
  626. p2 = self.cmdOutput.GetCurrentPos()
  627. if p2 >= p1:
  628. self.cmdOutput.StartStyling(p1, 0xff)
  629. if type == 'error':
  630. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleError)
  631. elif type == 'warning':
  632. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleWarning)
  633. elif type == 'message':
  634. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleMessage)
  635. else: # unknown
  636. self.cmdOutput.SetStyling(p2 - p1, self.cmdOutput.StyleUnknown)
  637. self.cmdOutput.EnsureCaretVisible()
  638. def OnCmdProgress(self, event):
  639. """!Update progress message info"""
  640. self.progressbar.SetValue(event.value)
  641. def CmdProtocolSave(self):
  642. """Save commands protocol into the file"""
  643. if not hasattr(self, 'cmdFileProtocol'):
  644. return # it should not happen
  645. try:
  646. output = open(self.cmdFileProtocol, "w")
  647. cmds = self.cmdPrompt.GetCommands()
  648. output.write('\n'.join(cmds))
  649. if len(cmds) > 0:
  650. output.write('\n')
  651. except IOError, e:
  652. GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e))
  653. finally:
  654. output.close()
  655. self.parent.SetStatusText(_("Commands protocol saved into '%s'") % self.cmdFileProtocol)
  656. del self.cmdFileProtocol
  657. def OnCmdProtocol(self, event = None):
  658. """!Save commands into file"""
  659. if not event.IsChecked():
  660. # stop capturing commands, save list of commands to the
  661. # protocol file
  662. self.CmdProtocolSave()
  663. else:
  664. # start capturing commands
  665. self.cmdPrompt.ClearCommands()
  666. # ask for the file
  667. dlg = wx.FileDialog(self, message = _("Save file as..."),
  668. defaultFile = "grass_cmd_protocol.txt",
  669. wildcard = _("%s (*.txt)|*.txt|%s (*)|*") % (_("Text files"), _("Files")),
  670. style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
  671. if dlg.ShowModal() == wx.ID_OK:
  672. self.cmdFileProtocol = dlg.GetPath()
  673. dlg.Destroy()
  674. def OnCmdAbort(self, event):
  675. """!Abort running command"""
  676. self.cmdThread.abort()
  677. def OnCmdRun(self, event):
  678. """!Run command"""
  679. if self.parent.GetName() == 'Modeler':
  680. self.parent.OnCmdRun(event)
  681. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  682. self.btnCmdAbort.Enable()
  683. def OnCmdPrepare(self, event):
  684. """!Prepare for running command"""
  685. if self.parent.GetName() == 'Modeler':
  686. self.parent.OnCmdPrepare(event)
  687. event.Skip()
  688. def OnCmdDone(self, event):
  689. """!Command done (or aborted)"""
  690. if self.parent.GetName() == 'Modeler':
  691. self.parent.OnCmdDone(event)
  692. # Process results here
  693. try:
  694. ctime = time.time() - event.time
  695. if ctime < 60:
  696. stime = _("%d sec") % int(ctime)
  697. else:
  698. mtime = int(ctime / 60)
  699. stime = _("%(min)d min %(sec)d sec") % { 'min' : mtime,
  700. 'sec' : int(ctime - (mtime * 60)) }
  701. except KeyError:
  702. # stopped deamon
  703. stime = _("unknown")
  704. if event.aborted:
  705. # Thread aborted (using our convention of None return)
  706. self.WriteLog(_('Please note that the data are left in inconsistent state '
  707. 'and may be corrupted'), self.cmdOutput.StyleWarning)
  708. msg = _('Command aborted')
  709. else:
  710. msg = _('Command finished')
  711. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  712. self.btnCmdAbort.Enable(False)
  713. if event.onDone:
  714. event.onDone(cmd = event.cmd, returncode = event.returncode)
  715. self.progressbar.SetValue(0) # reset progress bar on '0%'
  716. self.cmdOutputTimer.Stop()
  717. if event.cmd[0] == 'g.gisenv':
  718. Debug.SetLevel()
  719. self.Redirect()
  720. if self.parent.GetName() == "LayerManager":
  721. self.btnCmdAbort.Enable(False)
  722. if event.cmd[0] not in globalvar.grassCmd or \
  723. event.cmd[0] == 'r.mapcalc':
  724. return
  725. display = self.parent.GetLayerTree().GetMapDisplay()
  726. if not display or not display.IsAutoRendered():
  727. return
  728. mapLayers = map(lambda x: x.GetName(),
  729. display.GetMap().GetListOfLayers(l_type = 'raster') +
  730. display.GetMap().GetListOfLayers(l_type = 'vector'))
  731. try:
  732. task = GUI(show = None).ParseCommand(event.cmd)
  733. except GException, e:
  734. print >> sys.stderr, e
  735. task = None
  736. return
  737. for p in task.get_options()['params']:
  738. if p.get('prompt', '') not in ('raster', 'vector'):
  739. continue
  740. mapName = p.get('value', '')
  741. if '@' not in mapName:
  742. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  743. if mapName in mapLayers:
  744. display.GetWindow().UpdateMap(render = True)
  745. return
  746. elif self.parent.GetName() == 'Modeler':
  747. pass
  748. else: # standalone dialogs
  749. dialog = self.parent.parent
  750. if hasattr(self.parent.parent, "btn_abort"):
  751. dialog.btn_abort.Enable(False)
  752. if hasattr(self.parent.parent, "btn_cancel"):
  753. dialog.btn_cancel.Enable(True)
  754. if hasattr(self.parent.parent, "btn_clipboard"):
  755. dialog.btn_clipboard.Enable(True)
  756. if hasattr(self.parent.parent, "btn_help"):
  757. dialog.btn_help.Enable(True)
  758. if hasattr(self.parent.parent, "btn_run"):
  759. dialog.btn_run.Enable(True)
  760. if event.returncode == 0 and not event.aborted:
  761. try:
  762. winName = self.parent.parent.parent.GetName()
  763. except AttributeError:
  764. winName = ''
  765. if winName == 'LayerManager':
  766. mapTree = self.parent.parent.parent.GetLayerTree()
  767. elif winName == 'LayerTree':
  768. mapTree = self.parent.parent.parent
  769. elif winName: # GMConsole
  770. mapTree = self.parent.parent.parent.parent.GetLayerTree()
  771. else:
  772. mapTree = None
  773. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  774. if hasattr(dialog, "addbox") and dialog.addbox.IsChecked():
  775. # add created maps into layer tree
  776. for p in dialog.task.get_options()['params']:
  777. prompt = p.get('prompt', '')
  778. if prompt in ('raster', 'vector', '3d-raster') and \
  779. p.get('age', 'old') == 'new' and \
  780. p.get('value', None):
  781. name, found = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
  782. param = p.get('name', ''))
  783. if mapTree.GetMap().GetListOfLayers(l_name = name):
  784. continue
  785. if prompt == 'raster':
  786. lcmd = ['d.rast',
  787. 'map=%s' % name]
  788. else:
  789. lcmd = ['d.vect',
  790. 'map=%s' % name]
  791. mapTree.AddLayer(ltype = prompt,
  792. lcmd = lcmd,
  793. lname = name)
  794. if hasattr(dialog, "get_dcmd") and \
  795. dialog.get_dcmd is None and \
  796. hasattr(dialog, "closebox") and \
  797. dialog.closebox.IsChecked() and \
  798. (event.returncode == 0 or event.aborted):
  799. self.cmdOutput.Update()
  800. time.sleep(2)
  801. dialog.Close()
  802. def OnProcessPendingOutputWindowEvents(self, event):
  803. self.ProcessPendingEvents()
  804. def ResetFocus(self):
  805. """!Reset focus"""
  806. self.cmdPrompt.SetFocus()
  807. class GMStdout:
  808. """!GMConsole standard output
  809. Based on FrameOutErr.py
  810. Name: FrameOutErr.py
  811. Purpose: Redirecting stdout / stderr
  812. Author: Jean-Michel Fauth, Switzerland
  813. Copyright: (c) 2005-2007 Jean-Michel Fauth
  814. Licence: GPL
  815. """
  816. def __init__(self, parent):
  817. self.parent = parent # GMConsole
  818. def write(self, s):
  819. if len(s) == 0 or s == '\n':
  820. return
  821. for line in s.splitlines():
  822. if len(line) == 0:
  823. continue
  824. evt = wxCmdOutput(text = line + '\n',
  825. type = '')
  826. wx.PostEvent(self.parent.cmdOutput, evt)
  827. class GMStderr:
  828. """!GMConsole standard error output
  829. Based on FrameOutErr.py
  830. Name: FrameOutErr.py
  831. Purpose: Redirecting stdout / stderr
  832. Author: Jean-Michel Fauth, Switzerland
  833. Copyright: (c) 2005-2007 Jean-Michel Fauth
  834. Licence: GPL
  835. """
  836. def __init__(self, parent):
  837. self.parent = parent # GMConsole
  838. self.type = ''
  839. self.message = ''
  840. self.printMessage = False
  841. def flush(self):
  842. pass
  843. def write(self, s):
  844. if "GtkPizza" in s:
  845. return
  846. # remove/replace escape sequences '\b' or '\r' from stream
  847. progressValue = -1
  848. for line in s.splitlines():
  849. if len(line) == 0:
  850. continue
  851. if 'GRASS_INFO_PERCENT' in line:
  852. value = int(line.rsplit(':', 1)[1].strip())
  853. if value >= 0 and value < 100:
  854. progressValue = value
  855. else:
  856. progressValue = 0
  857. elif 'GRASS_INFO_MESSAGE' in line:
  858. self.type = 'message'
  859. self.message += line.split(':', 1)[1].strip() + '\n'
  860. elif 'GRASS_INFO_WARNING' in line:
  861. self.type = 'warning'
  862. self.message += line.split(':', 1)[1].strip() + '\n'
  863. elif 'GRASS_INFO_ERROR' in line:
  864. self.type = 'error'
  865. self.message += line.split(':', 1)[1].strip() + '\n'
  866. elif 'GRASS_INFO_END' in line:
  867. self.printMessage = True
  868. elif self.type == '':
  869. if len(line) == 0:
  870. continue
  871. evt = wxCmdOutput(text = line,
  872. type = '')
  873. wx.PostEvent(self.parent.cmdOutput, evt)
  874. elif len(line) > 0:
  875. self.message += line.strip() + '\n'
  876. if self.printMessage and len(self.message) > 0:
  877. evt = wxCmdOutput(text = self.message,
  878. type = self.type)
  879. wx.PostEvent(self.parent.cmdOutput, evt)
  880. self.type = ''
  881. self.message = ''
  882. self.printMessage = False
  883. # update progress message
  884. if progressValue > -1:
  885. # self.gmgauge.SetValue(progressValue)
  886. evt = wxCmdProgress(value = progressValue)
  887. wx.PostEvent(self.parent.progressbar, evt)
  888. class GMStc(stc.StyledTextCtrl):
  889. """!Styled GMConsole
  890. Based on FrameOutErr.py
  891. Name: FrameOutErr.py
  892. Purpose: Redirecting stdout / stderr
  893. Author: Jean-Michel Fauth, Switzerland
  894. Copyright: (c) 2005-2007 Jean-Michel Fauth
  895. Licence: GPL
  896. """
  897. def __init__(self, parent, id, margin = False, wrap = None):
  898. stc.StyledTextCtrl.__init__(self, parent, id)
  899. self.parent = parent
  900. self.SetUndoCollection(True)
  901. self.SetReadOnly(True)
  902. #
  903. # styles
  904. #
  905. self.SetStyle()
  906. #
  907. # line margins
  908. #
  909. # TODO print number only from cmdlog
  910. self.SetMarginWidth(1, 0)
  911. self.SetMarginWidth(2, 0)
  912. if margin:
  913. self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
  914. self.SetMarginWidth(0, 30)
  915. else:
  916. self.SetMarginWidth(0, 0)
  917. #
  918. # miscellaneous
  919. #
  920. self.SetViewWhiteSpace(False)
  921. self.SetTabWidth(4)
  922. self.SetUseTabs(False)
  923. self.UsePopUp(True)
  924. self.SetSelBackground(True, "#FFFF00")
  925. self.SetUseHorizontalScrollBar(True)
  926. #
  927. # bindings
  928. #
  929. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  930. def OnTextSelectionChanged(self, event):
  931. """!Copy selected text to clipboard and skip event.
  932. The same function is in TextCtrlAutoComplete class (prompt.py).
  933. """
  934. wx.CallAfter(self.Copy)
  935. event.Skip()
  936. def SetStyle(self):
  937. """!Set styles for styled text output windows with type face
  938. and point size selected by user (Courier New 10 is default)"""
  939. settings = Settings()
  940. typeface = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'type')
  941. if typeface == "":
  942. typeface = "Courier New"
  943. typesize = settings.Get(group = 'appearance', key = 'outputfont', subkey = 'size')
  944. if typesize == None or typesize <= 0:
  945. typesize = 10
  946. typesize = float(typesize)
  947. self.StyleDefault = 0
  948. self.StyleDefaultSpec = "face:%s,size:%d,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  949. self.StyleCommand = 1
  950. self.StyleCommandSpec = "face:%s,size:%d,,fore:#000000,back:#bcbcbc" % (typeface, typesize)
  951. self.StyleOutput = 2
  952. self.StyleOutputSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  953. # fatal error
  954. self.StyleError = 3
  955. self.StyleErrorSpec = "face:%s,size:%d,,fore:#7F0000,back:#FFFFFF" % (typeface, typesize)
  956. # warning
  957. self.StyleWarning = 4
  958. self.StyleWarningSpec = "face:%s,size:%d,,fore:#0000FF,back:#FFFFFF" % (typeface, typesize)
  959. # message
  960. self.StyleMessage = 5
  961. self.StyleMessageSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  962. # unknown
  963. self.StyleUnknown = 6
  964. self.StyleUnknownSpec = "face:%s,size:%d,,fore:#000000,back:#FFFFFF" % (typeface, typesize)
  965. # default and clear => init
  966. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  967. self.StyleClearAll()
  968. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  969. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  970. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  971. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  972. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  973. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  974. def OnDestroy(self, evt):
  975. """!The clipboard contents can be preserved after
  976. the app has exited"""
  977. wx.TheClipboard.Flush()
  978. evt.Skip()
  979. def AddTextWrapped(self, txt, wrap = None):
  980. """!Add string to text area.
  981. String is wrapped and linesep is also added to the end
  982. of the string"""
  983. # allow writing to output window
  984. self.SetReadOnly(False)
  985. if wrap:
  986. txt = textwrap.fill(txt, wrap) + '\n'
  987. else:
  988. if txt[-1] != '\n':
  989. txt += '\n'
  990. if '\r' in txt:
  991. self.parent.linePos = -1
  992. for seg in txt.split('\r'):
  993. if self.parent.linePos > -1:
  994. self.SetCurrentPos(self.parent.linePos)
  995. self.ReplaceSelection(seg)
  996. else:
  997. self.parent.linePos = self.GetCurrentPos()
  998. self.AddText(seg)
  999. else:
  1000. self.parent.linePos = self.GetCurrentPos()
  1001. try:
  1002. self.AddText(txt)
  1003. except UnicodeDecodeError:
  1004. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  1005. if enc:
  1006. txt = unicode(txt, enc)
  1007. elif 'GRASS_DB_ENCODING' in os.environ:
  1008. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  1009. else:
  1010. txt = EncodeString(txt)
  1011. self.AddText(txt)
  1012. # reset output window to read only
  1013. self.SetReadOnly(True)
  1014. class PyStc(stc.StyledTextCtrl):
  1015. """!Styled Python output (see gmodeler::frame::PythonPanel for
  1016. usage)
  1017. Based on StyledTextCtrl_2 from wxPython demo
  1018. """
  1019. def __init__(self, parent, id = wx.ID_ANY, statusbar = None):
  1020. stc.StyledTextCtrl.__init__(self, parent, id)
  1021. self.parent = parent
  1022. self.statusbar = statusbar
  1023. self.modified = False # content modified ?
  1024. self.faces = { 'times': 'Times New Roman',
  1025. 'mono' : 'Courier New',
  1026. 'helv' : 'Arial',
  1027. 'other': 'Comic Sans MS',
  1028. 'size' : 10,
  1029. 'size2': 8,
  1030. }
  1031. self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
  1032. self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
  1033. self.SetLexer(stc.STC_LEX_PYTHON)
  1034. self.SetKeyWords(0, " ".join(keyword.kwlist))
  1035. self.SetProperty("fold", "1")
  1036. self.SetProperty("tab.timmy.whinge.level", "1")
  1037. self.SetMargins(0, 0)
  1038. self.SetTabWidth(4)
  1039. self.SetUseTabs(False)
  1040. self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
  1041. self.SetEdgeColumn(78)
  1042. # setup a margin to hold fold markers
  1043. self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
  1044. self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
  1045. self.SetMarginSensitive(2, True)
  1046. self.SetMarginWidth(2, 12)
  1047. # like a flattened tree control using square headers
  1048. self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080")
  1049. self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080")
  1050. self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080")
  1051. self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080")
  1052. self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080")
  1053. self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
  1054. self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080")
  1055. self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
  1056. self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
  1057. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  1058. # Make some styles, the lexer defines what each style is used
  1059. # for, we just have to define what each style looks like.
  1060. # This set is adapted from Scintilla sample property files.
  1061. # global default styles for all languages
  1062. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces)
  1063. self.StyleClearAll() # reset all to be like the default
  1064. # global default styles for all languages
  1065. self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces)
  1066. self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % self.faces)
  1067. self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % self.faces)
  1068. self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
  1069. self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
  1070. # Python styles
  1071. # Default
  1072. self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
  1073. # Comments
  1074. self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % self.faces)
  1075. # Number
  1076. self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % self.faces)
  1077. # String
  1078. self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
  1079. # Single quoted string
  1080. self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces)
  1081. # Keyword
  1082. self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % self.faces)
  1083. # Triple quotes
  1084. self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % self.faces)
  1085. # Triple double quotes
  1086. self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % self.faces)
  1087. # Class name definition
  1088. self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % self.faces)
  1089. # Function or method name definition
  1090. self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % self.faces)
  1091. # Operators
  1092. self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % self.faces)
  1093. # Identifiers
  1094. self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces)
  1095. # Comment-blocks
  1096. self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % self.faces)
  1097. # End of line where string is not closed
  1098. self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces)
  1099. self.SetCaretForeground("BLUE")
  1100. def OnKeyPressed(self, event):
  1101. """!Key pressed
  1102. @todo implement code completion (see wxPython demo)
  1103. """
  1104. if not self.modified:
  1105. self.modified = True
  1106. if self.statusbar:
  1107. self.statusbar.SetStatusText(_('Python script contains local modifications'), 0)
  1108. event.Skip()
  1109. def OnUpdateUI(self, evt):
  1110. # check for matching braces
  1111. braceAtCaret = -1
  1112. braceOpposite = -1
  1113. charBefore = None
  1114. caretPos = self.GetCurrentPos()
  1115. if caretPos > 0:
  1116. charBefore = self.GetCharAt(caretPos - 1)
  1117. styleBefore = self.GetStyleAt(caretPos - 1)
  1118. # check before
  1119. if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
  1120. braceAtCaret = caretPos - 1
  1121. # check after
  1122. if braceAtCaret < 0:
  1123. charAfter = self.GetCharAt(caretPos)
  1124. styleAfter = self.GetStyleAt(caretPos)
  1125. if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
  1126. braceAtCaret = caretPos
  1127. if braceAtCaret >= 0:
  1128. braceOpposite = self.BraceMatch(braceAtCaret)
  1129. if braceAtCaret != -1 and braceOpposite == -1:
  1130. self.BraceBadLight(braceAtCaret)
  1131. else:
  1132. self.BraceHighlight(braceAtCaret, braceOpposite)
  1133. def OnMarginClick(self, evt):
  1134. # fold and unfold as needed
  1135. if evt.GetMargin() == 2:
  1136. if evt.GetShift() and evt.GetControl():
  1137. self.FoldAll()
  1138. else:
  1139. lineClicked = self.LineFromPosition(evt.GetPosition())
  1140. if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
  1141. if evt.GetShift():
  1142. self.SetFoldExpanded(lineClicked, True)
  1143. self.Expand(lineClicked, True, True, 1)
  1144. elif evt.GetControl():
  1145. if self.GetFoldExpanded(lineClicked):
  1146. self.SetFoldExpanded(lineClicked, False)
  1147. self.Expand(lineClicked, False, True, 0)
  1148. else:
  1149. self.SetFoldExpanded(lineClicked, True)
  1150. self.Expand(lineClicked, True, True, 100)
  1151. else:
  1152. self.ToggleFold(lineClicked)
  1153. def FoldAll(self):
  1154. lineCount = self.GetLineCount()
  1155. expanding = True
  1156. # find out if we are folding or unfolding
  1157. for lineNum in range(lineCount):
  1158. if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
  1159. expanding = not self.GetFoldExpanded(lineNum)
  1160. break
  1161. lineNum = 0
  1162. while lineNum < lineCount:
  1163. level = self.GetFoldLevel(lineNum)
  1164. if level & stc.STC_FOLDLEVELHEADERFLAG and \
  1165. (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
  1166. if expanding:
  1167. self.SetFoldExpanded(lineNum, True)
  1168. lineNum = self.Expand(lineNum, True)
  1169. lineNum = lineNum - 1
  1170. else:
  1171. lastChild = self.GetLastChild(lineNum, -1)
  1172. self.SetFoldExpanded(lineNum, False)
  1173. if lastChild > lineNum:
  1174. self.HideLines(lineNum+1, lastChild)
  1175. lineNum = lineNum + 1
  1176. def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
  1177. lastChild = self.GetLastChild(line, level)
  1178. line = line + 1
  1179. while line <= lastChild:
  1180. if force:
  1181. if visLevels > 0:
  1182. self.ShowLines(line, line)
  1183. else:
  1184. self.HideLines(line, line)
  1185. else:
  1186. if doExpand:
  1187. self.ShowLines(line, line)
  1188. if level == -1:
  1189. level = self.GetFoldLevel(line)
  1190. if level & stc.STC_FOLDLEVELHEADERFLAG:
  1191. if force:
  1192. if visLevels > 1:
  1193. self.SetFoldExpanded(line, True)
  1194. else:
  1195. self.SetFoldExpanded(line, False)
  1196. line = self.Expand(line, doExpand, force, visLevels-1)
  1197. else:
  1198. if doExpand and self.GetFoldExpanded(line):
  1199. line = self.Expand(line, True, force, visLevels-1)
  1200. else:
  1201. line = self.Expand(line, False, force, visLevels-1)
  1202. else:
  1203. line = line + 1
  1204. return line