goutput.py 57 KB

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