goutput.py 59 KB

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