code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/env python
# vim:ts=4:sw=4:noet:
import sys
import time
from optparse import OptionParser
from c.base.version import InfoStrings
import c.base.support as support
import c.compiler.parse as parse
import c.compiler.mem as mem
import c.compiler.semantics as semantics
import c.compiler.cmg as cmg
from c.compiler.codegen import CodeGen
from c.compiler.optimise import Optimiser
from c.compiler.compiler import Compiler
sources = [
"Object",
"Magnitude",
"Collection",
"Dictionary",
"Number",
"Integer",
"SmallInt",
"Array",
"OrderedArray",
"ByteArray",
"String",
"Symbol",
"Boolean",
"False",
"True",
"Char",
"Class",
"Context",
"Method",
"Block",
"Undefined",
"System",
"Time",
"Robot",
"DrawingRobot",
"Colour",
"Shape",
"Polygon",
"UnitTest",
]
class ImageGen:
def main(self):
parser = OptionParser()
parser.add_option("-o", "--output", dest="filename", default="data/default")
parser.add_option("-n", "--nocfg", action="store_false", dest="config", default=True)
parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True)
parser.add_option("-l", "--libpath", dest="libpath", default="src")
options,args = parser.parse_args()
self.run(options, args)
def log(self, msg):
if self.options.verbose:
print msg
def run(self, options, args):
self.options = options
stat = support.Status({"exceptions":True})
p = parse.Parser(None, stat)
classes = []
self.log("Parsing")
for a in sources:
classes.extend(p.parseFile(options.libpath+"/"+a+".st"))
for a in args:
classes.extend(p.parseFile(a))
self.log("Initialising memory")
m = mem.Memory(stat)
m.createBase()
self.log("Checking semantics")
s = semantics.Checker(m, stat)
s.check(classes)
s.markUnused(classes)
self.log("Generating bytecode")
bcstart = time.time()
comp = Compiler(m, allClasses=classes)
bcTotal = 0
methCount = 0
clshash = {}
for cls in classes:
clshash[cls.name] = cls
for cls in classes:
asm = ""
for meth in cls.meths:
comp.optimiseAndGenerateMethod(cls.spy, meth)
bcTotal += len(meth.spy.bytecodes)
methCount += 1
bctime = time.time()-bcstart
self.log("%d bytecodes, %d methods, %0.2f seconds" % (bcTotal,methCount,bctime))
self.log("avg %0.1f bytes/method" % (bcTotal/float(methCount)))
self.log("Writing image")
m.readyForSave()
ofn = options.filename
oext = InfoStrings["imageExtension"]
if options.config:
size = m.save("%s.%s" % (ofn,oext), "%s.cfg" % ofn)
else:
size = m.save("%s.%s" % (ofn,oext))
self.log("%dKB written" % (size/1024))
self.log("Complete")
return
if __name__=="__main__":
ImageGen().main()
| Python |
# vim:ts=4:sw=4:noet:
import unittest
from c.compiler.parse import Parser
from c.compiler.mem import Memory
from c.compiler.semantics import Checker
from c.compiler.codegen import CodeGen, Bytecodes
from c.compiler.optimise import Optimiser
from c.compiler.disassemble import disassembleMethod
import c.compiler.spy as spy
from c.base.support import Status
NIL = 0xD
ADD = 2
def PUSHT(x): return (Bytecodes.PushTemporary<<4)|x
def PUSHC(x): return (Bytecodes.PushConstant<<4)|x
def PUSHB(x,y): return [(Bytecodes.PushBlock<<4)|x, y]
def SEND0(x): return (Bytecodes.SendMessage0<<4)|x
def SEND1(x): return (Bytecodes.SendMessage1<<4)|x
def SEND2(x): return (Bytecodes.SendMessage2<<4)|x
def SENDB(x): return (Bytecodes.SendBinary<<4)|x
def POPIT(x): return (Bytecodes.PopInstTemp<<4)|x
def STORT(x): return (Bytecodes.AssignTemporary<<4)|x
def BRNCHF(x): return [(Bytecodes.DoSpecial<<4)|Bytecodes.SpecialBranchFalse, x]
def RETST(): return (Bytecodes.DoSpecial<<4)|Bytecodes.SpecialReturnStack
def RETSF(): return (Bytecodes.DoSpecial<<4)|Bytecodes.SpecialReturnSelf
def POP(): return (Bytecodes.DoSpecial<<4)|Bytecodes.SpecialPop
class CodegenTests(unittest.TestCase):
def setUp(self):
stat = Status({"exceptions":True})
self.p = Parser(None, stat)
classes = []
self.m = Memory(stat)
self.m.createBase()
self.s = Checker(self.m, stat)
self.s.populateFromMem()
self.cg = CodeGen(self.m)
def compileMethod(self, code):
meth = self.p.parseMethodFromSource(code)
cls = self.m.globals["mainClass"]
cls.methods = spy.SpyDictionary(self.m)
self.s.checkSingleMethod(cls, meth)
self.cg.setup()
opt = Optimiser(self, self.m, [cls])
opt.doIROpts(cls.name, meth)
meth.cfg()
opt.doBBOpts(cls.name, meth)
meth.cg(self.m, self.cg)
self.cg.fixLabels()
if self.cg.seenSuper:
self.cg.literals.append(cls)
return self.cg.bcs, self.cg.literals
def makeBytecode(self, ibc):
bc = []
for a in ibc:
if isinstance(a, int):
bc.append(a)
elif isinstance(a, list):
bc.extend(a)
else:
bc.append(a())
return bc
def checkMethod(self, code, ebcs):
bc, lits = self.compileMethod(code)
ebc = self.makeBytecode(ebcs)
self.assertEqual(bc, ebc, "Bytecode mismatch.\nExpected:\n%s\n\nGot:\n%s" % (
disassembleMethod(ebc, lits)[0], disassembleMethod(bc, lits)[0]))
def testBasicIf(self):
self.checkMethod(
"foo: x [ x > 0 ifTrue: [ ^ x negate. ]. ^ x ]", [
PUSHT(1),
PUSHC(0),
SEND1(0),
BRNCHF(8),
PUSHT(1),
SEND0(1),
RETST,
PUSHC(NIL),
POP,
PUSHT(1),
RETST
])
def testToDo(self):
self.checkMethod(
"""
foo: max [
|sum|
sum := 0.
1 to: max do: [ :i |
sum := sum + i.
].
]""", [
PUSHC(0),
POPIT(10),
PUSHC(1),
PUSHT(1),
PUSHB(3, 11),
PUSHT(2),
PUSHT(3),
SENDB(ADD),
STORT(2),
RETST,
SEND2(0),
POP,
RETSF
])
| Python |
# vim:ts=4:sw=4:noet:
import unittest
from c.compiler.parse import Parser
from c.compiler.ir import *
from c.base.support import Status
def irmsg(name, recv, args, line=None):
return (IRMessage, {
"_line" : line,
"name" : name,
"recv" : recv,
"args" : args
})
def irname(name, line=None):
return (IRName, {"_line" : line, "name" : name})
def irint(val, line=None):
return (IRInteger, {"_line" : line, "value" : val})
def irstr(val, line=None):
return (IRString, {"_line" : line, "value" : val})
def irblock(stmts, line=None):
return (IRBlock, {"_line" : line, "statements" : stmts})
def irreturn(val, line=None):
return (IRReturn, {"_line" : line, "value": val})
def irassign(var, val, line=None):
return (IRAssign, {"_line" : line, "var": var, "value": val})
class ParserTests(unittest.TestCase):
def setUp(self):
self.stat = Status({"exceptions":True})
self.p = Parser(None, self.stat)
def checkParse(self, code, expect):
m = self.p.parseMethodFromSource(code)
self.checkParseExpect(m, expect)
def checkParseExpectDict(self, obj, expect):
for e in expect:
if e=="_line":
eline = expect[e]
if eline:
if len(eline)==2:
self.assertEqual(obj.line[:2], eline[:2])
else:
self.assertEqual(obj.line, eline)
else:
self.assert_(hasattr(obj, e), "%s doesn't have attribute '%s'" % (obj, e))
item = getattr(obj, e)
eitem = expect[e]
self.checkParseExpect(item, eitem)
def checkParseExpectList(self, obj, expect):
self.assertEqual(len(obj), len(expect))
for li, ei in zip(obj, expect):
self.checkParseExpect(li, ei)
def checkParseExpectTuple(self, obj, expect):
self.assert_(isinstance(obj, expect[0]), "Expected class '%s', got '%s'" % (expect[0], obj))
self.checkParseExpect(obj, expect[1])
def checkParseExpect(self, obj, expect):
if isinstance(expect, dict):
self.checkParseExpectDict(obj, expect)
elif isinstance(expect, list):
self.checkParseExpectList(obj, expect)
elif isinstance(expect, tuple):
self.checkParseExpectTuple(obj, expect)
elif isinstance(expect, str):
self.assertEqual(obj, expect)
elif isinstance(expect, int):
self.assertEqual(obj, expect)
else:
print "OMG", obj, expect
def testA(self):
self.checkParse("""
moo [
^ 3.
]""",
{"body":{"statements":[
irreturn(
irint(3, line=(3,3)),
line=(3,3)
)]}})
def testB(self):
self.checkParse("""
moo: x [
x > 1 ifTrue: [ "cheese"
^ 3.
"badger"
].
]""",
{"body":{"statements":[
irmsg("ifTrue:",
irmsg(">",
irname("x", line=(3,3)),
[irint(1)],
line=(3,3)),
[irblock([
irreturn(irint(3, line=(4,4)))
])],
line=(3,6))
]}})
def testC(self):
self.checkParse("""
main [
|n|
self penDown.
4 timesRepeat: [
n := n + 1.
].
]
""",
{"body":{"statements":[
irmsg("penDown", irname("self"), []),
irmsg("timesRepeat:", irint(4), [irblock([
irassign(
irname("n"),
irmsg(
"+",
irname("n"),
[irint(1)],
line=(6,6)),
line=(6,6))
])
])
]}})
def testBlockString(self):
self.checkParse("main [ '[' print. ]",
{"body":{"statements":[
irmsg("print", irstr("["), [])]}})
def testUnmatchedBlock(self):
ok = False
try:
self.checkParse("main [ [ ]", {})
except CoreException, e:
ok = True
self.assertEqual(e.msg, "Unexpected end of input")
self.failUnless(ok)
def testUnmatchedBlock2(self):
ok = False
try:
self.checkParse("main [ ] ]", {})
except CoreException, e:
ok = True
self.assertEqual(e.msg, "Expected End of file, got Binary message")
self.failUnless(ok)
| Python |
# vim:ts=4:sw=4:noet:
import unittest
from c.compiler.lexer import Lexer
from c.base.support import Status
class LexerTests(unittest.TestCase):
def setUp(self):
self.stat = Status({"exceptions":True})
def checkLex(self, code, expect):
l = Lexer(self.stat, code)
l.nextLex()
for eline in expect:
eln = eline[0]
evals = eline[1:]
for ev in evals:
self.failUnless(l.token)
t = l.token
self.assertEqual(l.lineNum, eln)
self.assertEqual(t.value, ev)
l.nextLex()
def testExampleA(self):
self.checkLex("""
|n|
"hello world"
4 > n ifTrue: [
'hello' printNl
].
""",(
(2, "|", "n", "|"),
(5, "4", ">", "n", "ifTrue:", "["),
(6, "hello", "printNl"),
(7, "]", ".")))
def testExampleB(self):
self.checkLex("""
"moocow
cheese
"
4 > n * 3 'mooo' "wookly" x
#( )
""",(
(6, "4", ">", "n", "*", "3", "mooo", "x"),
(7, "#(", ")")))
def testSingleCharString(self):
self.checkLex("'[' print.",
((1, "[", "print"),))
| Python |
#!/usr/bin/env python
# vim:ts=4:sw=4:noet:
import os
import markdown
import sys
import glob
outdir = "."
def genFile(basepath, ifn, title, cssfile, next="", prev=""):
ofn = basepath+outdir+"/"+ifn.split(".")[0]+".html"
idata = file(basepath+ifn, "rt").read()
hdata = file(basepath+"header.html","rt").read()
fdata = file(basepath+"footer.html","rt").read()
ohtml = markdown.markdown(idata)
of = file(ofn,"wt")
of.write(hdata % (title, cssfile))
of.write(ohtml)
of.write(fdata % (prev, next))
of.close()
def genIndex(basepath, fns):
ofn = basepath+outdir+"/tutorial.html"
hdata = file(basepath+"header.html","rt").read()
fdata = file(basepath+"footer.html","rt").read()
of = file(ofn,"wt")
of.write(hdata % ("Foxtalk Tutorial", "tutorial.css"))
of.write("<h1>Foxtalk Tutorial</h1>")
of.write("<h2>Tutorial Index</h2>")
of.write("<ul>")
for fn in fns:
sfn = fn.split(".")[0].split("_")
if sfn[0]!="tut":
pass
num = int(sfn[1])
name = " ".join(sfn[2:])
link = fn.replace(".txt",".html")
#name = fn
of.write("<li><a href=\"%s\">%s</a></li>" % (link, name))
of.write("</ul>")
next = "<a class=\"alnright\" href=\"%s\">Next</a>" % (
fns[0].replace("txt","html"))
of.write(fdata % ("",next))
of.close()
def genTutorial(basepath):
files = sorted([os.path.split(f)[-1] for f in glob.glob(basepath+"tut_*.txt")])
genIndex(basepath, files)
for i, fn in enumerate(files):
sfn = fn.split(".")[0].split("_")
if sfn[0]!="tut":
pass
num = int(sfn[1])
name = " ".join(sfn[2:])
title = "Foxtalk Tutorial - %d - %s" % (num, name)
cssfile = "tutorial.css"
#print title
next = prev = ""
if i<(len(files)-1):
next = "<a class=\"alnright\" href=\"%s\">Next</a>" % (
files[i+1].replace("txt","html"))
if (i>0):
prev = "<a class=\"alnleft\" href=\"%s\">Previous</a>" % (
files[i-1].replace("txt","html"))
else:
prev = "<a class=\"alnleft\" href=\"tutorial.html\">Previous</a>"
genFile(basepath, fn, title, cssfile, next, prev)
def genReference(basepath):
files = {
"syntax.txt" : "Foxtalk Reference",
"reference.txt" : "Foxtalk Reference",
}
for f in files:
genFile(basepath, f, files[f], "tutorial.css")
def main(args):
basepath = os.path.split(args[0])[0]+"/"
genTutorial(basepath)
genReference(basepath)
if __name__=="__main__":
main(sys.argv)
| Python |
# vim:ts=4:sw=4:noet:
import os
import sys
import compileall
import shutil
import SCons
# check if we're being run from the main SConstruct
caninstall = True
try:
Import('installbin', 'installdata')
except:
caninstall = False
# Builder helpers
def inst(x):
env.Alias("install", x)
return x
def getAllSources():
allSources = []
for root, dirs, files in os.walk(os.getcwd()+"/c"):
allSources.extend([root+"/"+f for f in files if f.endswith(".py")])
return allSources
def cleancode(target, source, env):
cleaned = 0
for root, dirs, files in os.walk(str(source[0])+"/c"):
for f in [root+"/"+f for f in files if ".pyc" not in f]:
os.remove(f)
cleaned += 1
print "%d sources cleaned " % cleaned
def runImagegen(target, source, config=False, extraSources = True):
basepath = str(source[0]).split(os.sep)
filename = str(target[0]).split(".")[0]
cfg = config and " " or " -n"
libpath = "/".join(basepath[:basepath.index("src")+1])
prgpath = "/".join(basepath[:basepath.index("src")])
if prgpath == "": prgpath = "."
cmdline = "python %s/imagegen.py -o %s %s -q -l %s" % (
prgpath, filename, cfg, libpath)
if extraSources:
cmdline += " %s" % (" ".join(map(str, source)))
os.system(cmdline)
def buildExample(target, source, env):
runImagegen(target, source)
def buildImage(target, source, env):
runImagegen(target, source, True, False)
def compileAll(target, source, env):
compileall.compile_dir(str(source[0]))
def buildPydocs(target, source, env):
outdir = os.path.split(str(target[0]))[0]
basedir = os.path.commonprefix(map(str,source))
if basedir=="":
basedir = "."
cdir = basedir+"/c"
cmdline = "epydoc --simple-term --no-private --config %s/config -o %s %s" % (
outdir, outdir, cdir)
os.system(cmdline)
def py2xxx(target, source, cmd, doinstall):
cwd = os.getcwd()
todir = str(target[0]).split(os.sep)
todir = "/".join(todir[:todir.index("dist")])
os.chdir(todir)
cmdline = "python setup.py -q %s" % cmd
os.system(cmdline)
if caninstall:
doinstall()
os.chdir(cwd)
def buildPy2app(target, source, env):
def inst():
appdir = Dir(installbin).abspath+"/Foxtalk.app"
if os.path.exists(appdir):
shutil.rmtree(appdir)
shutil.copytree("dist/Foxtalk.app", appdir)
py2xxx(target, source, "py2app", inst)
def buildPy2exe(target, source, env):
def inst():
appdir = Dir(installbin).abspath
appexe = os.path.join(appdir,"foxtalk.exe")
if os.path.exists(appexe):
os.remove(appexe)
if not os.path.exists(appdir):
os.mkdir(appdir)
shutil.copy("dist/foxtalk.exe", appexe)
shutil.copy("dist/python26.dll", appdir)
shutil.copytree("dist/lib", os.path.join(appdir,"lib"))
py2xxx(target, source, "py2exe", inst)
def buildTutorial(target, source, env):
os.system("python %s/htmldown.py" % os.path.split(str(target[0]))[0])
def mkBuilder(func, pretty):
return Builder(action=SCons.Action.Action(func, pretty))
def mkBuilderSuffix(func, sto, sfrom, pretty):
return Builder(action=SCons.Action.Action(func, pretty), suffix=sto, src_suffix=sfrom)
# Builders and Environment
env = Environment(BUILDERS = {
"Image" : mkBuilder(buildImage, "imagegen $TARGET"),
"Example" : mkBuilder(buildExample, "imagegen $TARGET"),
"CompileAll" : mkBuilder(compileAll, "compileall $TARGET"),
"Pydocs" : mkBuilder(buildPydocs, "pydocs $TARGET"),
"Py2app" : mkBuilder(buildPy2app, "py2app $TARGET"),
"Py2exe" : mkBuilder(buildPy2exe, "py2exe $TARGET"),
"Tutorial" : mkBuilder(buildTutorial, "tutorial $TARGET"),
})
# Examples
examples = []
for dir in os.listdir('src/examples/'):
print os.getcwd()
sources = Glob("src/examples/%s/*.st" % dir)
example = env.Example("data/examples/%s.fox" % dir, sources)
examples.append(example)
env.Alias("examples", examples)
# Main Image
img = env.Image("data/default.fox", Glob("src/*.st"))
env.Alias("image", "data/default.fox")
env.Clean(img, "data/default.cfg")
# Pydocs
docs = env.Pydocs("doc/index.html", getAllSources()+["doc/config"])
env.Alias("pydocs", docs)
env.Clean(docs, Glob("doc/*.html")+Glob("doc/epydoc.*")+Glob("doc/*.png"))
# Tutorial
tuts = []
for f in Glob("tutorial/*.txt"):
tuts.append(env.Tutorial(str(f).replace(".txt",".html"), f))
env.Alias("tutorial", tuts)
env.Clean("tutorial", "tutorial/tutorial.html")
allTargets = ["image", "examples", "pydocs", "tutorial"]
# Executables
if sys.platform in ["darwin", "win32"]:
setupSources = getAllSources()+["setup.py"]
if sys.platform == "darwin":
app = env.Py2app("dist/Foxtalk.app/Contents/Info.plist", setupSources)
elif sys.platform == "win32":
app = env.Py2exe("dist/foxtalk.exe", setupSources)
env.Clean(app, ["dist", "build"])
env.Depends(app, ["image", "examples"])
env.Alias("app", app)
allTargets.append("app")
# Install
if caninstall:
if sys.platform == 'linux2':
app=inst(env.Install(installbin, "foxtalk.py"))
inst(env.Install(installdata, Glob("data/default.*")))
inst(env.Install(installdata, Glob("data/*.png")))
inst(env.Install(installdata, Glob("data/*.ico")))
inst(env.CompileAll("compile", Glob("c")))
inst(env.Install(installbin, "c"))
inst(env.Command("cleancode", [installbin], cleancode))
env.Depends(app, ["image", "examples"])
elif sys.platform == 'darwin':
env.Alias("install", "app")
elif sys.platform == 'win32':
env.Alias("install", "app")
inst(env.Install(installdata, Glob("data/default.*")))
inst(env.Install(installdata, Glob("data/*.png")))
inst(env.Install(installdata, Glob("data/*.ico")))
else:
raise Exception("Platform %s not supported" % sys.platform)
inst(env.Install(installdata+"/examples", Glob("data/examples/*.fox")))
inst(env.Install(installdata+"/tutorial", Glob("tutorial/*.html")+Glob("tutorial/*.css")+Glob("tutorial/images")))
env.Clean("install", "#release")
allTargets.append("install")
env.Alias("all", allTargets)
Help("Targets:\n")
for t in sorted(allTargets):
Help(" %s\n" % t)
Default(["image", "examples"])
| Python |
import sys
from distutils.core import setup
from imagegen import ImageGen
from c.base.version import InfoStrings
import glob
# additional files
additionalFiles = [
"data/IM_ToolRun.png",
"data/IM_ToolStop.png",
"data/book_open.png",
"data/brick.png",
"data/bricks.png",
"data/car.png",
"data/cog_edit.png",
"data/cog_error.png",
"data/cog_go.png",
"data/cog.png",
"data/cross.png",
"data/IM_ToolCompile.png",
"data/IM_ToolDocs.png",
"data/package.png",
"data/server.png",
"data/tick.png",
"data/plugin.png",
"data/intro.png",
"data/fox.ico",
"data/default.fox",
"data/default.cfg",
]
APP_NAME = InfoStrings["shortname"]
APP_VERSION = InfoStrings["versionString"]
APP_DESCRIPTION = "Foxtalk Smalltalk Environment"
APP_AUTHOR = "Foxtalkbots.com"
APP_EMAIL = InfoStrings["emailInfo"]
APP_URL = InfoStrings["urlHomepage"]
APP_MAINPY = "foxtalk.py"
APP_COPYRIGHT = InfoStrings["copyright"]
APP_ID = "com.foxtalkbots"
# generate default image
#ImageGen().main()
# make win32 distribution
if sys.platform == 'win32':
import py2exe
py26MSdll = glob.glob("c:\dev\py26dlls\*.*")
# py2exe options
py2exe_options = dict(
bundle_files = 3,
compressed = 2, #True,
optimize = 2
)
# main setup
setup(
name = APP_NAME,
version = APP_VERSION,
description = APP_DESCRIPTION,
author = APP_AUTHOR,
url = APP_URL,
windows = [{
"script": APP_MAINPY,
"icon_resources": [(1, "data/fox.ico")],
}],
data_files = [("",additionalFiles),
("Microsoft.VC90.CRT", py26MSdll),
("lib\Microsoft.VC90.CRT", py26MSdll),
],
options = dict(py2exe = py2exe_options),
zipfile = "lib/library.zip" #None
)
# make OSX distribution
if sys.platform == 'darwin':
import py2app
# py2app options
py2appOptions = dict(
iconfile = 'data/fox.icns',
argv_emulation = True,
compressed = 1,
optimize = 2,
plist=dict(
CFBundleName = APP_NAME,
CFBundleDisplayName = APP_NAME,
CFBundleExecutable = APP_NAME,
CFBundleSignature = APP_NAME,
CFBundleIdentifier = APP_ID,
CFBundlePackageType = "APPL",
CFBundleShortVersionString = APP_VERSION,
CFBundleVersion = APP_VERSION,
CFBundleGetInfoString = APP_DESCRIPTION,
CFBundleIconFile = "fox.icns",
NSHumanReadableCopyright = APP_COPYRIGHT,
LSHasLocalizedDisplayName = False,
NSAppleScriptEnabled = False,
)
)
# main setup
setup(
app = [APP_MAINPY],
name = APP_NAME,
author = APP_AUTHOR,
author_email = APP_EMAIL,
url = APP_URL,
options = dict(py2app = py2appOptions),
data_files = additionalFiles,
)
| Python |
#!/usr/bin/env python
import sys
from c.ui.mainapp import MainApp
MainApp(sys.argv).run()
| Python |
#!/usr/bin/env python
import unittest
import sys
sys.path.insert(0, "test")
mods = "lexer parser codegen"
loader = unittest.TestLoader()
tests = [loader.loadTestsFromModule(__import__(m)) for m in mods.split()]
suite = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=2).run(suite)
| Python |
# vim:ts=4:sw=4:noet:
""" Binary image format """
from c.base.support import CoreException
binmsgs = ["<", "<=", "+", "="," -", "new:"]
class CMG:
def __init__(self, mem):
self.mem = mem
self.objhash = {}
self.img = [0]*0x1000
def save(self, fn):
f = file(fn,"wb")
b = self.saveToBuf()
f.write(map(chr,b))
f.close()
def saveToBuf(self):
buf = []
self.buf16(buf, self.mem.nilObject.writeCMG(self))
self.buf16(buf, self.mem.getGlobal("true").writeCMG(self))
self.buf16(buf, self.mem.getGlobal("false").writeCMG(self))
self.buf16(buf, self.mem.getGlobalValues().writeCMG(self))
self.buf16(buf, self.mem.getGlobal("SmallInt").writeCMG(self))
self.buf16(buf, self.mem.getGlobal("Integer").writeCMG(self))
self.buf16(buf, self.mem.getGlobal("Array").writeCMG(self))
self.buf16(buf, self.mem.getGlobal("Block").writeCMG(self))
self.buf16(buf, self.mem.getGlobal("Context").writeCMG(self))
self.buf16(buf, self.mem.getGlobal("Undefined").methods.get("boot").writeCMG(self))
for msg in binmsgs:
self.buf16(buf, self.mem.newSymbol(msg).writeCMG(self))
self.buf16(buf, self.mem.newSymbol("doesNotUnderstand:").writeCMG(self))
for d in self.img[0x1000:]:
self.buf16(buf,d)
self.imageSize = 2*(len(self.img)-0x1000)
return buf
def buf16(self, buf, v):
buf.append(v&0xFF)
buf.append((v>>8)&0xFF)
def newObject(self,size, bin=False):
bsize = size
if not bin:
bsize*=2
if bsize>=126:
raise CoreException("warning: object sized: %s" % size)
p = len(self.img)
if bin:
x = [0]*(2+((size+1)>>1))
x[0] = size<<2
x[0] |= (1<<15)
else:
x = [0]*(2+size)
x[0] = size<<2
self.img.extend(x)
return p
def newInteger(self, val):
if (val<0):
val = ((-val)^0xFFFF) + 1
av = (val<<2)|2
return av
| Python |
# vim:ts=4:sw=4:noet:
"""
Core compiler
"""
import semantics
import parse
import codegen
import optimise
import logging
class Compiler:
""" Core Compiler
The main compiler class, of which only one should exist since it slowly
accrues a Method IR cache used in optimisation.
"""
def __init__(self, mem, mcheck=True, allClasses=[], useMethCache = {}):
self.mem = mem
self.mcheck = mcheck
self.allClasses = allClasses
self.parser = parse.Parser(None, mem.status)
self.checker = semantics.Checker(self.mem, mem.status, mcheck)
self.checker.populateFromMem()
self.cg = codegen.CodeGen(self.mem)
self.irmethCache = useMethCache
self.__precacheIRMethods()
def __precacheIRMethods(self):
""" cache IR Methods if we're passed full IR Classes (eg, imagegen.py) """
for c in self.allClasses:
mc = {}
for m in c.meths:
mc[m.name] = m
self.irmethCache[c.name] = mc
def checkMethodSig(self, sig):
""" Check a method signature and return the method name """
irmeth = self.parser.parseMethodFromSource("%s []" % sig)
return irmeth.name
def optimiseAndGenerateMethod(self, spycls, irmeth, updateDependants=True):
""" Optimise and generate bytecodes for an IR Method """
self.cg.setup()
opt = optimise.Optimiser(self, self.mem, self.allClasses)
opt.doIROpts(spycls.name, irmeth)
irmeth.cfg()
opt.doBBOpts(spycls.name, irmeth)
irmeth.cg(self.mem, self.cg)
self.cg.fixLabels()
# If there's a super send in this method, append the methods class to the
# literal array. The VM uses this to look up the superclass
if self.cg.seenSuper:
self.cg.literals.append(spycls)
irmeth.spy.bytecodes = self.cg.bcs
irmeth.spy.bclines = self.cg.bclines
irmeth.spy.literals = self.cg.literals
irmeth.spy.maxStack = self.cg.maxStack
irmeth.spy.maxTemps = irmeth.maxTemps
if updateDependants:
#print "compiled %s, do depends:" % (irmeth.name)
for depcls, depmeth in irmeth.spy.getDependants():
c = Compiler(self.mem, True, [], useMethCache = self.irmethCache)
source = "%s [ %s ]" % (depmeth.sig, depmeth.source)
c.compileMethod(depcls, source, updateDependants=False)
print "do dep for %s: %s>>%s" % (irmeth.name, depcls.name, depmeth.name)
self.__cacheIRMethod(spycls.name, irmeth.name, irmeth)
return irmeth.spy
def compileMethod(self, spycls, source, updateDependants=True):
""" Compile, optimise and generate bytecodes for method source
If updateDependants is true, recompile all methods that depend on this
method, since they may have inlined the previous version of this method
"""
irmeth = self.parser.parseMethodFromSource(source)
self.checker.checkSingleMethod(spycls, irmeth)
oldDeps = irmeth.spy.revdependants
irmeth.spy.clearRevDependants()
ret = self.optimiseAndGenerateMethod(spycls, irmeth, updateDependants)
for kd in oldDeps:
depcls, depmeth = oldDeps[kd]
if kd not in irmeth.spy.revdependants:
print "removing old dependency:", kd
depmeth.removeDependant(spycls, irmeth.spy)
return ret
def compileFile(self, sourcefile):
""" Compile an entire Smalltalk sourcefile """
classes = self.parser.parseFile(sourcefile)
self.checker.check(classes)
cname = ""
for cls in classes:
if cls.name[:4]!="Meta":
cname = cls.name
for meth in cls.meths:
self.mem.addMessage(meth.name)
self.optimiseAndGenerateMethod(cls.spy, meth, False)
return cname
def deleteCachedIRMethod(self, clsname, methname):
if clsname not in self.irmethCache:
return
if methname not in self.irmethCache[clsname]:
return
del self.irmethCache[clsname][methname]
def __cacheIRMethod(self, clsname, methname, irmeth):
""" Add an IR Method to the cache """
if clsname not in self.irmethCache:
self.irmethCache[clsname] = {}
self.irmethCache[clsname][methname] = irmeth
def getIRForMethod(self, clsname, methname):
""" Get IR Method from cache, or compile and cache it """
if clsname in self.irmethCache:
mc = self.irmethCache[clsname]
if methname in mc:
return mc[methname]
spycls = self.mem.getGlobal(clsname)
if spycls:
spymeth = spycls.getMethod(methname)
if spymeth:
self.__cacheIRMethod(clsname, methname, None)
source = "%s [ %s ]" % (spymeth.sig,spymeth.source)
c = Compiler(self.mem, self.mcheck, [], useMethCache = self.irmethCache)
c.compileMethod(spycls, source, updateDependants=False)
return self.irmethCache[clsname][methname]
logging.warn("getIRForMethod: no idea what to do")
return None
| Python |
# vim:ts=4:sw=4:noet:
""" Bytecode generator """
import spy
import logging
from c.base.support import CoreException
MAX_METHOD_SIZE = 120
class Bytecodes:
PushInstance = 0
PushTemporary = 1
PushLiteral = 2
PushConstant = 3
PushBlock = 4
DoPrimitive = 5
PopInstTemp = 6
AssignInstance = 7
AssignTemporary = 8
SendMessage = 9
SendMessage0 = 10
SendMessage1 = 11
SendMessage2 = 12
SendUnary = 13
SendBinary = 14
DoSpecial = 15
# 0
SpecialReturnSelf = 1
SpecialReturnStack = 2
SpecialReturnBlock = 3
SpecialDuplicate = 4
SpecialPop = 5
SpecialBranch = 6
SpecialBranchTrue = 7
SpecialBranchFalse = 8
# 9
# 10
SpecialSendSuper = 11
SpecialPushSt = 12
SpecialPopSt = 13
# 14
# 15
class CodeGen:
def __init__(self, mem):
self.mem = mem
self.setup()
def setup(self):
self.rlabels = {}
self.labeluse = {}
self.literals = []
self.bcs = []
self.bclines = []
self.firstLine = None
# record if we've seen a super send, because we need to add
# the super as a literal
self.seenSuper = False
# keep track of stack size - probably not entirely correct,
# but at least overestimates, which shouldn't cause problems
self.maxStack = 0
self.curStack = 0
def incStack(self, n=1):
self.curStack += n
self.maxStack = max(self.curStack, self.maxStack)
def decStack(self, n=1):
self.curStack -= n
if self.curStack<0:
logging.error("Possible stack underflow")
def lineNum(self, l):
if not self.firstLine:
self.firstLine = l[0]
nb = len(self.bcs)
self.bclines.append([nb,(l[0]-self.firstLine)])
def addBC(self, bc):
self.bcs.append(bc)
if len(self.bcs)>MAX_METHOD_SIZE:
raise CoreException("Method too large")
def addHighLow(self, hi, lo):
self.addBC((hi<<4)|lo)
def addSpecial(self, op):
self.addBC((Bytecodes.DoSpecial<<4)|op)
def fixLabels(self):
for idx in self.labeluse:
lb, ln = self.labeluse[idx]
targ = self.rlabels[lb]
if ln==1:
self.bcs[idx] = targ
else:
raise CoreException("Unhandled jump target len: %d" % ln)
def addLabelUse(self, lb, ln):
self.labeluse[len(self.bcs)] = (lb,ln)
def getLiteral(self, value):
if value in self.literals:
return self.literals.index(value)
self.literals.append(value)
if len(self.literals)>256:
raise CoreException("Too many literals")
return len(self.literals)-1
def label(self, lb):
self.rlabels[lb] = len(self.bcs) # mark the current bc count as a label
def pushInstance(self, pos):
self.addHighLow(Bytecodes.PushInstance, pos)
self.incStack()
def pushTemporary(self, pos):
if pos==-1:
pos = 0
self.addHighLow(Bytecodes.PushTemporary, pos)
self.incStack()
def pushLiteral(self, name):
if name == self.mem.nilObject:
self.addHighLow(Bytecodes.PushConstant, 0xD)
elif name == self.mem.trueObject:
self.addHighLow(Bytecodes.PushConstant, 0xE)
elif name == self.mem.falseObject:
self.addHighLow(Bytecodes.PushConstant, 0xF)
elif (isinstance(name, spy.SpySmallInt) and name.value==-1):
self.addHighLow(Bytecodes.PushConstant, 0xB)
elif (isinstance(name, spy.SpySmallInt) and name.value==-2):
self.addHighLow(Bytecodes.PushConstant, 0xC)
elif (isinstance(name, spy.SpySmallInt) and
name.value<=10 and name.value>=0):
self.addHighLow(Bytecodes.PushConstant, name.value)
else:
pos = self.getLiteral(name)
if pos<15:
self.addHighLow(Bytecodes.PushLiteral, pos)
else:
self.addHighLow(Bytecodes.PushLiteral, 0xF)
self.addBC(pos)
self.incStack()
def popInstance(self, pos):
if pos>=8:
raise Exception("too many instance vars: %d" % pos)
self.addHighLow(Bytecodes.PopInstTemp, pos)
def popTemporary(self, pos):
if pos>=8:
raise Exception("too many temps: %d" % pos)
self.addHighLow(Bytecodes.PopInstTemp, 8|pos)
def storeInstance(self, pos):
self.addHighLow(Bytecodes.AssignInstance, pos)
def storeTemporary(self, pos):
self.addHighLow(Bytecodes.AssignTemporary, pos)
def send(self, msg, nargs):
if nargs==0:
code = Bytecodes.SendMessage0
elif nargs==1:
code = Bytecodes.SendMessage1
elif nargs==2:
code = Bytecodes.SendMessage2
else:
code = Bytecodes.SendMessage
pos = self.getLiteral(msg)
if pos<15:
self.addHighLow(code, pos)
else:
self.addHighLow(code, 0xF)
self.addBC(pos)
if nargs>=3:
self.addBC(nargs+1)
self.decStack(nargs)
def sendu(self, msg, n):
self.addHighLow(Bytecodes.SendUnary, n)
def sendb(self, msg, n):
self.addHighLow(Bytecodes.SendBinary, n)
self.decStack()
def pushBlock(self, args, end):
self.addHighLow(Bytecodes.PushBlock, args)
self.addLabelUse(end, 1)
self.addBC(0)
self.incStack()
def prim(self, v, nargs):
self.addHighLow(Bytecodes.DoPrimitive, nargs)
self.addBC(v)
self.decStack(nargs-1)
def returnSelf(self):
self.addSpecial(Bytecodes.SpecialReturnSelf)
def returnStack(self):
self.addSpecial(Bytecodes.SpecialReturnStack)
self.decStack()
def returnBlock(self):
self.addSpecial(Bytecodes.SpecialReturnBlock)
def cascadeStart(self):
self.addSpecial(Bytecodes.SpecialDuplicate)
self.incStack()
def pop(self):
self.addSpecial(Bytecodes.SpecialPop)
self.decStack()
def branch(self, lb):
self.addSpecial(Bytecodes.SpecialBranch)
self.addLabelUse(lb,1)
self.addBC(0)
def branchIfTrue(self, lb):
self.addSpecial(Bytecodes.SpecialBranchTrue)
self.addLabelUse(lb,1)
self.addBC(0)
self.decStack()
def branchIfFalse(self, lb):
self.addSpecial(Bytecodes.SpecialBranchFalse)
self.addLabelUse(lb,1)
self.addBC(0)
self.decStack()
def pushSmalltalk(self):
self.addSpecial(Bytecodes.SpecialPushSt)
self.incStack()
def popSmalltalk(self):
self.addSpecial(Bytecodes.SpecialPopSt)
def sendSuper(self, msg, nargs):
self.addSpecial(Bytecodes.SpecialSendSuper)
self.addBC(self.getLiteral(msg))
self.addBC(nargs+1)
self.seenSuper = True
def cascadeEnd(self):
self.pop()
| Python |
# vim:ts=4:sw=4:noet:
""" Optimiser Core """
from opt.bbopt import OptTrim
from opt.iropt import OptInline
class Optimiser:
def __init__(self, compiler, mem, classes):
self.mem = mem
self.compiler = compiler
self.classes = classes
self.opttrim = OptTrim()
self.optinline = OptInline(self.compiler, self.mem, self.classes)
def doIROpts(self, cls, meth):
self.optinline.doMethod(cls, meth)
def doBBOpts(self, cls, meth):
self.opttrim.doMethod(meth)
| Python |
# vim:ts=4:sw=4:noet:
""" Intermediate Compiler Representation """
import spy
import cfg
from environment import Environment
import cmg
import logging
from c.base.support import CoreException
# IR Node
class IRNode:
def __init__(self, line):
self.line = line
self.checked = False
def cfg(self, body, bb, inBlock=False):
raise CoreException("Unhandled CFG: %s" % self)
def cg(self, cgen):
raise CoreException("Unhandled CG: %s" % self)
def genConstLit(self, cgen):
raise CoreException("Unhandled genConstLit: %s" % self)
def isJump(self):
return False
def isSuper(self):
return False
# IR Class
class IRClass(IRNode):
def __init__(self, line, name, supername, ivars, meths, docs, pragmas):
IRNode.__init__(self, line)
self.name = name
self.supername = supername
self.ivars = ivars
self.meths = meths
self.docs = docs
self.pragmas = pragmas
# IR Method
class IRMethod(IRNode):
def __init__(self, line, name, args, temps, maxtemps, body, source, docs):
IRNode.__init__(self, line)
self.name = name
self.args = args
self.temps = temps
self.maxtemps = maxtemps
self.body = body
self.source = source
self.docs = docs
def getSig(self):
if len(self.args)==1:
return self.name
elif len(self.args)==2 and ":" not in self.name:
return "%s %s" % (self.name, self.args[1])
else:
r = ""
for i, k in enumerate(self.name.split(":")):
if not k:
break
r += "%s: %s " % (k, self.args[i+1])
return r[:-1]
def canInline(self):
cannotInline = [
"ifTrue:",
"ifFalse:",
"ifTrue:ifFalse:",
"whileTrue:",
"whileFalse:",
]
if ((self.name in cannotInline) or
(len(self.body.statements)!=1) or
(not isinstance(self.body.statements[0], IRReturn))):
return False
retv = self.body.statements[0].value
return isinstance(retv, (IRInteger,IRString,IRChar,IRSymbol))
def cfg(self):
self.body.cfg()
def cg(self, mem, cgen):
cgen.lineNum(self.line)
self.body.cg(cgen)
# IR Body
class IRBody(IRNode):
def __init__(self, line, statements):
IRNode.__init__(self, line)
self.statements = statements
self.bb = None
def cfg(self):
self.bb = cfg.CFGBasicBlock(name="entry")
curbb = self.bb
for st in self.statements:
curbb = st.cfg(self, curbb)
curbb.addStatement(cfg.CFGEndStatement())
curbb.addStatement(cfg.CFGEndBody())
def cg(self, cgen):
cgen.lineNum(self.line)
self.bb.cleanup()
self.bb.cg(cgen)
# IR Block
class IRBlock(IRNode):
def __init__(self, line, args, statements):
IRNode.__init__(self, line)
self.statements = statements
self.args = args
self.bb = None
def cfg(self, body, bb, inline=False, inBlock=False):
if inline:
curbb = bb
for i, st in enumerate(self.statements):
curbb = st.cfg(self, curbb, inBlock)
if i<(len(self.statements)-1):
curbb.addStatement(cfg.CFGEndStatement())
return curbb
else:
curbb = cfg.CFGBasicBlock(name="block")
startbb = curbb
bb.addNext(curbb)
for i, st in enumerate(self.statements):
curbb = st.cfg(self, curbb, True)
if i<(len(self.statements)-1):
curbb.addStatement(cfg.CFGEndStatement())
if len(self.statements)==0:
curbb.addStatement(IRName(self.line, "nil", 0))
curbb.addStatement(cfg.CFGEndBlock())
nextbb = cfg.CFGBasicBlock(name="endblock")
bb.addStatement(cfg.CFGStartBlock(self.tempStart, startbb, nextbb))
curbb.addNext(nextbb)
bb.addNext(nextbb)
return nextbb
def cg(self, cgen):
pass
def __repr__(self):
return "(irblock %d %d)" % (len(self.statements), len(self.args))
# IR Message
class IRMessage(IRNode):
def __init__(self, line, recv, name, args):
IRNode.__init__(self, line)
self.name = name
self.recv = recv
self.args = args
def cfgIf(self, body, bb, truen, falsen, inBlock):
if self.recv:
bb = self.recv.cfg(body, bb, inBlock)
bbt = cfg.CFGBasicBlock(name=truen)
bbf = cfg.CFGBasicBlock(name=falsen)
bbn = cfg.CFGBasicBlock(name="endif")
bb.addNext(bbt)
bb.addNext(bbf)
return bb, bbt, bbf, bbn
def cfgSpecialIf(self, body, bb, truen, falsen, nextTrue, nextVal, inBlock):
bb, bbt, bbf, bbn = self.cfgIf(body, bb, truen, falsen, inBlock)
if nextTrue:
bba, bbb = bbt, bbf
else:
bba, bbb = bbf, bbt
bbb.addNext(bbn)
bbb.addStatement(IRName(self.line, nextVal, 0))
self.args[0].cfg(body, bba, inline=True, inBlock=inBlock).addNext(bbn)
if len(self.args[0].statements)==0:
bba.addStatement(IRName(self.line, "nil", 0))
bb.addStatement(cfg.CFGIf(bbt, bbf, bbn, iftrue=(not nextTrue)))
return bbn
def cfg(self, body, bb, inBlock=False):
argsAreBlocks = all(isinstance(arg, IRBlock) for arg in self.args)
if self.name=="ifTrue:ifFalse:" and argsAreBlocks:
# optimise a ifTrue: [...] ifFalse: [...] calls
bb, bbt, bbf, bbn = self.cfgIf(body, bb, "true", "false", inBlock)
self.args[0].cfg(body, bbt, inline=True, inBlock=inBlock).addNext(bbn)
self.args[1].cfg(body, bbf, inline=True, inBlock=inBlock).addNext(bbn)
if len(self.args[0].statements)==0:
bbt.addStatement(IRName(self.line, "nil", 0))
if len(self.args[1].statements)==0:
bbf.addStatement(IRName(self.line, "nil", 0))
bb.addStatement(cfg.CFGIf(bbt, bbf, bbn))
return bbn
elif self.name=="ifTrue:" and argsAreBlocks:
# optimise a ifTrue: [...] call
return self.cfgSpecialIf(body, bb, "true", "false", True, "nil", inBlock)
elif self.name=="ifFalse:" and argsAreBlocks:
# optimise a ifFalse: [...] call
return self.cfgSpecialIf(body, bb, "true", "false", False, "nil", inBlock)
elif self.name=="and:" and argsAreBlocks:
# optimise a and: [...] call
return self.cfgSpecialIf(body, bb, "and", "shortcirc", True, "false", inBlock)
elif self.name=="or:" and argsAreBlocks:
# optimise a or: [...] call
return self.cfgSpecialIf(body, bb, "shortcirc", "or", False, "true", inBlock)
elif self.name=="whileTrue:" and isinstance(self.recv, IRBlock) and argsAreBlocks:
# optimise a whileTrue: [...] call
bbc = cfg.CFGBasicBlock(name="whilecond")
bbw = cfg.CFGBasicBlock(name="whilebody")
bbn = cfg.CFGBasicBlock(name="endwhile")
bb.addNext(bbc)
bbcend = self.recv.cfg(body, bbc, inline=True)
bbcend.addNext(bbw)
bbcend.addNext(bbn)
bbwend = self.args[0].cfg(body, bbw, inline=True, inBlock=inBlock)
if len(self.args[0].statements)>0:
bbwend.addStatement(cfg.CFGEndStatement())
bbwend.addNext(bbc)
bbn.addStatement(IRName(self.line, "nil", 0))
bbcend.addStatement(cfg.CFGIf(bbw, bbn, bbn, iftrue=False))
return bbn
else:
if self.recv:
bb = self.recv.cfg(body, bb, inBlock=inBlock)
for arg in self.args:
bb = arg.cfg(body, bb, inBlock=inBlock)
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
unames = ["isNil", "notNil"]
symname = cgen.mem.newSymbol(self.name)
if self.recv and self.recv.isSuper():
cgen.sendSuper(symname, len(self.args))
elif len(self.args)==1 and self.name in cmg.binmsgs:
cgen.sendb(symname, cmg.binmsgs.index(self.name))
elif len(self.args)==0 and self.name in unames:
cgen.sendu(symname, unames.index(self.name))
else:
cgen.send(symname, len(self.args))
def __repr__(self):
return "(irmsg %s %d)" % (self.name, len(self.args))
# IR Return
class IRReturn(IRNode):
def __init__(self, line, value):
IRNode.__init__(self, line)
self.value = value
def cfg(self, body, bb, inBlock=False):
self.inBlock = inBlock
bb = self.value.cfg(body, bb, inBlock)
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
if self.inBlock:
cgen.returnBlock()
else:
cgen.returnStack()
def __repr__(self):
return "(irreturn)"
# IR Integer
class IRInteger(IRNode):
def __init__(self, line, value):
IRNode.__init__(self, line)
self.value = value
def cfg(self, body, bb, inBlock=False):
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
if (self.value < 8192) and (self.value >= -8192):
cgen.pushLiteral(spy.SpySmallInt(cgen.mem, self.value))
else:
cgen.pushLiteral(spy.SpyInteger(cgen.mem, self.value))
def genConstLit(self, cgen):
if (self.value < 8192) and (self.value >= -8192):
return spy.SpySmallInt(cgen.mem, self.value)
else:
return spy.SpyInteger(cgen.mem, self.value)
def __repr__(self):
return "(irint %d)" % (self.value)
# IR String
class IRString(IRNode):
def __init__(self, line, value):
IRNode.__init__(self, line)
self.value = value
def cfg(self, body, bb, inBlock=False):
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
cgen.pushLiteral(spy.SpyString(cgen.mem, self.value))
def genConstLit(self, cgen):
return spy.SpyString(cgen.mem, self.value)
def __repr__(self):
return "(irstr '%s')" % (self.value)
# IR Char
class IRChar(IRNode):
def __init__(self, line, value):
IRNode.__init__(self, line)
self.value = value
def cfg(self, body, bb, inBlock=False):
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
cgen.pushLiteral(spy.SpyChar(cgen.mem, self.value))
def genConstLit(self, cgen):
return spy.SpyChar(cgen.mem, self.value)
def __repr__(self):
return "(irchar '%s')" % (self.value)
# IR Name
class IRName(IRNode):
def __init__(self, line, name, type=None):
IRNode.__init__(self, line)
self.name = name
if type!=None:
self.type = type
def cfg(self, body, bb, inBlock=False):
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
if self.type==Environment.GLOBAL:
if self.name=="Smalltalk":
cgen.pushSmalltalk()
else:
if not cgen.mem.getGlobal(self.name):
logging.error("couldn't find global '%s'" % self.name)
cgen.pushLiteral(cgen.mem.getGlobal(self.name))
elif self.type==Environment.IVAR:
cgen.pushInstance(self.pos)
elif self.type==Environment.METH_TEMP:
cgen.pushTemporary(self.pos)
elif self.type==Environment.BLOCK_ARG:
cgen.pushTemporary(self.pos)
else:
raise CoreException("Unhandled irname type in cg: %s" % Environment.typenames[self.type])
def isSuper(self):
return self.type==Environment.METH_TEMP and self.pos==-1
def __repr__(self):
return "(irname '%s')" % self.name
# IR Symbol
class IRSymbol(IRNode):
def __init__(self, line, name):
IRNode.__init__(self, line)
self.name = name
def cfg(self, body, bb, inBlock=False):
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
cgen.pushLiteral(cgen.mem.newSymbol(self.name))
def genConstLit(self, cgen):
return spy.SpySymbol(cgen.mem, self.name)
def __repr__(self):
return "(irsym #%s)" % (self.name)
# IR Array (Const)
class IRArray(IRNode):
def __init__(self, line, values):
IRNode.__init__(self, line)
self.values = values
def cfg(self, body, bb, inBlock=False):
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
cgen.pushLiteral(
spy.SpyArray(cgen.mem,
map(lambda x: x.genConstLit(cgen), self.values)))
def __repr__(self):
return "(irarray #(%s))" % (self.values)
# IR Primitive
class IRPrimitive(IRNode):
def __init__(self, line, value, args):
IRNode.__init__(self, line)
self.value = value
self.args = args
def cfg(self, body, bb, inBlock=False):
for arg in self.args:
bb = arg.cfg(body, bb, inBlock)
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
cgen.prim(self.value, len(self.args))
def __repr__(self):
return "(irprim %d %d)" % (self.value, len(self.args))
# IR Assign
class IRAssign(IRNode):
def __init__(self, line, var, value):
IRNode.__init__(self, line)
self.var = var
self.value = value
self.doPop = False
def addPop(self):
self.doPop = True
def cfg(self, body, bb, inBlock=False):
bb = self.value.cfg(body, bb, inBlock)
bb.addStatement(self)
return bb
def cg(self, cgen):
cgen.lineNum(self.line)
if self.var.type==Environment.IVAR:
if self.doPop:
cgen.popInstance(self.var.pos)
else:
cgen.storeInstance(self.var.pos)
elif (self.var.type==Environment.METH_TEMP or
self.var.type==Environment.BLOCK_ARG):
if self.doPop:
cgen.popTemporary(self.var.pos)
else:
cgen.storeTemporary(self.var.pos)
elif (self.var.type==Environment.GLOBAL and
self.var.name=="Smalltalk"):
cgen.popSmalltalk()
else:
raise CoreException("Unhandled irname type in cg: %s (%s)" % (
Environment.typenames[self.var.type], self.var.name))
def __repr__(self):
return "(irassign %s)" % (self.var)
# IR Cascade
class IRCascade(IRNode):
def __init__(self, line, node):
IRNode.__init__(self, line)
self.node = node
def cfg(self, body, bb, inBlock=False):
self.node.cfg(body, bb, inBlock)
for i, casc in enumerate(self.list):
last = i == (len(self.list)-1)
if not last:
bb.addStatement(IRCascadeMark(1))
casc.cfg(body, bb, inBlock)
bb.addStatement(IRCascadeMark(0))
else:
casc.cfg(body, bb, inBlock)
return bb
class IRCascadeMark:
def __init__(self, start):
self.start = start
def cg(self, cgen):
if self.start:
cgen.cascadeStart()
else:
cgen.cascadeEnd()
def __repr__(self):
return "(ircascade %d)" % self.start
| Python |
# vim:ts=4:sw=4:noet:
""" Semantic Checker """
import spy
import ir
from environment import Environment
class IRProxy:
def __init__(self, spyobj):
self.spy = spyobj
if isinstance(spyobj, spy.SpyClass):
self.ivars = spyobj.instanceNames
self.name = spyobj.name
if isinstance(spyobj.parent, spy.SpyClass):
self.supername = spyobj.parent.name
else:
self.supername = "nil"
else:
self.ivars = []
self.supername = ""
class Checker:
def __init__(self, mem, status, mcheck=True):
self.mem = mem
self.status = status
self.classHash = {}
self.messageUsage = {"boot": 1}
self.checkValidMessages = mcheck
def populateFromMem(self):
for g in self.mem.globals:
if g not in self.classHash:
self.classHash[g] = IRProxy(self.mem.globals[g])
def markUnused(self, classes):
for c in classes:
for m in c.meths:
m.used = (m.name in self.messageUsage)
def check(self, classes):
for c in classes:
self.classHash[c.name] = c
self.checked = {}
for c in classes:
self.checkClass(c)
def checkClass(self, cls):
# check if we've already checked this class
if cls.name in self.checked:
return
self.checked[cls.name] = True
# find and set the superclass
if cls.supername not in self.classHash:
supercls = self.mem.getGlobal(cls.supername)
if not supercls:
self.status.error(
"Couldn't find superclass '%s' for class '%s'" % (
cls.supername, cls.name))
# try get the spyclass for this class
spyobj = self.mem.getGlobal(cls.name)
if not spyobj:
supercls = self.mem.getGlobal(cls.supername)
if not supercls:
self.checkClass(self.classHash[cls.supername])
spyobj = spy.SpyClass(self.mem, cls.name, supercls)
self.mem.addGlobal(cls.name, spyobj)
# try get the metaclass and check it
if not spyobj.cls:
if cls.name[:4]=="Meta":
if not self.mem.getGlobal("Class"):
self.checkClass(self.classHash["Class"])
spyobj.cls = self.mem.getGlobal("Class")
else:
self.checkClass(self.classHash["Meta"+cls.name])
spyobj.cls = self.mem.getGlobal("Meta"+cls.name)
# check superclass
if not spyobj.parent:
supercls = self.mem.getGlobal(cls.supername)
if not supercls:
self.checkClass(self.classHash[cls.supername])
spyobj.parent = supercls
# setup instance variables
curcls = cls
ivarnames = []
theseIvars = []
for iv in curcls.ivars:
theseIvars.append(iv)
while curcls:
for i,iv in enumerate(curcls.ivars):
ivarnames.insert(i,iv)
if curcls.supername in self.classHash:
curcls = self.classHash[curcls.supername]
else:
break
spyobj.instanceNames = theseIvars
spyobj.instanceSize = len(ivarnames)
spyobj.docs = cls.docs
spyobj.pragmas = cls.pragmas
# setup base environment
self.clsEnv = Environment(self, ivarnames, None, Environment.IVAR, cls.name)
# create method dictionary
if not spyobj.methods:
spyobj.methods = spy.SpyDictionary(self.mem)
# check methods
for m in cls.meths:
self.checkMethod(cls, spyobj, m)
cls.spy = spyobj
def checkSingleMethod(self, spycls, meth):
self.clsEnv = Environment(self, spycls.getAllIvars(), None, Environment.IVAR, spycls.name)
self.checkMethod(None, spycls, meth)
def checkMethod(self, cls, spycls, meth):
if spycls.hasMethod(meth.name):
spymeth = spycls.methods.get(meth.name)
spymeth.sig = meth.getSig()
spymeth.args = meth.args
spymeth.source = meth.source
# A recompiled method loses the docs, so set the IRMethod's docs from
# the old SpyMethod
if meth.docs=="":
meth.docs = spymeth.docs
else:
spymeth = spy.SpyMethod(self.mem, meth.name, spycls, meth.source)
spymeth.sig = meth.getSig()
spymeth.args = meth.args
if len(spycls.methods)>50:
self.status.error("Class '%s' has too many methods" % spycls.name)
spycls.methods.add(meth.name, spymeth)
spymeth.docs = meth.docs
temps = []
temps.extend(meth.args)
temps.extend(meth.temps)
self.curEnv = Environment(self, temps, self.clsEnv, Environment.METH_TEMP, meth.name)
self.tempSize = len(temps)
self.tempMax = self.tempSize
for st in meth.body.statements:
self.checkExpression(meth, st)
meth.spy = spymeth
meth.maxTemps = self.tempMax
def checkExpression(self, m, st):
if isinstance(st, ir.IRReturn): self.checkReturn(m, st)
elif isinstance(st, ir.IRAssign): self.checkAssign(m, st)
elif isinstance(st, ir.IRMessage): self.checkMessage(m, st)
elif isinstance(st, ir.IRPrimitive): self.checkPrimitive(m, st)
elif isinstance(st, ir.IRName): self.checkName(m, st)
elif isinstance(st, ir.IRCascade): self.checkCascade(m, st)
elif isinstance(st, ir.IRInteger): self.checkInteger(m, st)
elif isinstance(st, ir.IRString): self.checkString(m, st)
elif isinstance(st, ir.IRSymbol): self.checkSymbol(m, st)
elif isinstance(st, ir.IRBlock): self.checkBlock(m, st)
elif isinstance(st, ir.IRChar): self.checkChar(m, st)
elif isinstance(st, ir.IRArray): self.checkArray(m, st)
elif st==None:
pass
else:
self.status.error("ir node not understood: %s" % st)
def checkReturn(self, m, st):
self.checkExpression(m, st.value)
def checkAssign(self, m, st):
self.checkExpression(m, st.var)
self.checkExpression(m, st.value)
def checkMessage(self, m, st):
if (self.checkValidMessages and self.mem.messageTable and
(st.name not in self.mem.messageTable)):
self.status.error("No class responds to '%s'" % st.name, st.line)
if st.name in self.messageUsage:
self.messageUsage[st.name] += 1
else:
self.messageUsage[st.name] = 1
self.checkExpression(m, st.recv)
for a in st.args:
self.checkExpression(m, a)
def checkBlock(self, m, st):
st.tempStart = self.tempSize
self.tempStart = st.tempStart
self.tempSize += len(st.args)
if self.tempSize > self.tempMax:
self.tempMax = self.tempSize
self.curEnv = Environment(self, st.args, self.curEnv, Environment.BLOCK_ARG, m.name, st.tempStart)
for bst in st.statements:
self.checkExpression(m, bst)
self.curEnv = self.curEnv.parent
self.tempSize -= len(st.args)
def checkName(self, m, st):
if st.checked:
return
st.checked = True
if st.name == "super":
st.type = Environment.METH_TEMP
st.pos = -1
return
ne = self.curEnv.has(st.name)
if ne:
st.type = ne.type
st.pos = ne.get(st.name)
if st.type == Environment.BLOCK_ARG:
st.pos += ne.varBase
else:
st.type = Environment.GLOBAL
st.pos = 0
if (st.name!="Smalltalk") and (st.name not in self.classHash):
if not self.mem.getGlobal(st.name):
self.status.error("Couldn't find variable '%s'" % st.name, st.line)
def checkCascade(self, m, st):
self.checkExpression(m, st.node)
for stc in st.list:
self.checkExpression(m, stc)
def checkPrimitive(self, m, st):
for stp in st.args:
self.checkExpression(m, stp)
def checkInteger(self, m, st):
pass
def checkString(self, m, st):
pass
def checkSymbol(self, m, st):
pass
def checkChar(self, m, st):
pass
def checkArray(self, m, st):
for v in st.values:
self.checkExpression(m, v)
| Python |
# vim:ts=4:sw=4:noet:
""" Object memory management and serialisation support """
import os
import pickle
import spy
import datetime
import logging
IMAGE_VERSION = 1
CORE_DEPENDANCIES = [
"Array",
"Block",
"ByteArray",
"Char",
"Class",
"Method",
"OrderedArray",
"Object",
"True",
"False",
"Undefined",
"Symbol",
"true",
"false",
"nil",
"mainClass"
]
import StringIO
import sys
class FoxUnpickler(pickle.Unpickler):
PICKLE_SAFE = {
'copy_reg': set(['_reconstructor']),
'__builtin__': set(['object']),
'datetime' : set(['datetime']),
'c.compiler.mem' : set(['Mem', 'Image']),
'c.compiler.spy' : "all",
}
def find_class(self, module, name):
if not module in self.PICKLE_SAFE:
raise pickle.UnpicklingError('Attempting to unpickle unsafe module %s' % module)
__import__(module)
mod = sys.modules[module]
if self.PICKLE_SAFE[module]!="all":
if not name in self.PICKLE_SAFE[module]:
raise pickle.UnpicklingError('Attempting to unpickle unsafe class %s' % name)
return getattr(mod, name)
@classmethod
def loads(cls, st):
return cls(StringIO.StringIO(st)).load()
class Image:
def __init__(self, globals, symbols, date=None):
self.globals = globals
self.symbols = symbols
self.version = IMAGE_VERSION
if date:
self.date = date
else:
self.date = datetime.datetime.now()
class Memory:
_instance = None
def __init__(self, status):
self.status = status
self.globals = {}
self.symbols = {}
self.haveGlobals = False
self.date = None
self.defaultDate = None
Memory._instance = self
self.messageTable = None
self.oldImage = False
def loadDefaultDate(self, filename):
if os.path.exists(filename):
f = file(filename, "rb")
self.defaultDate = pickle.load(f)
f.close()
else:
self.defaultDate = datetime.datetime(1970,1,1)
def reset(self):
self.globals = {}
self.symbols = {}
self.haveGlobals = False
def addGlobal(self, name, value):
self.globals[name] = value
if self.haveGlobals:
self.globalValues.add(name, value)
return value
def getGlobal(self, name):
if name in self.globals:
return self.globals[name]
return None
def removeGlobal(self, name):
if name in self.globals:
del self.globals[name]
if self.globalValues.has(name):
self.globalValues.remove(name)
def newSymbol(self, name):
if name in self.symbols:
return self.symbols[name]
sym = spy.SpySymbol(self, name)
self.symbols[name] = sym
return sym
def createBase(self):
self.nilObject = spy.SpyObject(self, None)
self.SymbolClass = spy.SpyClass(self, "Symbol")
self.addGlobal("Symbol", self.SymbolClass)
NilClass = self.addGlobal("Undefined", spy.SpyClass(self, "Undefined"))
self.nilObject.cls = NilClass
self.addGlobal("nil", self.nilObject)
ObjectClass = self.addGlobal("Object", spy.SpyClass(self, "Object"))
MetaObjectClass = self.addGlobal("MetaObject", spy.SpyClass(self, "MetaObject"))
ObjectClass.parent = self.nilObject
ClassClass = self.addGlobal("Class", spy.SpyClass(self, "Class", ObjectClass))
MetaClassClass = self.addGlobal("MetaClass", spy.SpyClass(self, "MetaClass"))
MetaClassClass.cls = ClassClass
self.addGlobal("Block", spy.SpyClass(self, "Block"))
self.addGlobal("Method", spy.SpyClass(self, "Method"))
self.addGlobal("Char", spy.SpyClass(self, "Char"))
self.SmallIntClass = self.addGlobal("SmallInt", spy.SpyClass(self, "SmallInt"))
self.SmallIntClass.size = 6
self.addGlobal("Integer", spy.SpyClass(self, "Integer"))
TrueClass = self.addGlobal("True", spy.SpyClass(self, "True"))
self.trueObject = self.addGlobal("true", spy.SpyObject(self, TrueClass))
FalseClass = self.addGlobal("False", spy.SpyClass(self, "False"))
self.falseObject = self.addGlobal("false", spy.SpyObject(self, FalseClass))
self.addGlobal("Array", spy.SpyClass(self, "Array"))
self.addGlobal("ByteArray", spy.SpyClass(self, "ByteArray"))
self.addGlobal("OrderedArray", spy.SpyClass(self, "OrderedArray"))
self.addGlobal("String", spy.SpyClass(self, "String"))
self.addGlobal("Dictionary", spy.SpyClass(self, "Dictionary"))
self.globalValues = spy.SpyDictionary(self)
self.addGlobal("mainClass", NilClass)
self.haveGlobals = True
self.addGlobal("MetaObject", MetaObjectClass)
def fileOut(self, basedir):
for k in self.globalValues.pdict:
v = self.globalValues.pdict[k]
v.fileOut(basedir)
def save(self, filename, infofile=None):
f = file(filename, "wb")
img = Image(self.globalValues, self.symbols, self.date)
pickle.dump(img, f, 2)
size = f.tell()
f.close()
if infofile:
f = file(infofile, "wb")
pickle.dump(img.date, f, 2)
f.close()
return size
def load(self, filename):
self.reset()
f = file(filename, "rb")
try:
img = FoxUnpickler.loads(f.read())
except Exception, e:
print "Fatal deserialisation error", e
if img.version < IMAGE_VERSION:
logging.warn("Older image version, expect breakage")
if img.version > IMAGE_VERSION:
logging.warn("Newer image version, expect breakage")
if hasattr(img, "date"):
logging.info("Image creation time: %s" % img.date)
self.globalValues = img.globals
self.symbols = img.symbols
self.date = img.date
self.oldImage = (self.defaultDate > self.date)
if self.oldImage:
logging.warn("Image is older than default")
self.haveGlobals = True
for gn in self.globalValues.pdict:
self.addGlobal(gn, self.globalValues.pdict[gn])
self.nilObject = self.globalValues.get("nil")
self.trueObject = self.globalValues.get("true")
self.falseObject = self.globalValues.get("false")
f.close()
self.generateMessageTable()
def generateMessageTable(self):
self.messageTable = {}
visited = {}
for gn in self.globals:
cls = self.globals[gn]
if isinstance(cls, spy.SpyClass):
if cls.name not in visited:
visited[cls.name] = 1
for meth in cls.methods.pdict:
if meth in self.messageTable:
self.messageTable[meth] += 1
else:
self.messageTable[meth] = 1
def addMessage(self, msg):
if msg in self.messageTable:
self.messageTable[msg] += 1
else:
self.messageTable[msg] = 1
def removeMessage(self, msg):
if self.messageTable[msg] > 1:
self.messageTable[msg] -= 1
else:
del self.messageTable[msg]
def getMainClass(self):
mainClass = None
for g in self.globals:
glb = self.globals[g]
if isinstance(glb, spy.SpyClass):
if glb.methods.has("main"):
mainClass = glb
break
return mainClass
def readyForSave(self):
for g in self.globals:
self.globalValues.add(g, self.globals[g])
mainClass = self.nilObject
for g in self.globals:
glb = self.globals[g]
if isinstance(glb, spy.SpyClass):
if glb.methods.has("main"):
mainClass = glb
break
self.globalValues.add("mainClass", mainClass)
bootClass = self.globalValues.get("nil").cls
bootClass.methods.get("boot").literals[0] = mainClass
return mainClass != self.nilObject
def getGlobalValues(self):
gusage = {}
for g in self.globals:
gusage[g] = Dependancy(g)
# create core dependancy list
core = Dependancy("!CORE", map(lambda x: gusage[x],CORE_DEPENDANCIES))
# iterate through globals populating dependancy tree
for g in self.globals:
glob = self.globals[g]
if g[:4] != "Meta" and isinstance(glob, spy.SpyClass):
thisdep = gusage[g]
# add meta class dependancy
if "Meta"+g in gusage:
thisdep.dependsOn(gusage["Meta"+g])
# add superclass dependancy
if isinstance(glob.parent, spy.SpyClass) and glob.parent.name in gusage:
thisdep.dependsOn(gusage[glob.parent.name])
# add method literal dependancies
for meth in glob.methods.pdict.values():
clslits = [l for l in meth.literals if isinstance(l, spy.SpyClass)]
for c in clslits:
thisdep.dependsOn(gusage[c.name])
# traverse unused class dependancies
unused = []
for u in [g for g in gusage if gusage[g].countDependedOnBy()==0]:
expandUnused(gusage, u, None, unused, [])
# create globals array skipping meta- and unused classes
glbs = spy.SpyDictionary(self)
for g in self.globals:
if g[:4] != "Meta" and g not in unused:
glbs.add(g, self.globals[g])
return glbs
def expandUnused(gusage, name, parent, unused, visited):
if name in visited:
return
visited.append(name)
u = gusage[name]
if (u.countDependedOnBy()==1 and u._isDependedOnBy[0].value==parent) or (not parent):
unused.append(name)
else:
return
for dep in u._dependsOn:
expandUnused(gusage, dep.value, name, unused, visited)
class Dependancy:
def __init__(self, value, deps=[]):
self.value = value
self._dependsOn = []
self._isDependedOnBy = []
for dep in deps:
self.dependsOn(dep)
def dependsOn(self, dep):
if dep not in self._dependsOn:
self._dependsOn.append(dep)
dep.isDependedOnBy(self)
def isDependedOnBy(self, dep):
if dep not in self._isDependedOnBy:
self._isDependedOnBy.append(dep)
def countDependsOn(self):
return len(self._dependsOn)
def countDependedOnBy(self):
return len(self._isDependedOnBy)
def __repr__(self):
return "<dep '%s' [%d/%d]>" % (self.value, len(self._dependsOn), len(self._isDependedOnBy))
| Python |
# vim:ts=4:sw=4:noet:
""" Control Flow Graph """
import logging
import ir
cfgcount = 1
class CFGBasicBlock:
def __init__(self,name=""):
global cfgcount
self.statements = []
self.prevs = []
self.nexts = []
self.references = []
self.name = "%d_%s" % (cfgcount, name)
cfgcount += 1
def addStatement(self, st):
self.statements.append(st)
def addNext(self, n):
n.addPrev(self)
self.nexts.append(n)
if len(self.nexts)>2:
raise Exception("%s has %d nexts: %s" % (self.name, len(self.nexts), self.nexts))
def removeNexts(self):
for n in self.nexts:
n.removePrev(self)
self.nexts = []
def removePrev(self, p):
self.prevs.pop(self.prevs.index(p))
def addPrev(self, p):
self.prevs.append(p)
def addReference(self, r):
self.references.append(r)
def isEntry(self):
return len(self.prevs)==0
def isExit(self):
return len(self.nexts)==0
def cleanup(self, visited=[]):
if self.name in visited:
return
visited.append(self.name)
eraseNexts = False
# add extra jumps if needed (for connector bbs)
if not self.isExit():
if (len(self.statements)>0):
last = self.statements[-1]
if isinstance(last, ir.IRReturn):
eraseNexts = True
elif not last.isJump():
if len(self.nexts)!=1:
raise Exception("invalid num lens: %s" % self)
self.addStatement(CFGJump(self.nexts[0]))
else:
self.addStatement(CFGJump(self.nexts[0]))
# merge connector bbs where possible
if len(self.nexts)==1:
if (len(self.statements)==0):
raise Exception("problem with num statements in bb %s" % self)
if (len(self.statements)==1) and isinstance(self.statements[0],CFGJump):
target = self.statements[0].target
ok = True
for p in self.prevs:
if len(p.nexts)>1:
ok = False
break
if ok:
for p in self.prevs:
p.nexts = []
p.addNext(target)
for r in self.references:
r.updateRef(self, target)
# clean nexts
for n in self.nexts:
n.cleanup(visited)
# erase next links if this should be an exit block
if eraseNexts:
self.removeNexts()
def cg(self, codegen, visited=[], stopat=[]):
if self.name in stopat:
return
if self.name in visited:
return
visited.append(self.name)
codegen.label(self.name)
for st in self.statements:
st.cg(codegen)
if (not self.isExit()) and (len(self.statements)>0):
last = self.statements[-1]
last.genJump(codegen, visited, stopat)
else:
for n in self.nexts:
n.cg(codegen, visited, stopat)
def dorepr(self, visited):
if self.name in visited:
return ""
visited.append(self.name)
info = ""
if self.isEntry(): info += "entry "
if self.isExit(): info += "exit "
ret = "(bb %s %s\n" % (self.name, info)
for s in self.statements:
ret += " %s\n" % s
ret += " (next %s)\n" % map(lambda x: x.name, self.nexts)
ret += ")\n"
for n in self.nexts:
ret += n.dorepr(visited)
return ret
def __repr__(self):
return self.dorepr([])[:-1]
class CFGIf:
def __init__(self, tb, fb, eb, iftrue=True):
self.tb = tb
self.fb = fb
self.eb = eb
self.eb.addReference(self)
self.iftrue = iftrue
def cg(self, codegen):
pass
def updateRef(self, old, new):
self.eb = new
self.eb.addReference(self)
def isJump(self):
return True
def genJump(self, codegen, visited, stop):
nstop = [self.eb.name]
for s in stop: nstop.append(s)
if self.iftrue:
codegen.branchIfTrue(self.tb.name)
self.fb.cg(codegen, visited, stopat=nstop)
self.tb.cg(codegen, visited, stopat=stop)
else:
codegen.branchIfFalse(self.fb.name)
self.tb.cg(codegen, visited, stopat=nstop)
self.fb.cg(codegen, visited, stopat=stop)
if self.eb.name not in visited and len(self.eb.prevs)>0:
self.eb.cg(codegen, visited, stopat=stop)
def __repr__(self):
return "(cfgif %d)" % self.iftrue
class CFGJump:
def __init__(self, target):
self.target = target
self.target.addReference(self)
def cg(self, codegen):
pass
def updateRef(self, old, new):
self.target = new
self.target.addReference(self)
def isJump(self):
return True
def genJump(self, codegen, visited, stop):
if (self.target.name in visited) or (self.target.name in stop):
codegen.branch(self.target.name)
self.target.cg(codegen, visited, stop)
def __repr__(self):
return "(cfgjump)"
class CFGEndStatement:
def cg(self, codegen):
codegen.pop()
def isJump(self):
return False
def __repr__(self):
return "(cfgendstmt)"
class CFGEndBlock:
def cg(self, codegen):
codegen.returnStack()
def isJump(self):
return False
def __repr__(self):
return "(cfgendblk)"
class CFGEndBody:
def cg(self, codegen):
codegen.returnSelf()
def isJump(self):
return False
def __repr__(self):
return "(cfgendbody)"
class CFGStartBlock:
def __init__(self, tempStart, blkbb, endbb):
self.tempStart = tempStart
self.blkbb = blkbb
self.endbb = endbb
def isJump(self):
return True
def genJump(self, cgen, visited, stop):
cgen.pushBlock(self.tempStart, self.endbb.name)
self.blkbb.cg(cgen, visited, stop)
self.endbb.cg(cgen, visited, stop)
def cg(self, cgen):
pass
def __repr__(self):
return "(cfgstartblk)"
| Python |
# vim:ts=4:sw=4:noet:
""" Bytecode disassembler """
from codegen import Bytecodes
from cmg import binmsgs
extraBytes = [
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # 0 push instance
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # 1 push temporary
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, # 2 push literal
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # 3 push constant
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, # 4 pushb
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, # 5 prim
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # 6 pop instance/temporary
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # 7 store instance
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # 8 store temporary
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2, # A send
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, # B send0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, # C send1
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, # 9 send2
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # D sendu
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, # E sendb
0,0,0,0,0,0,1,1,1,0,0,2,0,0,0,0, # F special
]
opNames = [ "pushi", "pusht", "pushl", "pushc", "pushb", "prim", "popit", "stori",
"stort", "send", "send0", "send1", "send2", "sendu", "sendb", "special" ]
def getJumps(bytecodes):
jumps = []
ptr=0
while ptr<len(bytecodes):
bc = bytecodes[ptr]
low = bc & 0x0F
high = bc >> 4
ptr += 1
if high == Bytecodes.DoSpecial:
if low in range(6,9):
x = bytecodes[ptr]
jumps.append((x, (ptr-1, "label%d" % len(jumps))))
ptr += extraBytes[bc]
return jumps
def disassembleInstruction(bytecodes, literals, pt, inblock, jumps):
ptr = pt
bc = bytecodes[ptr]
low = bc & 0x0F
high = bc >> 4
ret = "%03X: %02X " % (ptr, bc)
ptr += 1
extras = []
for i in range(extraBytes[bc]):
ebc = bytecodes[ptr]
ptr +=1
extras.append(ebc)
ret += "%02X " % ebc
ret = ret.ljust(12)
if len(inblock)>0:
if ptr>inblock[-1]:
inblock.pop()
ret += " "*len(inblock)
opname = opNames[high]
if high in [Bytecodes.PushInstance,
Bytecodes.PopInstTemp,
Bytecodes.PushTemporary,
Bytecodes.AssignInstance,
Bytecodes.AssignTemporary]:
ret += "%s %d" % (opname, low)
elif high in [Bytecodes.PushLiteral,
Bytecodes.SendMessage0,
Bytecodes.SendMessage1,
Bytecodes.SendMessage2]:
if low == 15:
low = extras[0]
ret += "%s %s" % (opname, literals[low])
elif high == Bytecodes.SendMessage:
if low == 15:
low = extras[0]
nargs = extras[-1]
ret += "%s %d, %s" % (opname, nargs, literals[low])
elif high == Bytecodes.PushConstant:
if low==13:
low = "nil"
elif low==14:
low = "true"
elif low==15:
low = "false"
elif low==11 or low==12:
low = 10-low
ret += "pushc %s" % low
elif high == Bytecodes.SendUnary:
unmsg = ["#isNil","#notNil"]
ret += "sendu %s" % unmsg[low]
elif high == Bytecodes.SendBinary:
ret += "sendb #%s" % binmsgs[low]
elif high == Bytecodes.PushBlock:
ret += "pushb %d, %d" % (low, extras[0])
inblock.append(extras[0])
elif high == Bytecodes.DoPrimitive:
ret += "prim %d" % extras[0]
elif high == Bytecodes.DoSpecial:
if low == 1:
ret += "retsf"
elif low == 2:
ret += "retst"
elif low == 3:
ret += "retbk"
elif low == 4:
ret += "dup"
elif low == 5:
ret += "pop"
elif low == 6:
x = extras[0]
if x in jumps:
ret += "brnch %s" % (jumps[x][1])
else:
ret += "brnch 0x%03X" % (x)
elif low == 7:
x = extras[0]
if x in jumps:
ret += "brnct %s" % (jumps[x][1])
else:
ret += "brnct 0x%03X" % (x)
elif low == 8:
x = extras[0]
if x in jumps:
ret += "brncf %s" % (jumps[x][1])
else:
ret += "brncf 0x%03X" % (x)
elif low == 11:
ret += "sends %s" %literals[extras[0]]
elif low == 12:
ret += "pushst"
elif low == 13:
ret += "popst "
else:
ret += "!unknown special",low
else:
ret += "! unknown %d %d %d" % (bc, low, high)
return ptr, inblock, ret
def disassembleMethod(bytecodes, literals):
ptr = 0
ret = ""
literals = map(lambda x: x.asString(), literals)
instCount = 0
jdict = dict(getJumps(bytecodes))
inblock = []
while ptr < len(bytecodes):
if ptr in jdict:
ret += "%s:\n" % jdict[ptr][1]
ptr, inblock, inststr = disassembleInstruction(bytecodes, literals, ptr, inblock, jdict)
ret += " %s\n" % inststr
instCount += 1
return ret[:-1], instCount
| Python |
# vim:ts=4:sw=4:noet:
""" Parser """
import ir
import primtable as primtable
from lexer import Lexer, Token
class Parser:
def __init__(self, mem, status):
self.status = status
self.mainClass = None
self.prims = primtable.PrimTable()
def acceptType(self, type):
if type!=self.lex.token.type:
self.status.error("Expected %s, got %s" % (
Token.prettyTypenames[type],
Token.prettyTypenames[self.lex.token.type]),
self.lex.popLine())
t = self.lex.token
self.lex.nextLex()
return t
def accept(self, s, t=None):
if s!=self.lex.token.value:
self.status.error("Expected '%s', got '%s'" % (
s, self.lex.token.value),
self.lex.popLine())
if t and t!=self.lex.token.type:
self.status.error("Expected %s, got %s" % (
Token.prettyTypenames[t],
Token.prettyTypenames[self.lex.token.type]),
self.lex.popLine())
tok = self.lex.token
self.lex.nextLex()
return tok
def bootMethod(self, mainClassName):
boottext = "boot [ (mainClass new) main. <halt> ]"
self.lex = Lexer(self.status, boottext)
self.lex.nextLex()
self.ivars = []
m = self.parseMethod(None)
return m
def parseFile(self, filename):
f = file(filename,"rb")
source = f.read()
f.close()
return self.parseFileFromSource(source)
def parseFileFromSource(self, source):
self.lex = Lexer(self.status, source)
self.lex.nextLex()
classes = []
while self.lex.token and self.lex.token.type==Token.ID:
classes.append(self.parseClass())
return classes
def parseVars(self):
vars = []
if self.lex.token.value=="|":
self.accept("|", Token.BIN)
while self.lex.token.value!="|":
vars.append(self.acceptType(Token.ID).value)
self.accept("|", Token.BIN)
return vars
def parsePragma(self):
self.accept("<", Token.BIN)
k = self.acceptType(Token.ID).value[:-1]
v = self.acceptType(Token.STR).value
self.accept(">", Token.BIN)
return k,v
def parsePragmas(self):
pragmas = {}
while self.lex.token.value=="<":
self.lex.saveState()
self.lex.nextLex()
if self.lex.token.value!="category:":
self.lex.backtrack()
break
self.lex.backtrack()
k,v = self.parsePragma()
pragmas[k] = v
return pragmas
def parseClass(self):
lnumStart = self.lex.lineNum
self.lex.pushLine()
docs = self.lex.lastComment
if len(docs) and docs[0]!="!":
docs=""
else:
docs = docs[2:]
self.lex.lastComment = ""
supername = self.acceptType(Token.ID)
self.accept("subclass:")
name = self.acceptType(Token.ID)
self.accept("[", Token.BIN)
tivars = self.parseVars()
pragmas = self.parsePragmas()
meths = []
cls = ir.IRClass(
0,
name.value,
supername.value,
tivars,
meths,
docs,
pragmas)
while self.lex.token.type!=Token.BIN or self.lex.token.value!="]":
meths.append(self.parseMethod(cls))
self.lex.lastComment = ""
self.accept("]", Token.BIN)
cls.line = self.lex.popLine()
return cls
def __parseMethod(self, doCleanSource=True):
self.lex.pushLine()
self.temps = []
self.maxTemps = 0
docs = self.lex.lastComment
if len(docs) and docs[0]!="!":
docs=""
else:
docs = docs[2:]
name = self.parseMethodName()
self.lex.idxofs = self.lex.index+1
self.accept("[", Token.BIN)
tokStart = self.lex.token
for t in self.parseVars():
self.addTempName(t)
body = self.parseBody()
tokEnd = self.lex.oldtoken
self.lex.lastComment = ""
self.accept("]", Token.BIN)
source = self.lex.getText(tokStart,tokEnd)
if doCleanSource:
source = self.cleanSource(source)
return ir.IRMethod(
self.lex.popLine(),
name,
self.args,
self.temps,
self.maxTemps,
body,
source,
docs)
def parseMethodFromSource(self, source):
self.lex = Lexer(self.status, source)
self.lex.nextLex()
irmeth = self.__parseMethod(False)
self.acceptType(Token.EOF)
return irmeth
def parseMethod(self, cls):
irmeth = self.__parseMethod()
if irmeth.name=="main":
self.mainClass = cls
return irmeth
def cleanSource(self, src):
doDetab = True
numtabs = 100
for sl in src.split("\n")[1:]:
mtl = 100
if len(sl)>0:
for i in range(len(sl)):
if sl[i]!="\t":
break
mtl = i
if mtl<numtabs:
numtabs = mtl
nsrc = ""
if numtabs!=100 and numtabs>0:
print "detabbing:\n", src
nsrc = src.split("\n")[0]+"\n"
for sl in src.split("\n")[1:]:
nsrc += "%s\n" % sl[numtabs:]
src = nsrc[:-1]
print src
return src
def parseMethodName(self):
self.args = ["self"]
if self.lex.token.isName():
return self.acceptType(Token.ID).value
if self.lex.token.isBinary():
name = self.accept(self.lex.token.value).value
self.args.append(self.acceptType(Token.ID).value)
return name
if self.lex.token.isKeyword():
name = ""
while self.lex.token.isKeyword():
key = self.acceptType(Token.ID)
name += key.value
self.args.append(self.acceptType(Token.ID).value)
return name
self.status.error("Invalid method name")
def parseBody(self):
lnum = self.lex.lineNum
self.lex.pushLine()
sl = self.parseStatementList()
return ir.IRBody(self.lex.popLine(), sl)
def parseBlock(self):
lnum = self.lex.lineNum
self.lex.pushLine()
self.lex.nextLex()
btemps = []
if self.lex.token.value[0]==":":
btemps = self.parseBlockTemporaries()
stmts = self.parseStatementList()
self.accept("]", Token.BIN)
return ir.IRBlock(self.lex.popLine(), btemps, stmts)
def addTempName(self, name):
if ((name in self.args) or (name in self.temps)):
self.status.error("Name redefined: %s" % (name), self.lex.popLine())
self.temps.append(name)
self.maxTemps += 1
def parseBlockTemporaries(self):
bts = []
while self.lex.token.value[0]==":":
self.lex.nextLex()
if self.lex.token.isName():
self.maxTemps += 1 # FIXME: used to add to self.temps, what does this change?
bts.append(self.lex.token.value)
else:
self.status.error("Invalid block arg: %s" % (
self.lex.token.value),
self.lex.popLine())
self.lex.nextLex()
self.accept("|", Token.BIN)
return bts
def parseStatementList(self):
list = []
while self.lex.token.value!="]":
list.append(self.parseStatement())
if self.lex.token.value==".":
self.accept(".")
return list
def parseStatement(self):
if self.lex.token.value == "<":
return self.parsePrimitive()
elif self.lex.token.value=="^":
self.lex.pushLine()
self.accept("^", Token.BIN)
lnum = self.lex.lineNum
exp = self.parseExpression()
return ir.IRReturn(self.lex.popLine(), exp)
else:
return self.parseExpression()
def parseExpression(self):
if not self.lex.token.isName():
return self.parseCascade(self.parseTerm())
node = self.nameNode()
if self.lex.token.value == ":=":
self.lex.pushLine()
self.accept(self.lex.token.value, Token.BIN)
lnum = self.lex.lineNum
exp = self.parseExpression()
return ir.IRAssign(self.lex.popLine(), node, exp)
return self.parseCascade(node)
def parseCascade(self, base):
node = self.parseKeywordContinuation(base)
if self.lex.token.value == ";" and isinstance(node, ir.IRMessage):
lnum = self.lex.lineNum
self.lex.pushLine()
recv = node.recv
node.recv = None
list = [node]
while self.lex.token.value == ";":
self.lex.nextLex()
list.append(self.parseKeywordContinuation(None))
node = ir.IRCascade(self.lex.popLine(), recv)
node.list = list
return node
def parseKeywordContinuation(self, base):
recv = self.parseBinaryContinuation(base)
if not self.lex.token.isKeyword():
return recv
name = ""
args = []
lnum = self.lex.lineNum
self.lex.pushLine()
while self.lex.token.isKeyword():
name = name + self.lex.token.value
self.lex.nextLex()
args.append(self.parseBinaryContinuation(self.parseTerm()))
return ir.IRMessage(self.lex.popLine(), recv, name, args)
def parseBinaryContinuation(self, base):
recv = self.parseUnaryContinuation(base)
while self.lex.token.isBinary():
self.lex.pushLine()
lnum = self.lex.lineNum
name = self.lex.token.value
self.lex.nextLex()
arg = self.parseUnaryContinuation(self.parseTerm())
recv = ir.IRMessage(self.lex.popLine(), recv, name, [arg])
return recv
def parseUnaryContinuation(self, base):
recv = base
while self.lex.token.isName():
self.lex.pushLine()
lnum = self.lex.lineNum
name = self.lex.token.value
self.lex.nextLex()
recv = ir.IRMessage(self.lex.popLine(), recv, name, [])
return recv
def parseTerm(self):
if self.lex.token.value == None:
self.status.error("Unexpected end of input",
self.lex.popLine())
elif self.lex.token.type == Token.BIN and self.lex.token.value == "(":
self.lex.nextLex()
node = self.parseExpression()
self.accept(")", Token.BIN)
return node
elif self.lex.token.type == Token.BIN and self.lex.token.value == "[":
return self.parseBlock()
elif self.lex.token.isName():
return self.nameNode()
else:
return self.parseLiteral()
def parseLiteral(self):
self.lex.pushLine()
if len(self.lex.token.value)>0 and self.lex.token.value[0] == "$":
t = self.lex.currentChar()
start = self.lex.token.index
self.lex.nextChar()
self.lex.nextLex()
return ir.IRChar(self.lex.popLine(), t)
elif ((self.lex.token.type == Token.INT and
len(self.lex.token.value)>0 and
self.lex.token.value[0].isdigit()) or
(self.lex.token.type == Token.BIN and self.lex.token.value == "-")):
return self.parseInteger()
elif self.lex.token.type == Token.STR:
v = self.lex.token.value
self.lex.nextLex()
return ir.IRString(self.lex.popLine(), v)
elif self.lex.token.type == Token.SYM:
v = self.lex.token.value
self.lex.nextLex()
return ir.IRSymbol(self.lex.popLine(), v)
elif self.lex.token.value == "#(":
arr = []
self.accept("#(", Token.BIN)
while self.lex.token.value!=")":
arr.append(self.parseLiteral())
self.accept(")", Token.BIN)
return ir.IRArray(self.lex.popLine(), arr)
else:
v = self.lex.token.value
self.lex.nextLex()
self.status.error("Invalid literal: %s" % (v),
self.lex.popLine())
def parseInteger(self):
neg = False
if self.lex.token.type == Token.BIN and self.lex.token.value == "-":
neg = True
self.lex.nextLex()
iv = self.lex.token.value
self.lex.nextLex()
if "r" in iv:
if neg:
self.status.error("Negative arbitrary based integer invalid", self.lex.popLine())
base, val = iv.split("r")
v = int(val, int(base))
if v>(2**32 - 1):
self.status.error("Integer overflow", self.lex.popLine())
else:
for c in iv:
if not c.isdigit():
self.status.error("Expected number literal", self.lex.popLine())
v = int(iv)
if neg:
v = -v
return ir.IRInteger(self.lex.popLine(), v)
def parsePrimitive(self):
lnum = self.lex.lineNum
self.lex.pushLine()
start = self.lex.token.index
self.lex.nextLex()
name = self.lex.token.value
if not self.lex.token.isName():
self.status.error("error parsing primitive", self.lex.popLine())
self.lex.nextLex()
num = self.prims.lookupName(name)
if num == None:
self.status.error("Invalid primitive '%s'" % (name), self.lex.popLine())
args = []
while self.lex.token.value!=">":
args.append(self.parseTerm())
size = self.lex.token.index - start + 1
self.lex.nextLex()
return ir.IRPrimitive(self.lex.popLine(), num, args)
def nameNode(self):
self.lex.pushLine()
v = self.lex.token.value
self.lex.nextLex()
return ir.IRName(self.lex.popLine(), v)
| Python |
# vim:ts=4:sw=4:noet:
""" Primitive method table """
primitives = {
# Object
"objectIdentity" : 1,
"objectClass" : 2,
"objectSize" : 3,
"objectNew" : 4,
# Array
"arrayAt" : 5,
"arrayAtPut" : 6,
"bytearrayAlloc" : 7,
# String
"stringAt" : 8,
"stringAtPut" : 9,
"stringClone" : 10,
"stringReplace" : 11,
"stringPrint" : 12,
# Character
"charPrint" : 13,
"charRead" : 14,
# Block
"blockValue" : 15,
"contextExecute" : 16,
# Smallint
"smallintRandom" : 31,
"smallintAdd" : 32,
"smallintDiv" : 33,
"smallintMod" : 34,
"smallintLess" : 35,
"smallintEqual" : 36,
"smallintMult" : 37,
"smallintSub" : 38,
"smallintAlloc" : 39,
"smallintFit" : 40,
"smallintBitOr" : 41,
"smallintBitAnd" : 42,
"smallintShift" : 43,
"smallintTrunk" : 44,
# Integer
"integerDiv" : 45,
"integerMod" : 46,
"integerAdd" : 47,
"integerMult" : 48,
"integerSub" : 49,
"integerLess" : 50,
"integerEqual" : 51,
# System
"methodFlush" : 96,
"halt" : 97,
"error" : 98,
"yieldUntil" : 99,
# Hardware
"sleepMS" : 128,
"timeStartupMS" : 129,
"motorVelocity" : 130,
"motorBrake" : 131,
"analogRead" : 132,
"digitalRead" : 133,
"setPenState" : 134,
"setPenColour" : 135,
"memWrite" : 136,
"memRead" : 137,
"setPosition" : 138,
"getPosition" : 139,
"getEncoder" : 140,
"motionCommand" : 141,
"setPenStyle" : 142,
# Music
"musicStop" : 160,
"musicPlayNote" : 161,
"musicPlayPatch" : 162,
}
class PrimTable:
def __init__(self):
pass
def lookupName(self, name):
if name in primitives:
return primitives[name]
else:
return None
def cifyName(self, name):
new = "PRIM_"
cp = "a"
for c in name:
if c.isupper() and cp.islower():
new += "_"+c
else:
new += c.upper()
cp = c
return new
def writeHFile(self, fn):
nums = {}
for name in primitives:
nums[primitives[name]] = name
numkeys = nums.keys()
numkeys.sort()
f = file(fn,"wb")
f.write("#ifndef _PRIMDEFS_H_\n")
f.write("#define _PRIMDEFS_H_\n\n")
for num in numkeys:
name = self.cifyName(nums[num])
f.write("#define %s%s%d\n" % (name," "*(25-len(name)),num))
f.write("\n#endif\n")
if __name__=="__main__":
p = PrimTable()
p.writeHFile("primdefs.h")
| Python |
# vim:ts=4:sw=4:noet:
"""
Smalltalk-Python (Spy) Objects. This is the main representation of
Smalltalk objects in the environment.
SpyObjects are the core representation of smalltalk objects in the environment. The image files are serialised (pickled) versions of SpyObjects. A SpyObject can also emit the CMG version of itself (the binary format used by CVM).
"""
import logging
import mem
STATE_COMPILED = 0
STATE_UNCOMPILED = 1
STATE_ERROR = 2
################################################################################
class SpyObject:
""" Base Spy class """
def __init__(self, mem, cls, size=0):
self.mem = mem
self.cls = cls
self.size = size
def writeCMG(self, cmg):
if self in cmg.objhash:
return cmg.objhash[self]<<2
r = self._writeCMG(cmg)
return r
def __getstate__(self):
odict = self.__dict__.copy()
del odict['mem']
return odict
def __setstate__(self, dict):
self.__dict__.update(dict)
self.mem = mem.Memory._instance
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
for i in range(self.size):
cmg.img[mobj+2+i] = self.mem.nilObject.writeCMG(cmg)
return mobj<<2
def fileOut(self, rootdir):
pass
def asString(self):
return self.__repr__()
################################################################################
class SpyBinObject(SpyObject):
""" Base Binary Object Spy Class """
def __init__(self, mem, cls, size=0):
SpyObject.__init__(self, mem, cls, size)
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size, True)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
data = []
for d in self.data:
data.append(d)
if len(data)%2 == 1:
data.append(0xFF)
for i in range(len(data)/2):
cmg.img[mobj+2+i] = (data[i*2 +1]<<8) + data[i*2]
return mobj<<2
def __len__(self):
return len(self.data)
def __repr__(self):
return "<SpyByteArray %d bytes>" % len(self.data)
################################################################################
class SpyClass(SpyObject):
""" Spy Class """
def __init__(self, mem, name, parent=None):
SpyObject.__init__(self, mem, None, 4)
self.name = name
self.parent = parent
self.methods = None
self.instanceSize = 0
self.instanceNames = []
self.docs = ""
self.pragmas = {}
if parent:
self.instanceSize = parent.instanceSize
def newClassInit(self):
self.methods = SpyDictionary(self.mem)
self.cls = SpyClass(self.mem, "Meta"+self.name, self.parent.cls)
self.cls.methods = SpyDictionary(self.mem)
self.cls.cls = self.mem.getGlobal("Class")
self.cls.addPragma("category", "")
self.addPragma("category","")
def addPragma(self, k,v):
self.pragmas[k] = v
def getPragma(self,k):
if k in self.pragmas:
return self.pragmas[k]
return ""
def inLibrary(self):
return self.getPragma("category")[:7]=="Library"
def getAllIvars(self, withClasses=False):
ivars = []
curcls = self
while curcls:
for i,iv in enumerate(curcls.instanceNames):
if withClasses:
ivars.insert(i,(curcls.name,iv))
else:
ivars.insert(i,iv)
if curcls.parent != self.mem.nilObject:
curcls = curcls.parent
else:
break
return ivars
def addIvar(self, ivar):
self.instanceNames.append(ivar)
#self.instanceSize += 1
logging.warn("addIvar: add ivar to child classes")
def removeIvar(self, ivar):
logging.info("removing %s from %s" % (ivar, self.instanceNames))
self.instanceNames.remove(ivar)
#self.instanceSize -= 1
logging.warn("removeIvar: recompile all methods")
def hasMethod(self, name):
return self.methods.has(name)
def removeMethod(self, name):
self.methods.remove(name)
def addMethod(self, name, meth):
self.methods.add(name, meth)
def getMethod(self, name, inherit=True):
if self.hasMethod(name):
return self.methods.get(name)
elif inherit and (self.parent != self.mem.nilObject):
return self.parent.getMethod(name)
else:
return None
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
cmg.img[mobj+2] = self.mem.newSymbol(self.name).writeCMG(cmg) # 0 - name
cmg.img[mobj+3] = self.parent.writeCMG(cmg) # 1 - parent
cmg.img[mobj+4] = self.methods.writeCMG(cmg) # 2 - methods
cmg.img[mobj+5] = cmg.newInteger(len(self.getAllIvars())) # 3 - instance size
#if self.instanceSize != len(self.getAllIvars()):
# raise Exception("bad ivarsize in %s" % self.name)
for i in range(self.size-4):
cmg.img[mobj+6+i] = self.mem.nilObject.writeCMG(cmg)
return mobj<<2
def fileOutClass(self, rootdir, f):
name = self.name
metaname = self.cls.name
metasupername = self.cls.parent.name
if self.parent == self.mem.nilObject:
supername = "nil"
else:
supername = self.parent.name
if "docs" in dir(self):
print >> f, """\"! %s\"""" % self.docs.replace("\"", "\\\"")
print >> f, "%s subclass: %s [" % (supername, name)
if len(self.instanceNames)>0:
print >> f, "|",
for v in self.instanceNames:
print >> f, v,
print >> f, "|"
for p in self.pragmas:
print >> f, "<%s: '%s'>" % (p, self.pragmas[p])
mnames = self.methods.pdict.keys()
mnames.sort()
for mn in mnames:
self.methods.pdict[mn].fileOut(f)
print >> f, "]"
print >> f, ""
def fileOut(self, rootdir):
if self.name[:4] == "Meta":
return
#print "--- fileout",rootdir
f = file(rootdir+"/"+self.name+".st","wb")
self.fileOutClass(rootdir, f)
self.cls.fileOutClass(rootdir, f)
f.close()
def __repr__(self):
return "<SpyClass %s 0x%X>" % (self.name, id(self))
def asString(self):
return "<Class %s>" % self.name
################################################################################
class SpyArray(SpyObject):
""" Spy Array """
def __init__(self, mem, init):
SpyObject.__init__(self, mem, mem.getGlobal("Array"), len(init))
self.parr = init
def add(self, n, v):
self.parr[n] = v
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
for i,d in enumerate(self.parr):
cmg.img[mobj+2+i] = d.writeCMG(cmg)
return mobj<<2
def __repr__(self):
return "<SpyArray %d items>" % len(self.parr)
def asString(self):
r = "#("
for i in self.parr:
r+=" "+i.asString()
if len(r)>16:
r+=" ..."
break
r += " )"
return r
################################################################################
class SpyOrderedArray(SpyObject):
""" Spy OrderedArray """
def __init__(self, mem, init):
SpyObject.__init__(self, mem, mem.getGlobal("OrderedArray"), len(init))
self.parr = init
def add(self, n, v):
self.parr[n] = v
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
for i,d in enumerate(self.parr):
cmg.img[mobj+2+i] = d.writeCMG(cmg)
return mobj<<2
def __repr__(self):
return "<SpyOrderedArray %d items>" % len(self.parr)
################################################################################
class SpyByteArray(SpyBinObject):
""" Spy ByteArray """
def __init__(self, mem, data):
SpyBinObject.__init__(self, mem, mem.getGlobal("ByteArray"), len(data))
self.data = data
################################################################################
class SpyDictionary(SpyObject):
""" Spy Dictionary """
def __init__(self, mem):
SpyObject.__init__(self, mem, mem.getGlobal("Dictionary"), 2)
self.pdict = {}
def remove(self, n):
del self.pdict[n]
def add(self, n, v):
self.pdict[n] = v
def get(self, n):
return self.pdict[n]
def has(self, n):
return n in self.pdict
def __len__(self):
return len(self.pdict)
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
keys = self.pdict.keys()
keys.sort()
vals = []
for k in keys:
vals.append(self.pdict[k])
keys = map(lambda x: self.mem.newSymbol(x), keys)
cmg.img[mobj+2] = SpyOrderedArray(self.mem, keys).writeCMG(cmg)
cmg.img[mobj+3] = SpyArray(self.mem, vals).writeCMG(cmg)
return mobj<<2
def __repr__(self):
return "<SpyDictionary %d items>" % len(self.pdict.keys())
def asString(self):
return "<Dictionary>"
################################################################################
class SpyMethod(SpyObject):
""" Spy Method
A SpyMethod has dependants (methods which depend/call this method), and
reverse-dependants (methods which this method depends on/calls).
Dependant/Reverse-Dependant mappings are updated when a method compiled.
"""
def __init__(self, mem, name, incls, source):
SpyObject.__init__(self, mem, mem.getGlobal("Method"), 4)
self.name = name
self.incls = incls
self.source = source
self.sig = None
self.args = []
self.bclines = []
self.docs = ""
self.state = STATE_COMPILED
self.dependants = {}
self.revdependants = {}
def clearDependants(self):
""" Clear dependant map for this method """
self.dependants = {}
def clearRevDependants(self):
""" Clear reverse dependant map for this method """
self.revdependants = {}
def removeDependant(self, depcls, depmeth):
""" Remove a dependant """
dep = "%s>>%s" % (depcls.name, depmeth.name)
print "remove dep: %s" % dep
if dep not in self.dependants:
print "Warning: can't remove dep '%s' from %s" % (dep, self)
return
del self.dependants[dep]
def addDependant(self, depcls, depmeth):
""" Add a dependant (and update revdependant map of dependant) """
dep = "%s>>%s" % (depcls.name, depmeth.name)
revdep = "%s>>%s" % (self.name, self.incls.name)
if dep not in self.dependants:
self.dependants[dep] = (depcls, depmeth)
depmeth.revdependants[revdep] = (self.incls, self)
def getDependants(self):
""" Get dependants """
return self.dependants.values()
def lineFromBp(self, bc):
""" Get the source line number that maps to the specified bytecode """
i = 0
#print "lineFromBp in %s:0x%02X -" % (self.name, bc)
while (i<len(self.bclines)) and (bc>=self.bclines[i][0]):
i+= 1
return self.bclines[i-1][1]
def _writeCMG(self, cmg):
#print "writing method (%d): %s" % (self.used, self.name)
mobj = cmg.newObject(3+len(self.literals)) #self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
cmg.img[mobj+2] = self.mem.newSymbol(self.name).writeCMG(cmg) # 0 - name
cmg.img[mobj+3] = cmg.newInteger((self.maxStack<<6)|self.maxTemps) # 1 - tempsize
cmg.img[mobj+4] = SpyByteArray(self.mem, self.bytecodes).writeCMG(cmg) # 2 - bytecodes
for i,l in enumerate(self.literals):
cmg.img[mobj+5+i] = l.writeCMG(cmg)
return mobj<<2
def fileOut(self, f):
print >> f, """\"! %s\"""" % self.docs.replace("\"", "\\\"")
print >> f, "%s [" % self.sig
print >> f, "%s" % self.source,
print >> f, "]"
print >> f, ""
def __repr__(self):
return "<SpyMethod %s>" % self.name
################################################################################
class SpySymbol(SpyBinObject):
""" Spy Symbol """
def __init__(self, mem, name):
SpyBinObject.__init__(self, mem, mem.getGlobal("Symbol"), len(name))
self.name = name
self.data = []
for c in name:
self.data.append(ord(c))
def _writeCMG(self, cmg):
self.optr = SpyBinObject._writeCMG(self, cmg)
return self.optr
def asString(self):
return self.name
def __repr__(self):
return "<SpySymbol #%s>" % self.name
def asString(self):
return "#%s" % self.name
################################################################################
class SpyString(SpyBinObject):
""" Spy String """
def __init__(self, mem, value):
SpyBinObject.__init__(self, mem, mem.getGlobal("String"), len(value))
self.value = value
self.data = []
for c in value:
self.data.append(ord(c))
def __repr__(self):
return "<SpyString '%s'>" % self.value
def asString(self):
return "'%s'" % self.value
################################################################################
class SpyInteger(SpyBinObject):
""" Spy Integer """
def __init__(self, mem, value):
SpyBinObject.__init__(self, mem, mem.getGlobal("Integer"), 4)
self.value = value
self.data = []
self.data.append((value )&0xFF)
self.data.append((value>>8 )&0xFF)
self.data.append((value>>16)&0xFF)
self.data.append((value>>24)&0xFF)
def __repr__(self):
return "<SpyInteger %d>" % self.value
def __eq__(self, other):
if not isinstance(other,SpyInteger):
return False
return self.value==other.value
def __hash__(self):
return hash(self.value)
def asString(self):
return "%d" % self.value
################################################################################
class SpySmallInt(SpyObject):
""" Spy SmallInt """
def __init__(self, mem, value):
SpyObject.__init__(self, mem, mem.getGlobal("SmallInt"))
self.value = value
def _writeCMG(self, cmg):
return cmg.newInteger(self.value)
def __repr__(self):
return "<SpySmallInt %d>" % self.value
def __eq__(self, other):
if not isinstance(other,SpySmallInt):
return False
return self.value==other.value
def __hash__(self):
return hash(self.value)
def asString(self):
return "%d" % self.value
################################################################################
class SpyChar(SpyObject):
""" Spy Character """
def __init__(self, mem, value):
SpyObject.__init__(self, mem, mem.getGlobal("Char"), 1)
self.value = value
def _writeCMG(self, cmg):
mobj = cmg.newObject(self.size)
cmg.objhash[self] = mobj
cmg.img[mobj+1] = self.cls.writeCMG(cmg)
cmg.img[mobj+2] = cmg.newInteger(ord(self.value))
return mobj<<2
def asString(self):
return "$%s" % self.value
| Python |
# vim:ts=4:sw=4:noet:
""" Basic block optimiser base class """
import c.compiler.cfg
class BBVisitor:
def doMethod(self, meth):
self.visit(meth.body.bb)
def visit(self, bb, visited=[]):
if bb.name in visited:
return
visited.append(bb.name)
self.doBasicBlock(bb)
for n in bb.nexts:
self.visit(n, visited)
| Python |
# vim:ts=4:sw=4:noet:
""" IR optimisers """
import c.compiler.cfg
from irvisit import IRVisitor
import c.compiler.ir as ir
class OptInline(IRVisitor):
def __init__(self, compiler, mem, classes):
self.mem = mem
self.compiler = compiler
self.classes = {}
for c in classes:
self.classes[c.name] = c
def getIRMethod(self, clsname, methname):
return self.compiler.getIRForMethod(clsname, methname)
def doMethod(self, cls, meth):
#print "iropt:do method", cls, meth
self.clsname = cls
self.meth = meth
IRVisitor.doMethod(self, meth)
def doIRReturn(self, node):
r,v = self.doIRNode(node.value)
if r:
node.value = v
return (None, None)
def inlineCall(self, orig, new):
#print " original:", orig, orig.args
#print " new:", new
#print "check inline", orig.name
return (True, new)
def doIRMessage(self, node):
if node.recv:
if ((isinstance(node.recv, ir.IRName)) and
((node.recv.name=="self") or
(self.mem.getGlobal(node.recv.name)))):
if node.recv.name!="self":
spycls = self.mem.getGlobal("Meta"+node.recv.name)
else:
spycls = self.mem.getGlobal(self.clsname)
if not spycls:
return (None, None)
spymeth = spycls.getMethod(node.name)
if spymeth and spymeth.name != self.meth.name:
irmeth = self.getIRMethod(spymeth.incls.name, spymeth.name)
if irmeth and irmeth.canInline():
#print "possible inline of %s in %s>>%s" % (
# node.name, self.clsname, self.meth.name)
#print " - using method %s>>%s" % (spymeth.incls.name, spymeth.name)
code = irmeth.body.statements[0].value
depcls = self.mem.getGlobal(self.clsname)
depmeth = depcls.getMethod(self.meth.name)
spymeth.addDependant(depcls, depmeth)
return self.inlineCall(node, code)
else:
r, v = self.doIRNode(node.recv)
if r: node.recv = v
for i,a in enumerate(node.args):
r,v = self.doIRNode(a)
if r: node.args[i] = v
return (None, None)
def doIRPrimitive(self, node):
for i,a in enumerate(node.args):
r,v = self.doIRNode(a)
if r: node.args[i] = v
return (None, None)
def doIRAssign(self, node):
r,v = self.doIRNode(node.value)
if r: node.value = v
return (None, None)
def doIRCascade(self, node):
r,v = self.doIRNode(node.node)
if r: node.node = v
for i,c in enumerate(node.list):
r,v = self.doIRNode(c)
if r: node.list[i] = v
return (None, None)
def doIRInteger(self, node):
return (None, None)
def doIRString(self, node):
return (None, None)
def doIRSymbol(self, node):
return (None, None)
def doIRChar(self, node):
return (None, None)
def doIRName(self, node):
return (None, None)
def doIRArray(self, node):
return (None, None)
| Python |
# vim:ts=4:sw=4:noet:
""" Basic block optimisers """
from bbvisit import BBVisitor
import c.compiler.cfg
class OptTrim(BBVisitor):
def doBasicBlock(self, bb):
newst = []
gotReturn = False
i = 0
while i<len(bb.statements):
st = bb.statements[i]
# check for store/pop pairs, and merge into a pop
if i<(len(bb.statements)-1):
nextst = bb.statements[i+1]
if (isinstance(st, c.compiler.ir.IRAssign) and
isinstance(nextst, c.compiler.cfg.CFGEndStatement) and
st.var.pos<8):
st.addPop()
i+=1
# remove anything after a return
if isinstance(st, c.compiler.ir.IRReturn):
newst.append(st)
gotReturn = True
if not gotReturn:
newst.append(st)
i += 1
bb.statements = newst
| Python |
"""
Optimisations
"""
| Python |
# vim:ts=4:sw=4:noet:
""" IR optimiser base class """
import c.compiler.ir as ir
from c.base.support import CoreException
class IRVisitor:
def doMethod(self, meth):
self.doIRBody(meth.body)
def doIRNode(self, node):
if isinstance(node, ir.IRReturn): return self.doIRReturn(node)
elif isinstance(node, ir.IRMessage): return self.doIRMessage(node)
elif isinstance(node, ir.IRPrimitive): return self.doIRPrimitive(node)
elif isinstance(node, ir.IRName): return self.doIRName(node)
elif isinstance(node, ir.IRAssign): return self.doIRAssign(node)
elif isinstance(node, ir.IRInteger): return self.doIRInteger(node)
elif isinstance(node, ir.IRString): return self.doIRString(node)
elif isinstance(node, ir.IRSymbol): return self.doIRSymbol(node)
elif isinstance(node, ir.IRChar): return self.doIRChar(node)
elif isinstance(node, ir.IRCascade): return self.doIRCascade(node)
elif isinstance(node, ir.IRBlock): return self.doIRBlock(node)
elif isinstance(node, ir.IRArray): return self.doIRArray(node)
else:
raise CoreException("Unhandled node %s" % node)
def doIRBody(self, node):
for i, st in enumerate(node.statements):
r,v = self.doIRNode(st)
if r:
node.statements[i] = v
return (None, None)
def doIRBlock(self, node):
return self.doIRBody(node)
| Python |
"""
The Foxtalk Compiler
The compiler can be roughly divided into 3 parts:
1. Frontend (Lexer, Parser, Semantic Analysis)
2. Midend (IR Generation, CFG, Optimisation)
3. Backend (Code Generation, Image Generation)
The L{compiler driver<Compiler>} manages the various steps of the compilation process. The common case is not compiling a set of source files (this is only the case during initial image generation), but rather recompiling a single method in a live image.
The compilation process is as follows:
1. L{Compiler.compileMethod()<c.compiler.compiler.Compiler.compileMethod>} is called from the UI with a method's new source, and its L{SpyClass}.
2. The method is lexed and L{parsed<c.compiler.parse.Parser.parseMethodFromSource>} resulting in an L{IRMethod}.
3. The method is checked by the L{Semantic Checker<Checker>}, generating an updated L{SpyMethod} from the IRMethod.
4. Method dependencies are updated.
5. L{IR-Level optimisations<c.compiler.opt.iropt>} are performed.
6. CFG conversion is performed on the IR.
7. L{BB-Level optimisations<c.compiler.opt.bbopt>} are performed.
8. Bytecode Generation takes place.
9. Dependant methods are recompiled (since they may have L{inlined<OptInline>} previous versions of this method)
At this point the SpyClasses representing the image are up to date (in terms of the bytecode in their methods). A call to L{CMG.saveToBuf()<c.compiler.cmg.CMG.saveToBuf>} will generate the binary L{CMG} image from the current image in L{Memory}.
"""
| Python |
# vim:ts=4:sw=4:noet:
""" Lexer """
class Token:
EOF, ID, BIN, INT, STR, SYM, FLT = range(7)
typenames = ["EOF", "ID ", "BIN", "INT", "STR", "SYM", "FLT"]
prettyTypenames = [ "EOF", "Identifier", "Binary message", "Integer", "String", "Symbol", "Float" ]
def __init__(self, index, type, value=None, numchars=None):
self.index = index
self.type = type
self.value = value
if not numchars:
if self.value:
self.numchars = len(self.value)
else:
self.numchars = 0
else:
self.numchars = numchars
def isName(self):
if ((self.type in [Token.STR, Token.SYM, Token.EOF]) or
(not self.value[0].isalpha())):
return False
return self.value[-1].isalpha() or self.value[-1].isdigit()
def isKeyword(self):
if (self.type == Token.EOF or (not self.value[0].isalpha())):
return False
return self.value[-1]==":"
def isBinary(self):
if self.type == Token.EOF:
return False
return not (self.isName() or
self.isKeyword() or
self.value[0] in ".()[]#^$;'")
class Lexer:
def __init__(self, status, text):
self.status = status
self.text = text
self.index = 0
self.lineNum = 1
self.token = None
self.oldtoken = None
self.lastComment = ""
self.linestack = []
self.idxofs = 0
def pushLine(self):
idx = self.index
if self.token:
idx = self.token.index
self.linestack.append((self.lineNum, idx))
def popLine(self):
if len(self.linestack)==0:
return (self.lineNum, self.lineNum, self.index, self.index)
ln = self.linestack.pop()
idx = self.index
if self.oldtoken:
idx = self.oldtoken.index+len(self.oldtoken.value)
ln = (ln[0], self.lineNum, ln[1]-self.idxofs, idx-self.idxofs)
return ln
def currentChar(self, n=0):
if (self.index+n)<len(self.text):
return self.text[self.index+n]
return None
def nextChar(self):
if self.currentChar() == "\n":
self.lineNum += 1
self.index += 1
return self.currentChar()
def getText(self, frm, to):
return self.text[frm.index:to.index+1+to.numchars]
def skipBlanks(self):
c = self.currentChar()
while c and c in " \t\r\n":
c = self.nextChar()
if c=="\"":
self.skipComment()
def skipComment(self):
cc = self.nextChar()
comment = cc
while cc!="\"":
cur = self.currentChar()
cc = self.nextChar()
if (cur=="\\" and cc=="\""):
comment = comment[:-1]+"\""
cc = 'a'
else:
comment += cc
if cc==None:
self.status.error("Unterminated comment")
self.lastComment = comment[:-1]
self.nextChar()
self.skipBlanks()
def saveState(self):
self.back_oldtoken = self.oldtoken
self.back_token = self.token
self.back_index = self.index
self.back_lineNum = self.lineNum
self.back_lastComment = self.lastComment
def backtrack(self):
self.oldtoken = self.back_oldtoken
self.token = self.back_token
self.index = self.back_index
self.lineNum = self.back_lineNum
self.lastComment = self.back_lastComment
def nextLex(self):
self.oldtoken = self.token
self.skipBlanks()
c = self.currentChar()
if c==None:
self.token = Token(self.index, Token.EOF)
elif c.isdigit():
self.lexNumber()
elif c.isalpha():
self.lexAlnum()
elif c == "'":
self.lexString()
elif c == "#":
self.lexSymbol()
else:
self.lexBinary()
def lexNumber(self):
start = self.index
while self.nextChar().isdigit() :
pass
if self.currentChar()=="r":
self.nextChar()
cc = self.nextChar()
while cc.isdigit() or cc in "ABCDEF":
cc = self.nextChar()
elif self.currentChar()=="." and self.currentChar(1).isdigit():
self.nextChar()
cc = self.nextChar()
while cc.isdigit():
cc = self.nextChar()
self.token = Token(start, Token.FLT, self.text[start:self.index])
return
self.token = Token(start, Token.INT, self.text[start:self.index])
def lexAlnum(self):
start = self.index
cc = self.nextChar()
while cc.isdigit() or cc.isalpha() or cc==":":
cc = self.nextChar()
self.token = Token(start, Token.ID,self.text[start:self.index])
def charIsSyntax(self, c):
return (c in ".()[]#^$;'")
def lexBinary(self):
c = self.currentChar()
self.token = Token(self.index-0, Token.BIN, c)
d = self.nextChar()
if self.charIsSyntax(c):
return self.token
if (d in " \t\n\r") or d.isdigit() or d.isalpha() or self.charIsSyntax(d):
return self.token
c += d
self.token = Token(self.index-1, Token.BIN, c)
self.nextChar()
def lexString(self):
self.index += 1
first = self.index
cc = self.currentChar()
while cc!="'":
if cc==None:
self.status.error("Unterminated string")
self.index += 1
cc = self.currentChar()
self.index += 1
last = self.index - 1
self.token = Token(first-1, Token.STR, self.text[first:last], len(self.text[first:last])+2)
return self.text[first:last]
def lexSymbol(self):
self.nextChar()
cc = self.currentChar()
if cc==None or cc in " \t\r\n":
self.status.error("Invalid symbol")
if cc=="(":
self.token = Token(self.token.index, Token.BIN, "#(")
self.nextChar()
return self.token
if self.charIsSyntax(cc):
self.status.error("Invalid symbol")
self.nextLex()
self.token = Token(self.token.index, Token.SYM, self.token.value)
cc = self.token
return cc.value
| Python |
# vim:ts=4:sw=4:noet:
""" Semantic Checker Environments """
class Environment:
GLOBAL, IVAR, METH_TEMP, BLOCK_ARG = range(4)
typenames = [
"global",
"instance variable",
"method temporary",
"block argument"
]
def __init__(self, checker, vars, parent, type, name, varBase=0):
self.checker = checker
self.vars = {}
self.parent = parent
if self.parent:
for i,v in enumerate(vars):
pe = self.has(v)
if pe:
self.checker.status.warning(
"%s '%s' in '%s' shadows %s in '%s'" % (
self.typenames[type], v, name, self.typenames[pe.type], pe.name))
self.vars[v] = i
else:
for i,v in enumerate(vars):
self.vars[v] = i
self.type = type
self.name = name
self.varBase = varBase
def has(self, v):
if v in self.vars:
return self
if self.parent:
pe = self.parent.has(v)
if pe:
return pe
return None
def get(self, v):
if v in self.vars:
return self.vars[v]
if self.parent:
pe = self.parent.get(v)
if pe!=None:
return pe
return None
| Python |
# vim:ts=4:sw=4:noet:
""" Connections to devices """
import socket
import serial
import time
class RemoteConnection:
def __init__(self):
self.timeout = 0.5
def setTimeout(self, to):
self.timeout = to
class RemoteTcpConnection(RemoteConnection):
def __init__(self, host="localhost", port=4321, connect=True):
RemoteConnection.__init__(self)
self.host = host
self.port = port
self.sock = None
if connect:
self.connect()
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.sock.connect((self.host, self.port))
self.sock.settimeout(1)
return True
except:
self.sock = None
return False
def __del__(self):
if self.sock:
self.sock.close()
def send(self, msg):
if not self.sock:
if not self.connect():
return []
self.sock.send(msg)
def recv(self):
if not self.sock:
if not self.connect():
return []
return self.sock.recv(512)
def close(self):
self.sock.close()
self.sock = None
def __repr__(self):
return "<conn tcp %s:%d>" % (self.host, self.port)
class RemoteSerialConnection(RemoteConnection):
def __init__(self, port="/dev/tty.KeySerial1", baud=115200, connect=True):
RemoteConnection.__init__(self)
self.port = port
self.baud = baud
if connect:
self.connect()
def connect(self):
self.ser = serial.Serial(self.port, self.baud)
self.ser.flushInput()
self.ser.flushOutput()
def send(self, msg):
if self.timeout>0.5:
self.ser.write(msg)
#for m in msg:
# self.ser.write(m)
# time.sleep(0.000001)
else:
self.ser.write(msg)
def recv(self):
timeout = time.time()+self.timeout
while not self.ser.inWaiting():
if (time.time()>timeout):
return []
l = ord(self.ser.read(1))
data = self.ser.read(l-1)
return chr(l)+data
def close(self):
self.ser.close()
def __repr__(self):
return "<conn ser %s>" % (self.port)
| Python |
# vim:ts=4:sw=4:noet:
""" VM remote interface """
import logging
from simpleobj import SimpleObj, SimpleSmallInt
ERROR_BAD_MSG = 7
ERROR_RUNTIME = 14
NIL_PTR = 0x4000
errNames = [
"Unknown error",
"Halt instruction",
"Fatal primitive error",
"Out of memory",
"Root stack overflow",
"Root stack underflow",
"Stack underflow",
"Method not understood",
"Static object write",
"Object data out of range",
"Communication message overflow",
"Tried to convert non-bin to string",
"Invalid bytecode instruction",
"Static cache overflow",
"Runtime error",
]
class RemoteStackFrame:
""" Representation of a remote stack frame (from L{Remote.backtrace()}) """
def __init__(self, meth, incls, recv, line, type, args, temps):
self.meth = meth
self.incls = incls
self.recv = recv
self.line = line
self.type = type
self.args = args
self.temps = temps
class RemoteObj:
""" L{SimpleObj} wrapper for backtrace views """
def __init__(self, value, ptr=None):
self.value = value
self.ptr = ptr
if self.ptr:
self.loc = "%s@%s" % (str(self), self.ptr)
else:
self.loc = str(self)
def __repr__(self):
return self.value
def __str__(self):
return str(self.value)
class Remote:
def __init__(self, dm, status):
self.globals = None
self.dm = dm
self.conn = None
self.status = status
def send(self,command,data, showresp=1):
msg = ""
msg += chr(len(data)+3)
msg += chr(command)
for d in data:
msg += chr(d)
msg += '\0'
self.conn.send(msg)
r = map(lambda x: ord(x), self.conn.recv())
if len(r)==0:
raise Exception("Timeout sending data to robot")
if len(r)<3 or len(r)!=r[0]:
raise Exception("Invalid response from robot: %s" % r)
else:
resp_len = r[0]
resp = r[1:-1]
if showresp:
self.parseResp(resp)
return resp
def parseResp(self, resp):
cmd = resp[0]
data = resp[1:]
if cmd > 1:
return
self.status.printNnl(" Response:",)
if cmd==1:
if data[0]==1:
self.status.printNl("OK")
else:
self.status.printNl("ERROR")
else:
self.status.printNl("Unknown")
def parseObject(self, data):
truncated = data[0]==5
if len(data)<4:
self.status.printNl("Invalid object")
return
ptr = (data[2]<<8) + data[1]
if ptr&2:
return SimpleSmallInt(ptr>>2)
hdr = (data[4]<<8) + data[3]
bin = hdr&0x8000
hdr &= (~0x8000)
size = hdr>>2
cls = (data[6]<<8) + data[5]
odata = []
if bin:
if (size+7)>len(data):
if truncated:
for i in range(len(data)-7):
odata.append(data[7+i])
else:
raise Exception("Invalid bin object size: %d" % size)
else:
for i in range(size):
odata.append(data[7+i])
else:
if (size*2+7)>len(data):
if truncated:
for i in range((len(data)-7)>>1):
odata.append((data[8+(i*2)]<<8) + data[7+(i*2)])
else:
raise Exception("Invalid object size: %d" % size)
else:
for i in range(size):
odata.append((data[8+(i*2)]<<8) + data[7+(i*2)])
return SimpleObj(self, ptr, cls, size, bin, odata, truncated)
def parseDict(self, dict):
keys = self.getObject(dict.data[0])
vals = self.getObject(dict.data[1])
pdict = {}
for i, k in enumerate(keys.data):
key = self.getObject(k).asString()
val = self.getObject(vals.data[i])
pdict[key] = val
return pdict
def detect(self):
pass
def setVMState(self, state):
self.dm.aquireConnection()
self.send(1,[state], showresp = 0)
self.dm.releaseConnection()
def getVMState(self):
self.dm.aquireConnection()
s = self.send(2,[])
self.dm.releaseConnection()
return s
def restart(self):
self.dm.aquireConnection()
self.send(3,[], showresp = 0)
self.dm.releaseConnection()
def getObject(self, optr):
self.dm.aquireConnection()
if optr&2:
obj = SimpleSmallInt(optr>>2)
else:
obj = self.parseObject(self.send(6,[optr&0xFF, optr>>8]))
self.dm.releaseConnection()
return obj
def getCurCtx(self, nth=0):
ctx = self.parseObject(self.send(4,[]))
while isinstance(ctx, SimpleObj) and ctx.ptr!=NIL_PTR and nth>0:
ctx = self.getObject(ctx.data[6])
nth = nth - 1
if (not isinstance(ctx, SimpleObj)) or ctx.ptr==NIL_PTR:
return None
return ctx
def getRawGlobals(self):
return self.parseObject(self.send(5,[]))
def getGlobals(self):
self.globals = self.parseDict(self.parseObject(self.send(5,[])))
return self.globals
def getGlobal(self, name):
if not self.globals:
self.getGlobals()
if name in self.globals:
return self.globals[name]
else:
return None
def getLastError(self):
self.dm.aquireConnection()
x = self.send(7,[])
errno = x[1]+(x[2]<<8)
errparam = x[3]+(x[4]<<8)
errstring = "Unknown error"
if errno<len(errNames):
errstring = errNames[errno]
self.dm.releaseConnection()
return (errno, errparam, errstring)
def sendStaticRoots(self, data):
self.send(8, data, showresp=0)
def sendStaticBlock(self, addr, data):
ln = len(data)/2
addr /= 2
cmd = [addr&0xFF, addr>>8, ln&0xFF, ln>>8]
for d in data:
cmd.append(d)
self.send(9,cmd, showresp=0)
def getVersion(self):
self.dm.aquireConnection()
data = self.send(11, [], showresp=0)
self.dm.releaseConnection()
str = ""
for d in data[1:]:
if d!=0:
str += chr(d)
return str.split("-")
def getPlatform(self):
self.dm.aquireConnection()
data = self.send(12, [], showresp=0)
self.dm.releaseConnection()
str = ""
for d in data[1:]:
if d!=0:
str += chr(d)
return str.split("-")
def setObjectData(self, optr, idx, val):
data = [optr&0xFF, optr>>8, idx&0xFF, idx>>8, val&0xFF, val>>8]
self.dm.aquireConnection()
self.send(15, data, showresp=0)
self.dm.releaseConnection()
def allocObject(self, size, cls, bin=0):
data = [size&0xFF, size>>8, cls&0xFF, cls>>8, bin]
self.dm.aquireConnection()
r = self.send(16, data, showresp=0)
self.dm.releaseConnection()
return self.parseObject(r)
def allocSymbol(self, val):
blen = len(val)
sym = self.allocObject(blen, self.getGlobal("Symbol").ptr, 1)
for i,c in enumerate(val):
sym.setData(i, ord(c))
return sym
def allocByteArray(self, val):
blen = len(val)
sym = self.allocObject(blen, self.getGlobal("ByteArray").ptr, 1)
for i,c in enumerate(val):
sym.setData(i, c)
return sym
def runMethod(self, meth, recv):
data = [meth&0xFF, meth>>8, recv&0xFF, recv>>8]
self.dm.aquireConnection()
self.send(17, data, showresp=0)
self.dm.releaseConnection()
def getLastReturn(self):
self.dm.aquireConnection()
r = self.send(18, [], showresp=0)
self.dm.releaseConnection()
return self.parseObject(r)
def getBootState(self):
self.dm.aquireConnection()
s = self.send(131,[])
self.dm.releaseConnection()
if len(s)!=2:
raise Exception("invalid boot state")
return s[0] == 3 and s[1] == 1
def isUpgradable(self):
logging.error("implement: isUpgradable")
return True
def enterBootloader(self):
logging.error("implement: enterBootloader")
def bootInit(self):
r = self.send(130,[], showresp=0)
if r[0]!=1 or r[1]!=1:
self.dm.releaseConnection()
raise Exception("Couldn't initialise bootloader")
def bootPageWrite(self, addr, data):
di = 0
for c in range(4):
req = [addr&0xFF, (addr>>8)&0xFF, (addr>>16)&0xFF, (addr>>24)&0xFF]
for i in range(32):
req.append(data[di])
di += 1
r = self.send(129,req, showresp=0)
if r[0]!=1 or (r[1]!=3 and r[1]!=1):
self.dm.releaseConnection()
raise Exception("Couldn't write page at 0x%06X" % addr)
def bootImageWrite(self, start, data, progressCb=None):
if (len(data)%128)!=0:
x = ((len(data)/128)+1)*128 - len(data)
for i in range(x):
data.append(0)
n = start
end = start+len(data)
while n < end:
if progressCb:
progressCb(int((n-start)/float(end-start)*100.0))
r = self.bootPageWrite(n,data[n-start:n-start+128])
n += 128
if progressCb:
progressCb(100)
def upgrade(self, fn, progressCb=None):
f = file(fn,"rb")
data = map(ord,f.read())
f.close()
self.status.printNl("Upgrading firmware with '%s'" % fn)
self.dm.aquireConnection()
self.conn.setTimeout(1)
self.enterBootloader()
self.bootInit()
self.bootImageWrite(0x2000, data, progressCb)
self.conn.setTimeout(0.5)
self.dm.releaseConnection()
def upload(self, fn, progressCb=None):
f = file(fn,"rb")
data = map(ord,f.read())
f.close()
self.status.printNl("Uploading %s (%d bytes)." % (fn,len(data)))
self.uploadCMG(data, progressCb)
def uploadCMG(self, data, progressCb=None):
self.dm.aquireConnection()
try:
self.sendStaticRoots(data[:34])
except:
self.status.printNl("Failed to upload static roots")
return
statics = data[34:]
for d in range(264 - len(statics)%264):
statics.append(0xFF);
remaining = len(statics)
total = remaining
blockSize = 44
pos = 0
try:
while (remaining>=blockSize):
if progressCb:
progressCb(int((total-remaining)/float(total)*100.0))
self.sendStaticBlock(pos,statics[pos:pos+blockSize])
pos += blockSize
remaining -= blockSize
if remaining:
self.sendStaticBlock(pos,statics[pos:pos+remaining])
if progressCb:
progressCb(100)
except:
self.status.printNl("Failed upload at %d" % pos)
return
#self.status.printNl("Upload complete.")
self.dm.releaseConnection()
self.restart()
def arrayToPython(self, arr, limit=-1):
arrPy = []
array = arr.data
if limit!=-1:
array = array[:limit]
for i,aptr in enumerate(array):
item = self.getObject(aptr)
if isinstance(item, SimpleSmallInt):
arrPy.append(RemoteObj(item.val))
else:
acls = self.getObject(item.cls)
aclsName = self.getObject(acls.data[0]).asString()
if item.ptr == NIL_PTR:
aclsName = "nil"
elif aclsName == "String":
aclsName = item.asString()
elif aclsName == "Symbol":
aclsName = "#%s" % item.asString()
elif aclsName == "Integer":
v = 0
for i in range(3,-1,-1):
v = (v << 8) | item.data[i]
aclsName = "%d" % v
else:
aclsName = "<%s>" % aclsName
arrPy.append(RemoteObj(aclsName, aptr))
return arrPy
def backtrace(self, verbose=False, mem=None):
curCtx = self.getCurCtx()
blkPtr = self.getGlobal("Block").ptr
frames = []
while curCtx.ptr != NIL_PTR:
meth = self.getObject(curCtx.data[0])
methName = self.getObject(meth.data[0]).asString()
args = self.getObject(curCtx.data[1])
temps = self.getObject(curCtx.data[2])
bp = self.getObject(curCtx.data[4])
inclsName = "?"
numArgs = 0
if curCtx.cls == blkPtr:
ctxType = "block"
else:
ctxType = "message"
tempArray = []
if (temps.ptr != NIL_PTR):
tempArray = self.arrayToPython(temps)
ctxLine = 0 #"?"
clsName = "?"
if len(temps.data)>0:
arg = self.getObject(temps.data[0])
if isinstance(arg, SimpleSmallInt):
mcls = "SmallInt"
else:
acls = self.getObject(arg.cls)
mcls = self.getObject(acls.data[0]).asString()
bpv = 0
if isinstance(bp, SimpleSmallInt):
bpv = bp.val
else:
logging.error("bad bytepointer in backtrace %s" % bp)
clsName = mcls
inclsName = mcls
numArgs = len(tempArray)
if mem:
scls = mem.getGlobal(mcls)
if (scls):
# this gets broken by doit currently (because the receiver isn't set correctly)
smeth = scls.getMethod(methName)
if smeth:
inclsName = smeth.incls.name
ctxLine = smeth.lineFromBp(bpv)
numArgs = len(smeth.args)
else:
break
tempsArray = tempArray[numArgs:]
argsArray = tempArray[:numArgs]
f = RemoteStackFrame(
methName, inclsName, clsName, ctxLine, ctxType, argsArray, tempsArray)
frames.append(f)
curCtx = self.getObject(curCtx.data[6])
return frames
def rawRead(self, addr, ln):
cmd = [addr&0xFF, addr>>8, ln&0xFF, ln>>8]
return self.send(10,cmd, showresp=0)
| Python |
# vim:ts=4:sw=4:noet:
"""
VM remote object proxies
When interacting with the VM via L{Remote}, SimpleObjs are proxies representing
objects resident in the remote VMs memory.
Since the Foxtalk VM uses an optimised representation for Integers -8191 to 8192,
there's also a SimpleSmallInt proxy.
"""
class SimpleObj:
""" Remote Object Proxy """
def __init__(self, remote, ptr, cls, size, bin, data, trunc):
self.remote = remote
self.ptr = ptr
self.cls = cls
self.size = size
self.bin = bin
self.data = data
self.trunc = trunc
def __repr__(self):
return "<obj@%d: %d %s>" % (self.ptr, self.size, self.data)
def setData(self, idx, val):
self.data[idx] = val
self.remote.setObjectData(self.ptr, idx, val)
def asString(self):
s = ""
for c in self.data:
s += chr(c)
return s
def asPrettyString(self, remote):
acls = remote.getObject(self.cls)
aclsName = remote.getObject(acls.data[0]).asString()
return "<%s@%d: %d %s>" % (aclsName, self.ptr, self.size, self.data)
class SimpleSmallInt:
""" Smallint Object Proxy """
def __init__(self, val):
self.val = val
def asPrettyString(self, remote):
return "<SmallInt: %d>" % self.val
def asString(self):
return str(self.val)
| Python |
"""
Remote Object/Memory Interface
Remote provides an interface to a remote device's Foxtalk VM. It allows interaction with all the core functionality of the VM and Foxtalk code running on the VM.
L{Remote} interacts with the target device via the L{Device Manager<c.device>}. The remote allows interaction with live objects in the target VM memory, represented on the host side by L{SimpleObj}s.
"""
| Python |
# vim:ts=4:sw=4:noet:
"""
Simulator and VM-Sim Interface
"""
import socket
import SocketServer
import logging
import math
import subprocess
from Queue import Queue
from c.base.support import CoreException
from c.base.platform import Platform
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
logging.info("[sm] Sim client connect")
try:
while 1:
data = self.request.recv(1024).strip().split()
response = 0
if len(data)>0:
cmd = "cmd_"+data[0]
args = data[1:]
#print "got cmd", cmd, args
if hasattr(self.server.sim, cmd):
response = getattr(self.server.sim, cmd)(args)
if not response:
response = 0
else:
logging.warn("Unhandled sim request '%s'" % data)
response = -1
self.request.send("%d" % response)
except Exception, e:
logging.info("[sm] Sim client disconnect: %s" % e)
self.server.sim.reset()
return
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
def setSim(self, sim):
self.sim = sim
class Simulator:
def __init__(self, mc):
self.mc = mc
host = "localhost"
port = 2345
self.cvm_killed = False
self.server = None
for i in range(5):
try:
self.server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
break
except socket.error, e:
logging.warning("couldn't start sim on %d, trying new port" % port)
port += 1
if not self.server:
raise CoreException("Couldn't start simulator server: %s" % e)
self.simport = port
self.server.setSim(self)
ip, port = self.server.server_address
logging.info("[sm] Simulator server on %s:%s" % (ip, port))
self.printbuf = ""
self.pbqueue = Queue()
self.mc.tm.createTask("simserver", self.server.serve_forever, daemon=True)
self.resetPos = (175, 175)
self.maxPos = (350, 350)
self.reset()
self.mc.tm.createTask("cvm", self.cvm_runner)
def __del__(self):
print "sim destroy"
if not self.cvm_killed and hasattr(self, "cvm_p"):
print "need to kill cvm"
self.shutdown()
def shutdown(self):
logging.info("[sm] Shutting down")
self.cvm_p.kill()
self.cvm_killed = True
self.server.shutdown()
def cvm_runner(self):
logging.info("[sm] cvm started")
self.cvm_p = subprocess.Popen([Platform.getSimCmd(), "-p", "%d" % self.simport])
self.cvm_p.wait()
logging.info("[sm] cvm done")
def reset(self):
self.pos = self.oldPos = self.resetPos
self.theta = self.oldTheta = 0
self.vel = [0,0]
self.encoder = [0,0]
self.encoderTarget = [0,0]
self.radius = 20.0
self.wheel_radius = 10.0
self.penDown = False
self.penWidth = 1
self.penColour = (0.,0.,0.)
self.lines = []
self.linesDrawn = 0
self.needsReset = True
self.pbqueue.put("")
self.bumpers = [0,0,0]
self.lineSensor = [0,0,0]
self.addLinePoint()
def addLinePoint(self):
self.lines.append((self.pos, self.penColour, self.penWidth, self.penDown))
def getDistanceFrac(self, d0, de, dtarg):
d1 = d0+de
if ((d1 > d0 and dtarg >= d0 and dtarg <= d1) or
(d1 < d0 and dtarg <= d0 and dtarg >= d1)):
return (dtarg-d0)/(d1-d0)
return 1.0
def angleInRange(self, angle, low, high):
angle = angle%360
low = low%360
high = high%360
if high>=low:
return (angle>=low) and (angle<=high)
else:
return (angle>=low) or (angle<=high)
def checkBumpersAngle(self, ofs):
B_ANGLE_MAX = 60
B_ANGLE_MIN = 30
B_ANGLE_BOTH = 30
angle = math.degrees(self.theta)%360
if self.angleInRange(angle, ofs-B_ANGLE_MAX, ofs-B_ANGLE_MIN):
self.bumpers[1] = 1
if self.angleInRange(angle, ofs+B_ANGLE_MIN, ofs+B_ANGLE_MAX):
self.bumpers[0] = 1
if self.angleInRange(angle, ofs-B_ANGLE_BOTH, ofs+B_ANGLE_BOTH):
self.bumpers = [1,1]
def checkBumpers(self, collx, colly):
self.bumpers = [0,0]
if collx==1:
self.checkBumpersAngle(270)
elif collx==-1:
self.checkBumpersAngle(90)
if colly==1:
self.checkBumpersAngle(0)
elif colly==-1:
self.checkBumpersAngle(180)
def update(self, dt):
if self.vel[0]==0 and self.vel[1]==0:
return
# get left and right wheel velocities (revs/s), set ticks/rev
v_l, v_r = self.vel
tpr = 1800
# calculate revolutions
rev_l = v_l * dt
rev_r = v_r * dt
# calculate distance traveled for each wheel
d_l = rev_l * math.pi*2*self.wheel_radius
d_r = rev_r * math.pi*2*self.wheel_radius
# get encoder ticks
enc_l = rev_l * tpr
enc_r = rev_r * tpr
# get fraction of update travelled, based on encoder targets
frac_l = self.getDistanceFrac(self.encoder[0], enc_l, self.encoderTarget[0])
frac_r = self.getDistanceFrac(self.encoder[1], enc_r, self.encoderTarget[1])
d_l *= frac_l
d_r *= frac_r
enc_l *= frac_l
enc_r *= frac_r
# calculate cartesian motion
d_th = (d_l-d_r)/(2.0*self.radius)
d_avg = (d_l+d_r)/(2.0)
d_x = -d_avg*math.sin(self.theta)
d_y = d_avg*math.cos(self.theta)
# update
self.theta += d_th
newx = self.pos[0] + d_x
newy = self.pos[1] + d_y
rd = self.radius/2 + 3
collx = colly = 0
if (newx > self.maxPos[0]-rd):
newx = self.maxPos[0]-rd
collx = 1
if (newx < rd):
newx = rd
collx = -1
if (newy > self.maxPos[1]-rd):
newy = self.maxPos[1]-rd
colly = 1
if (newy < rd):
newy = rd
colly = -1
self.checkBumpers(collx, colly)
self.pos = (newx, newy)
self.encoder[0] += enc_l
self.encoder[1] += enc_r
"""
print "rev:(%0.2f,%0.2f) | d:(%0.2f,%0.2f) | enc:(%0.2f,%0.2f) | pos:(%0.2f,%0.2f)" % (
rev_l, rev_r,
d_l, d_r,
self.encoder[0], self.encoder[1], #enc_l, enc_r,
self.encoderTarget[0], self.encoderTarget[1])
print frac_l, frac_r
"""
# update lines
dx = self.pos[0] - self.oldPos[0]
dy = self.pos[1] - self.oldPos[1]
dth = abs(self.theta - self.oldTheta)
if (math.sqrt((dx*dx)+(dy*dy))>5 or dth>1):
if self.penDown:
self.addLinePoint()
self.oldTheta = self.theta
self.oldPos = self.pos
def cmd_beep(self, args):
logging.warn("BEEP %s" % args[0])
def cmd_reset(self, args):
self.reset()
def cmd_stop(self, args):
self.vel = [0,0]
def cmd_printchar(self, args):
c = chr(int(args[0]))
if c=="\n":
self.pbqueue.put(self.printbuf)
self.printbuf = ""
else:
self.printbuf += c
def cmd_setvel(self, args):
self.vel[int(args[0])] = float(args[1])/135.0
def cmd_setposition(self, args):
self.pos = (float(args[0]), float(args[1]))
def cmd_setangle(self, args):
self.theta = float(args[0])
def cmd_pencolour(self, args):
r, g, b = [float(x)/7.0 for x in args]
self.penColour = (r,g,b)
def cmd_penstate(self, args):
self.addLinePoint()
self.penDown = int(args[0])==1
self.addLinePoint()
def cmd_penstyle(self, args):
self.penWidth = int(args[0])
def cmd_getposition(self, args):
which = int(args[0])
if which==0:
return int(self.pos[0])
elif which==1:
return int(self.pos[1])
elif which==2:
a = math.degrees(self.theta)%360
return int(round(a, 0))
return 0
def cmd_getencoder(self, args):
which = int(args[0])
if which==0:
return int(self.encoder[0])
elif which==1:
return int(self.encoder[1])
return 0
def cmd_getdigital(self, args):
which = int(args[0])
if which >= 0 and which <= 2:
return self.bumpers[which]
elif which >= 3 and which <= 5:
return int(self.lineSensor[which-3])
return 0
def cmd_motioncommand(self, args):
which, value = map(int, args)
if which == 255:
dist = 0.001
if ((abs(self.encoder[0] - self.encoderTarget[0]) < dist) and
(abs(self.encoder[1] - self.encoderTarget[1]) < dist)):
return 0
else:
return 1
else:
self.encoderTarget[which] = value
return 0
| Python |
"""
Foxbot Simulator
"""
| Python |
# vim:ts=4:sw=4:noet:
""" Connection Manager to remote devices """
import threading
import logging
import time
import glob
import sys
from c.remote.connection import RemoteTcpConnection, RemoteSerialConnection
class DeviceChecker:
def __init__(self, dm):
self.dm = dm
self.connections = {}
def addConnection(self, id, conn, bootable):
self.connections[id] = (conn, bootable)
self.dm.onConnect(id, conn, bootable)
def removeConnection(self, id):
self.dm.onDisconnect(id, self.getConnection(id))
del self.connections[id]
def hasConnection(self, id):
return id in self.connections
def getConnection(self, id):
return self.connections[id][0]
def isConnectionBootable(self, id):
return self.connections[id][1]
def check(self):
pass
class SimDeviceChecker(DeviceChecker):
def __init__(self, dm):
DeviceChecker.__init__(self, dm)
self.conn = RemoteTcpConnection(connect=False)
def check(self):
if self.conn.sock:
try:
self.dm.mc.r.getBootState()
except Exception, e:
self.conn.sock = None
self.dm.releaseConnection()
self.removeConnection("sim:tcp")
else:
if self.conn.connect():
self.addConnection("sim:tcp", self.conn, False)
class SerialDeviceChecker(DeviceChecker):
def __init__(self, dm):
DeviceChecker.__init__(self, dm)
def check(self):
if sys.platform=="win32":
ports = []
for i in range(16):
ports.append(i)
else:
ports = glob.glob("/dev/tty.usbmodem*")
ports.extend(glob.glob("/dev/ttyUSB*"))
connkeys = self.connections.keys()
setNew = False
# check available ports
for p in ports:
oldconn = self.dm.mc.r.conn
if p in connkeys:
# if we're already connected to this port, check for disconnects
connkeys.remove(p)
conn = self.getConnection(p)
self.dm.mc.r.conn = conn
try:
self.dm.mc.r.getBootState()
except:
self.dm.releaseConnection()
cn = self.getConnection(p)
self.removeConnection(p)
cn.close()
else:
# otherwise check if there's a bot attached
try:
conn = RemoteSerialConnection(p)
self.dm.mc.r.conn = conn
boot = self.dm.mc.r.getBootState()
setNew = True
self.addConnection(p, conn, boot)
except:
self.dm.releaseConnection()
if not setNew:
self.dm.mc.r.conn = oldconn
# remaining conns are invalid because the port no longer exists
for p in connkeys:
cn = self.getConnection(p)
self.removeConnection(p)
cn.close()
class DeviceConnection:
pass
class DeviceManager:
def __init__(self, mc):
self.mc = mc
self.deviceCheckers = [
SimDeviceChecker(self),
SerialDeviceChecker(self),
]
self.mc.tm.createTask("checker", self.checkDevices, start=False)
self.stop = False
self.connected = False
self.curConnection = None
self.connLock = threading.Semaphore()
self.count = -5
def start(self):
self.mc.tm.startTask("checker")
def aquireConnection(self):
self.connLock.acquire()
return self.curConnection
def releaseConnection(self):
self.connLock.release()
def shutdown(self):
logging.info("[dm] Shutting down")
self.stop = True
def currentConnection(self):
return self.curConnection
def checkForFirmwareUpgrade(self):
revstr = self.mc.r.getVersion()[2][1:]
if not revstr:
return
rev = int(revstr)
p, a = self.mc.r.getPlatform()
fw = glob.glob("fw/%s-%s-*.bin" % (p.lower(), a.lower()))
upgrade = False
ffile = ""
for f in fw:
v = f[3:-4].split("-")
frev = int(v[2])
if frev>rev:
ffile = f
upgrade = True
if upgrade:
self.mc.showDeviceUpgrade(frev, ffile)
def refresh(self):
for dc in self.deviceCheckers:
for c in dc.connections:
self.onConnect(c, dc.getConnection(c), dc.isConnectionBootable(c))
def onConnect(self, id, conn, bootable):
self.curConnection = conn
self.mc.r.conn = conn
if bootable:
name = "<giggleboot>"
self.mc.addDevice(id, name, conn)
else:
name = self.mc.r.getPlatform()[0]
self.mc.addDevice(id, str(name), conn)
self.checkForFirmwareUpgrade()
logging.info("[dm] Connected %s" % conn)
def onDisconnect(self, id, conn):
self.curConnection = None
self.mc.r.conn = None
self.mc.removeDevice(id)
logging.info("[dm] Disconnected %s" % conn)
def checkDevices(self):
while not self.stop:
self.count += 1
if self.count % 20 == 0:
for dc in self.deviceCheckers:
dc.check()
time.sleep(0.1)
| Python |
"""
Remote Device Management
The L{DeviceManager} handles connections to target robots (or the simulator) via L{DeviceConnection}s. Device presence is polled via a medium-specific L{DeviceChecker}.
"""
| Python |
# vim:ts=4:sw=4:noet:
""" Support code """
import sys
class Struct:
def __init__(self, **entries): self.__dict__.update(entries)
Enum = Struct
class CoreException:
def __init__(self, msg, data=None):
self.msg = msg
self.data = data
def __str__(self):
if self.data:
return "%s" % (self.msg)
return self.msg
class Status:
def __init__(self, options, outstream=sys.stdout):
self.options = options
self.outstream = outstream
def error(self, msg, data=None):
if (self.options["exceptions"]):
raise CoreException(msg, data)
else:
self.outstream.write("ERROR: %s\n" % msg)
sys.exit(1)
def warning(self, msg):
self.outstream.write("WARNING: %s\n" % msg)
def info(self, msg):
self.outstream.write("%s\n" % msg)
def printNl(self, msg):
self.outstream.write("%s\n" % msg)
def printNnl(self, msg):
self.outstream.write("%s" % msg)
| Python |
# vim:ts=4:sw=4:noet:
"""
Logger
"""
import logging
def initLogging():
logging.basicConfig(
level = logging.ERROR,
format = "%(asctime)s %(levelname)7s: %(message)s")
logging.info("Log started")
| Python |
""" Version information """
InfoStrings = {
"shortname" : "Foxtalk",
"longname" : "Foxtalk",
"copyright" : "Foxtalkbots.com, 2010",
"versionString" : "0.9.4",
"description" : "Foxtalk Smalltalk Environment",
"imageExtension" : "fox",
"binaryExtension" : "cmg",
"urlAppcast" : "http://foxtalkbots.com/foxtalkappcast.xml",
"urlReference" : "http://foxtalkbots.com/forum",
"urlDownload" : "http://foxtalkbots.com/download.php",
"urlHomepage" : "http://foxtalkbots.com",
"emailInfo" : "info@foxtalkbots.com",
"configfile" : "foxtalk.cfg"
}
| Python |
"""
Miscellaneous base support code
"""
| Python |
# vim:ts=4:sw=4:noet:
""" Platform specific tweaks """
import os
import sys
from c.base.version import InfoStrings
class SPlatform:
def __init__(self):
self.basePath = None
self.configPath = None
self.simPath = None
if sys.platform == "win32":
self.simExe = "cvm16.exe"
else:
self.simExe = "cvm16"
def getSimCmd(self):
if not self.simPath:
options = [self.getBasePath()]
if sys.platform == "linux2":
options.append("../vm")
elif sys.platform == "win32":
options.append("c:/dev/foxtalk/vm")
elif sys.platform == "darwin":
options.append("../vm")
for opt in options:
op = os.path.join(opt, self.simExe)
if os.path.exists(op):
self.simPath = opt
break
if not self.simPath:
raise Exception("CVM16 not found")
return os.path.join(self.simPath, self.simExe)
def __getConfigPath(self):
if sys.platform == "win32":
home = os.getenv("USERPROFILE")
return os.path.join(home,"Application Data",InfoStrings["shortname"])
elif sys.platform == "linux2":
home = os.getenv("HOME")
return os.path.join(home,".%s" % InfoStrings["shortname"].lower())
elif sys.platform == "darwin":
home = os.getenv("HOME")
return os.path.join(home,"Library","Preferences",InfoStrings["shortname"])
def getConfigPath(self):
""" The config path is the location of config files
windows: env(USERPROFILE)\Application Data\<APP>
mac: ~/Library/Preferences/<APP>
linux: ~/.<APP> """
if not self.configPath:
self.configPath = self.__getConfigPath()
if not os.path.exists(self.configPath):
os.mkdir(self.configPath)
return self.configPath
def getConfigFilePath(self, fn):
return os.path.join(self.getConfigPath(), fn)
def getDefaultDir(self):
if sys.platform == "win32":
home = os.getenv("USERPROFILE")
return os.path.join(home,"My Documents")
else:
return os.getenv("HOME")
def __getBasePath(self):
if sys.platform == "win32":
# cwd works well enough on windows
return os.getcwd()
else:
# this should work well enough on linux
# but need to check mac app bundle
path = [os.getcwd()]
path.extend(os.getenv("PATH").split(":"))
for p in path:
fullpath = os.path.join(p, "cog.py")
if os.path.exists(fullpath):
return p
# fallthrough to cwd
return os.getcwd()
def getDataPath(self):
""" The data path is the location of data files
windows: data dir next to <APP>.exe (c:\program files\<APP>\data)
mac: inside <APP>.app (/Applications/<APP>.app/Resources/data)
linux: <APP> /share/<APP> (/usr/local/share/<APP>) """
#if sys.platform == "darwin":
# return self.getBasePath()
#else:
path = os.path.join(self.getBasePath(), "data")
if os.path.exists(path):
return path
else:
return self.getBasePath()
def getDataFilePath(self, fn):
return os.path.join(self.getDataPath(), fn)
def getBasePath(self):
""" The base path is the same directory as the application is in
windows: same as <APP>.exe (c:\program files\<APP>)
mac: same as <APP>.app (/Applications)
linux: same as <APP> (/usr/local/bin) """
if not self.basePath:
self.basePath = self.__getBasePath()
return self.basePath
Platform = SPlatform()
| Python |
# vim:ts=4:sw=4:noet:
"""
Class property helper
"""
import sys
def attribute(name, permit='rw', fget=None, fset=None, doc=''):
if _isprivate(name):
name = "_%s%s" % (_get_classname(), name)
if 'r' in permit and fget is None:
fget = lambda self: getattr(self, name)
if 'w' in permit and fset is None:
fset = lambda self, value: setattr(self, name, value)
fdel = lambda self: delattr(self, name)
return property(fget, fset, fdel, doc)
def _isprivate(name):
return name.startswith("__") and not name.endswith("__")
def _get_classname():
frame = sys._getframe(2)
return frame.f_code.co_name
| Python |
"""
Foxtalk
"""
| Python |
# vim:ts=4:sw=4:noet:
""" Documentation window """
import wx
import logging
from c.ui.wxw.common import loadWxImage, getProperPath
from c.base.platform import Platform
class IntroWindow(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent)
self.parent = parent
bmp = wx.Bitmap(getProperPath(Platform.getDataFilePath("intro.png")))
self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
self.SetSize((bmp.GetWidth(), bmp.GetHeight()))
parent.Fit()
bparent = self
if wx.Platform=="__WXMSW__":
bparent = self.bitmap
self.buttonTut = wx.Button(bparent, -1,
label='Start Tutorial', pos=(30, 180))
self.buttonTut.Bind(wx.EVT_BUTTON, self.buttonTut_click)
self.buttonNew = wx.Button(bparent, -1,
label='New Project', pos=(170, 180))
self.buttonNew.Bind(wx.EVT_BUTTON, self.buttonNew_click)
self.Show()
self.CentreOnParent()
def buttonTut_click(self, event):
self.Show(False)
self.parent.onTutorialButton(event)
def buttonNew_click(self, event):
self.Show(False)
self.parent.onNewProjectButton(event)
| Python |
# vim:ts=4:sw=4:noet:
""" UI element ids and shortcuts """
import wx
MenuInfo = {
"FILE_NEW_PROJECT" : "Ctrl+Alt+N",
"FILE_OPEN" : "Ctrl+O",
"FILE_EXAMPLES" : "",
"FILE_SAVE" : "Ctrl+S",
"FILE_DELETE" : "Ctrl+Alt+D",
"FILE_SAVE_AS" : "Ctrl+Shift+S",
"FILE_PAGE_SETUP" : "Ctrl+Shift+P",
"FILE_PRINT" : "Ctrl+P",
"FILE_EXIT" : "",
"EDIT_UNDO" : "Ctrl+Z",
"EDIT_REDO" : "Ctrl+Shift+Z",
"EDIT_CUT" : "Ctrl+X",
"EDIT_COPY" : "Ctrl+C",
"EDIT_PASTE" : "Ctrl+V",
"EDIT_SELECT_ALL" : "Ctrl+A",
"VIEW_CONSOLE" : "Ctrl+Shift+C",
"VIEW_SIMULATOR" : "Ctrl+Alt+S",
"VIEW_BROWSER" : "Ctrl+B",
"VIEW_JUMPTO" : "Ctrl+J",
"VIEW_GET_INFO" : "Ctrl+I",
"VIEW_DOCUMENTATION" : "Ctrl+D",
"PROJECT_OPEN" : "Ctrl+Shift+O",
"PROJECT_NEW_METHOD" : "Ctrl+N",
"PROJECT_NEW_CLASS" : "Ctrl+Shift+N",
"PROJECT_COMPILE" : "Ctrl+E",
"PROJECT_ADD_EXISTING" : "Ctrl+Shift+A",
"PROJECT_RUN" : "Ctrl+R",
"PROJECT_STOP" : "Ctrl+T",
"PROJECT_PAUSERESUME" : "Ctrl+Shift+R",
"PROJECT_EDIT_LIBRARY" : "",
"PROJECT_AUTO_SWITCH" : "",
"PROJECT_EXPORT_ALL" : "",
"PROJECT_EXPORT_CLASS" : "",
"PROJECT_EXPORT_PACKAGE" : "",
"PROJECT_IMPORT_CLASS" : "",
"DEV_CRASH" : "",
"EDIT_AUTOCOMPLETE" : "Ctrl+Space",
"HELP_ABOUT" : "",
"HELP_REFERENCE" : "",
"HELP_TUTORIAL" : "",
}
class Ids:
def __init__(self):
self.shash ={}
self.idhash = {}
for m in MenuInfo:
id = wx.NewId()
setattr(self, m, id)
self.idhash[id] = m
if MenuInfo[m]=="":
self.shash[id] = ""
else:
self.shash[id] = "\t"+MenuInfo[m]
if wx.Platform == "__WXMAC__":
setattr(self, "FILE_EXIT", wx.ID_EXIT)
setattr(self, "HELP_ABOUT", wx.ID_ABOUT)
self.shash[wx.ID_EXIT] = ""
self.shash[wx.ID_ABOUT] = ""
class Shortcuts:
def __init__(self):
for m in MenuInfo:
if MenuInfo[m]=="":
setattr(self, m, "")
else:
setattr(self, m, "\t"+MenuInfo[m])
ids = Ids()
shortcuts = Shortcuts()
| Python |
# vim:ts=4:sw=4:noet:
""" Memory inspector window """
import wx
from c.remote.simpleobj import *
from c.ui.wxw.widgets.baseframe import BaseFrame
class InspectorObject:
def __init__(self, value, ptr=None):
self.value = value
self.ptr = ptr
self.expanded = False
def __repr__(self):
return "<%s@%s>" % (self.value, self.ptr)
class InspectWindow(BaseFrame):
def __init__(self, parent, mem, remote, ptr, name="Object"):
self.mem = mem
self.r = remote
self.ptr = ptr
self.obj = self.r.getObject(ptr)
cls = self.r.getObject(self.obj.cls)
clsName = self.r.getObject(cls.data[0]).asString()
windowName = "Inspect: %s (%d)" % (name, ptr)
BaseFrame.__init__(self, parent, windowName, size=(300, 350))
self.tree = wx.TreeCtrl(self)
root = self.tree.AddRoot("%s @ %d" % (clsName, self.obj.ptr))
self.tree.SetPyData(root, InspectorObject(clsName, self.obj.ptr))
self.font = wx.Font(10,
wx.FONTFAMILY_MODERN,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL)
self.objData = {}
self.AddTreeNodes(root,[InspectorObject("?")])
self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree)
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree)
self.Centre()
self.Show(True)
self.tree.Expand(root)
self.tree.SetItemFont(root, self.font)
def objectAsString(self, aobj):
if not isinstance(aobj,SimpleSmallInt):
acls = self.r.getObject(aobj.cls)
aclsName = self.r.getObject(acls.data[0]).asString()
if aclsName == "Symbol":
data = "#"
for d in aobj.data:
data += chr(d)
data += " (Symbol)"
dName = data
return [InspectorObject(dName),False]
elif aclsName == "String":
data = "'"
for d in aobj.data:
data += chr(d)
data += "' (String)"
dName = data
return [InspectorObject(dName),False]
elif aclsName == "Array":
dName = "%s (%d items)" % (aclsName, aobj.size)
elif aclsName == "ByteArray":
dName = "%s (%d bytes)" % (aclsName, aobj.size)
elif aclsName == "Undefined":
dName = "nil"
return [InspectorObject(dName),False]
else:
dName = "<%s>" % (aclsName)
return [InspectorObject(dName, aobj.ptr),True]
else:
dName = "%d (SmallInt)" % aobj.val
return [InspectorObject(dName),False]
def populateNodeChildren(self, node, obj):
items = []
mcls = self.r.getObject(obj.cls)
mclsName = self.r.getObject(mcls.data[0]).asString()
if not obj.bin:
if mclsName=="Dictionary":
keys = self.r.getObject(obj.data[0]).data
vals = self.r.getObject(obj.data[1]).data
for i,d in enumerate(vals):
aobj = self.r.getObject(d)
key = self.r.getObject(keys[i]).asString()
ostr, hasChildren = self.objectAsString(aobj)
ostr.value = "%s -> %s" % (key, ostr.value)
if hasChildren:
items.append([ostr,InspectorObject("?")])
else:
items.append(ostr)
else:
scls = self.mem.getGlobal(mclsName)
ivars = []
if (scls):
ivars = scls.getAllIvars()
maxlen = 0
for iv in ivars:
if len(iv)>maxlen:
maxlen = len(iv)
for i,d in enumerate(obj.data):
aobj = self.r.getObject(d)
ostr, hasChildren = self.objectAsString(aobj)
if i<len(ivars):
ostr.value = "%s: %s" % (ivars[i].ljust(maxlen+1),ostr.value)
if hasChildren:
items.append([ostr,InspectorObject("?")])
else:
items.append(ostr)
else:
data = ""
if mclsName=="Symbol":
data += "#"
else:
for d in obj.data:
data += "%d, " % d
items.append(InspectorObject(data))
self.AddTreeNodes(node, items)
def AddTreeNodes(self, parentItem, items):
for item in items:
if type(item) == str:
raise Exception("string!")
elif isinstance(item, InspectorObject):
iid = self.tree.AppendItem(parentItem, item.value)
self.tree.SetPyData(iid, item)
self.tree.SetItemFont(iid, self.font)
else:
newItem = self.tree.AppendItem(parentItem, item[0].value)
self.tree.SetPyData(newItem, item[0])
self.tree.SetItemFont(newItem, self.font)
self.AddTreeNodes(newItem, item[1:])
def OnItemExpanded(self, evt):
item = evt.GetItem()
inspobj = self.tree.GetPyData(item)
if not inspobj.expanded:
inspobj.expanded = True
if inspobj.ptr:
self.tree.DeleteChildren(item)
self.populateNodeChildren(item, self.r.getObject(inspobj.ptr))
def OnActivated(self, evt):
item = evt.GetItem()
inspobj = self.tree.GetPyData(item)
if inspobj.ptr:
InspectWindow(self, self.mem, self.r, inspobj.ptr)
| Python |
# vim:ts=4:sw=4:noet:
""" Stacktrace window """
import wx
from c.remote.simpleobj import *
from c.ui.wxw.widgets.baseframe import BaseFrame
from c.ui.wxw.inspector import InspectWindow
class ObjectLink(wx.HyperlinkCtrl):
def __init__(self, parent, obj):
wx.HyperlinkCtrl.__init__(self, parent, -1, str(obj), obj.loc)
col = wx.Colour(100,180,255)
col0 = wx.Colour( 87,157,253)
self.SetHoverColour(col)
self.SetNormalColour(col0)
self.SetVisitedColour(col0)
f = self.GetFont()
f.SetUnderlined(False)
self.SetFont(f)
class StackTraceWindow(BaseFrame):
def __init__(self, parent, remote, mem):
self.r = remote
self.parent = parent
self.mem = mem
BaseFrame.__init__(self, parent, "Stack Trace", size=(280, 320))
self.SetMinSize((280, 320))
self.panel = wx.Panel(self, -1)
self.noLibraryFrames = True
self.lblHdrError = wx.StaticText(self.panel, -1, "Error:")
self.lblError = wx.StaticText(self.panel, -1, "")
self.staticline1 = wx.StaticLine(self.panel, -1)
self.staticline2 = wx.StaticLine(self.panel, -1)
self.treeTrace = wx.TreeCtrl(self.panel, style=wx.TR_DEFAULT_STYLE|wx.TR_HIDE_ROOT)
self.root = self.treeTrace.AddRoot("Stack Trace")
self.treeTrace.SetIndent(0)
self.lblHdrRecv = wx.StaticText(self.panel, -1, "Receiver:")
self.lblHdrArgs = wx.StaticText(self.panel, -1, "Arguments:")
self.lblHdrTemps = wx.StaticText(self.panel, -1, "Temporaries:")
# props
ft = self.lblError.GetFont()
newft = wx.Font(ft.GetPointSize(), wx.DECORATIVE, wx.NORMAL, wx.BOLD, 0, ft.GetFaceName())
self.lblHdrError.SetFont(newft)
self.lblHdrRecv.SetFont(newft)
self.lblHdrArgs.SetFont(newft)
self.lblHdrTemps.SetFont(newft)
# layout
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.lblHdrError, 0, wx.ALIGN_RIGHT, 0)
sizer_1.Add(self.lblError, 0, wx.LEFT|wx.EXPAND, 5)
self.mainSizer.Add(sizer_1, 0, wx.ALL|wx.EXPAND, 5)
self.mainSizer.Add(self.staticline1, 0, wx.EXPAND, 0)
self.mainSizer.Add(self.treeTrace, 1, wx.EXPAND, 0)
self.mainSizer.Add(self.staticline2, 0, wx.EXPAND, 0)
self.recvSizer = wx.BoxSizer(wx.HORIZONTAL)
self.recvPanel = wx.Panel(self.panel, -1)
self.argsSizer = wx.BoxSizer(wx.HORIZONTAL)
self.argsPanel = wx.Panel(self.panel, -1)
self.tempsSizer = wx.BoxSizer(wx.HORIZONTAL)
self.tempsPanel = wx.Panel(self.panel, -1)
gridsizer_1 = wx.FlexGridSizer(3,2,5,5)
gridsizer_1.Add(self.lblHdrRecv, 0, wx.ALIGN_RIGHT, 0)
gridsizer_1.Add(self.recvPanel, 0, wx.EXPAND, 0)
gridsizer_1.Add(self.lblHdrArgs, 0, wx.ALIGN_RIGHT, 0)
gridsizer_1.Add(self.argsPanel, 0, wx.EXPAND, 0)
gridsizer_1.Add(self.lblHdrTemps, 0, wx.ALIGN_RIGHT, 0)
gridsizer_1.Add(self.tempsPanel, 0, wx.EXPAND, 0)
self.recvPanel.SetSizer(self.recvSizer)
self.argsPanel.SetSizer(self.argsSizer)
self.tempsPanel.SetSizer(self.tempsSizer)
self.mainSizer.Add(gridsizer_1, 0, wx.ALL|wx.EXPAND, 5)
self.panel.SetSizer(self.mainSizer)
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.treeTrace)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.Bind(wx.EVT_HYPERLINK, self.onHyperlink)
def onHyperlink(self, event):
url = event.GetURL()
if "@" in url:
name, ptr = url.split("@")
InspectWindow(self, self.mem, self.r, int(ptr), name)
def onClose(self, event):
self.Show(False)
def hide(self):
self.Show(False)
def showBacktrace(self,msg):
self.Show(True)
msg = msg.rstrip().strip("Error: ")
if "Runtime error (" in msg:
knownErrors = {
"BlkArg" : "Incorrect number of block arguments",
"ArrEmpty" : "Empty collection",
"NoElt" : "Invalid array index",
"NoKey" : "No key in dictionary",
"PrimFail" : "Fatal primitive error",
"SubclassResp" : "Subclass' responsibility",
"ArrIdx" : "Invalid array index",
"DivZero" : "Division by zero",
"Overflow" : "Numeric overflow",
}
rte = msg[18:-1]
if rte in knownErrors:
msg = knownErrors[rte]
self.lblError.SetLabel(msg)
self.treeTrace.DeleteChildren(self.root)
self.frames = self.r.backtrace(mem=self.mem)
ids = self.addFrames(self.frames)
if len(ids)>0:
self.treeTrace.SelectItem(ids[0], True)
self.treeTrace.SetFocus()
def addFrames(self, frames):
ids = []
for i,frame in enumerate(frames):
clsItem = self.parent.project.controller.getProjectItem(frame.incls)
if clsItem:
if self.noLibraryFrames and clsItem.pkgitem.name!="Project":
continue
text = "%d: %s>>%s at line %d" % (i, frame.incls, frame.meth, frame.line)
ids.append(self.treeTrace.AppendItem(self.root, text))
return ids
def selectFrame(self, text):
sname = text.split(":")
if len(sname)==1:
return
if sname[0]=="arguments":
return
frame = self.frames[int(sname[0])]
r = frame.args[0]
self.recvSizer.Clear(True)
self.recvSizer.Add(ObjectLink(self.recvPanel, r), 0, wx.RIGHT|wx.EXPAND, 5)
self.argsSizer.Clear(True)
for a in frame.args[1:]:
self.argsSizer.Add(ObjectLink(self.argsPanel, a), 0, wx.RIGHT|wx.EXPAND, 5)
self.tempsSizer.Clear(True)
for t in frame.temps:
self.tempsSizer.Add(ObjectLink(self.tempsPanel, t), 0, wx.RIGHT|wx.EXPAND, 5)
self.tempsPanel.Layout()
self.parent.showSource(frame.incls, frame.meth, frame.line-1)
self.recvSizer.Fit(self.recvPanel)
self.argsSizer.Fit(self.argsPanel)
self.tempsSizer.Fit(self.tempsPanel)
def OnSelChanged(self, evt):
item = evt.GetItem()
self.selectFrame(self.treeTrace.GetItemText(item))
| Python |
# vim:ts=4:sw=4:noet:
""" 2D Simulator Renderer """
import wx
import time
import math
from c.ui.wxw.common import *
from c.simulator.simulator import Simulator
SIM_FPS = 15
if wx.Platform=="__WXMSW__":
Paint = wx.BufferedPaintDC
else:
Paint = wx.PaintDC
class SimCanvas(wx.Panel):
def __init__(self, parent, mc):
if wx.Platform=="__WXMAC__":
wx.Panel.__init__(self, parent, -1)
else:
wx.Panel.__init__(self, parent, -1, style = wx.BORDER_SUNKEN)
self.sim = Simulator(mc)
self.mc = mc
self.size = (100,100)
self.saytext = ""
self.drawTime = 0
self.tstart = time.time()
self.frames = 0
self.oldt = time.time()
self.timer = wx.Timer(self, -1)
self.bgColour = wx.Colour(231, 235, 255)
self.bg = wx.EmptyBitmap(100,100)
self.drawBot = True
self.Bind(wx.EVT_TIMER, self.OnTimer)
self.Bind(wx.EVT_PAINT, self.OnDraw)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
self.timer.Start(1000/SIM_FPS)
def __del__(self):
self.sim.shutdown()
def OnEraseBackground(self, event):
pass
def OnRightClick(self, event):
if not hasattr(self, "setBackColour"):
self.setBackColourId = wx.NewId()
self.toggleRobotId = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnBackColour, id=self.setBackColourId)
self.Bind(wx.EVT_MENU, self.OnToggleRobot, id=self.toggleRobotId)
menu = wx.Menu()
menu.Append(self.setBackColourId, "Set background colour")
if self.drawBot:
menu.Append(self.toggleRobotId, "Hide robot")
else:
menu.Append(self.toggleRobotId, "Show robot")
self.PopupMenu(menu)
menu.Destroy()
def OnBackColour(self, event):
dlg = wx.ColourDialog(self)
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetColourData()
self.bgColour = data.GetColour().Get()
dlg.Destroy()
def OnToggleRobot(self, event):
self.drawBot = not self.drawBot
def OnSize(self, event):
self.size = self.GetClientSize()
if self.size[0]>50:
self.sim.resetPos = [x/2 for x in self.size]
self.sim.maxPos = self.size
self.bg = wx.EmptyBitmap(self.size[0], self.size[1])
self.sim.linesDrawn = 0
event.Skip()
def OnTimer(self, evt):
newt = time.time()
dt = newt-self.oldt
self.oldt = newt
self.sim.update(dt)
if not self.sim.pbqueue.empty():
self.saytext = self.sim.pbqueue.get()
self.mc.view.logMessage("> %s\n" % self.saytext)
self.Refresh()
def OnDraw(self, evt):
dstart = time.time()
dc = Paint(self)
try:
gc = wx.GraphicsContext.Create(dc)
except NotImplementedError:
dc.DrawText("NONE FOR YOU", 25,25)
return
font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetWeight(wx.BOLD)
gc.SetFont(font)
gc.SetBrush(wx.Brush(self.bgColour))
path = gc.CreatePath()
path.AddRectangle(0,0,self.size[0],self.size[1])
gc.PushState()
gc.FillPath(path)
gc.PopState()
# background -----
if self.sim.needsReset:
self.bg = wx.EmptyBitmap(self.size[0], self.size[1])
memdc = wx.MemoryDC()
memdc.SelectObject(self.bg)
memgc = wx.GraphicsContext.Create(memdc)
memgc.SetBrush(wx.Brush(self.bgColour))
if self.sim.needsReset:
self.sim.needsReset = False
path = memgc.CreatePath()
path.AddRectangle(0,0,self.size[0],self.size[1])
memgc.PushState()
memgc.FillPath(path)
memgc.PopState()
if len(self.sim.lines)>1:
if self.sim.linesDrawn==0:
prev = self.sim.lines[0][0]
else:
prev = self.sim.lines[self.sim.linesDrawn-1][0]
while len(self.sim.lines)-self.sim.linesDrawn:
point, col, width, down = self.sim.lines[self.sim.linesDrawn]
if down:
memgc.SetPen(wx.Pen(wx.Colour(*[x*255 for x in col]), width))
memgc.StrokeLine(prev[0], prev[1], point[0], point[1])
prev = point
self.sim.linesDrawn += 1
gc.DrawBitmap(self.bg, 0, 0, self.size[0], self.size[1])
# background -----
"""
gc.PushState()
if len(self.sim.lines)>1:
prev = self.sim.lines[0][0]
for point, col, width, down in self.sim.lines[1:]:
if down:
gc.SetPen(wx.Pen(wx.Colour(*[x*255 for x in col]), width))
gc.StrokeLine(prev[0], prev[1], point[0], point[1])
prev = point
if down:
gc.StrokeLine(prev[0], prev[1], self.sim.pos[0], self.sim.pos[1])
gc.PopState()
"""
if self.drawBot:
"""
r = 20.0
w = 7.0
sa = math.radians(30)
rw = math.sqrt(r*r + w*w)
xc = self.sim.pos[0] - r*math.sin(self.sim.theta)
yc = self.sim.pos[1] + r*math.cos(self.sim.theta)
xl = self.sim.pos[0] - rw*math.sin(self.sim.theta+sa)
yl = self.sim.pos[1] + rw*math.cos(self.sim.theta+sa)
xr = self.sim.pos[0] - rw*math.sin(self.sim.theta-sa)
yr = self.sim.pos[1] + rw*math.cos(self.sim.theta-sa)
self.sim.lineSensor[0] = dc.GetPixel(xc,yc)!=self.bgColour
self.sim.lineSensor[1] = dc.GetPixel(xl,yl)!=self.bgColour
self.sim.lineSensor[2] = dc.GetPixel(xr,yr)!=self.bgColour
#print self.sim.lineSensor
"""
w = self.sim.radius
shd = gc.CreatePath()
shd.AddArc(0,0,w/2 + 2,math.radians(0),math.radians(360))
sqr = gc.CreatePath()
sqr.AddArc(0,0,w/2,math.radians(0),math.radians(360))
tri = gc.CreatePath()
tri.AddArc(0,0,w*0.4,math.radians(-30),math.radians(210))
tri2 = gc.CreatePath()
tri2.AddArc(0,-4,w*0.2,math.radians(0),math.radians(360))
bubble = gc.CreatePath()
tw, th = gc.GetTextExtent(self.saytext)
bw = max(0,tw-4)
bubble.AddArc(15,-15,8,math.radians(90),math.radians(270))
bubble.AddLineToPoint(15+bw,-23)
bubble.AddArc(15+bw,-15,8,math.radians(270),math.radians(90))
bubble.AddLineToPoint(15,-7)
gc.PushState()
gc.Translate(self.sim.pos[0], self.sim.pos[1])
gc.Rotate(self.sim.theta)
gc.SetBrush(wx.Brush(wx.Colour(0,0,0, 128)))
gc.FillPath(shd)
gc.SetBrush(wx.Brush(wx.Colour(255,255,255)))
gc.FillPath(sqr)
gc.SetBrush(wx.Brush(wx.Colour(0xFA,0x4E, 0x23)))
gc.FillPath(tri)
gc.FillPath(tri2)
gc.PopState()
if len(self.saytext)>0:
gc.PushState()
gc.Translate(self.sim.pos[0], self.sim.pos[1])
gc.SetPen(wx.Pen(wx.Colour(0x33,0x33,0x33,64)))
gc.SetBrush(wx.Brush(wx.Colour(0xFF,0xFF,0xFF,192)))
gc.FillPath(bubble)
gc.StrokePath(bubble)
gc.DrawText(self.saytext, 13,-15-(th/2))
gc.PopState()
# measurements
dtime = time.time()-dstart
self.drawTime = (self.drawTime+dtime)/2.0
if self.frames==0:
self.tstart = time.time()-0.01
self.frames += 1
trun = time.time()-self.tstart
fps = self.frames/trun
#gc.DrawText("%0.1fms %0.1ffps" % (self.drawTime*1000, fps), 10,10)
| Python |
# vim:ts=4:sw=4:noet:
""" Method info bar """
import wx
from c.ui.wxw.platform import UITweaks
from c.ui.wxw.common import loadWxImage
class MethodBar(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
hbox = wx.BoxSizer(wx.HORIZONTAL)
self.methLabel = wx.TextCtrl(self, -1, "")
self.methLabel.SetForegroundColour(wx.Colour(0x20, 0x20, 0x20))
self.methLabel.SetMinSize((200, UITweaks.methbarHeight))
self.methLabel.SetBackgroundColour(wx.Colour(0xE8, 0xE8, 0xE8))
self.methLabel.SetFont(wx.Font(
11,
wx.FONTFAMILY_SWISS,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD))
self.methLabel.SetEditable(False)
hbox.Add(self.methLabel, 1, wx.ALL | wx.EXPAND, UITweaks.methpad)
editSourceId = wx.NewId()
editDocsId = wx.NewId()
if wx.Platform=="__WXMAC__":
self.SetBackgroundColour(wx.Colour(0xE8, 0xE8, 0xE8))
self.SetSizer(hbox)
def setMethodName(self, name):
self.methLabel.SetValue(name)
| Python |
# vim:ts=4:sw=4:noet:
""" Custom view splitter """
import wx
class MainSplitter(wx.SplitterWindow):
def __init__(self, parent):
wx.SplitterWindow.__init__(self, parent, -1,
style = wx.SP_LIVE_UPDATE #|wx.SP_3DSASH
)
if wx.Platform=="__WXMAC__":
self.SetSashSize(1)
self.SetBackgroundColour(wx.Color(0x40,0x40,0x40))
| Python |
# vim:ts=4:sw=4:noet:
""" Validated input box """
import wx
from c.ui.wxw.common import loadWxImage, getProperPath
from c.base.platform import Platform
class CheckedEntry(wx.Panel):
def __init__(self, parent, callbkCheck, callbkDone, initVal=""):
wx.Panel.__init__(self, parent, -1)
hbox = wx.BoxSizer(wx.HORIZONTAL)
self.callbkDone = callbkDone
self.callbkCheck = callbkCheck
self.textctrl = wx.TextCtrl(self, -1, initVal, style = wx.TE_PROCESS_ENTER)
self.textctrl.Bind(wx.EVT_TEXT, self.onUpdate)
self.textctrl.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
self.textctrl.SetFocus()
self.imGood = wx.Bitmap(getProperPath(Platform.getDataFilePath("tick.png")))
self.imBad = wx.Bitmap(getProperPath(Platform.getDataFilePath("cross.png")))
self.statusImage = wx.StaticBitmap(self, -1, self.imBad)
hbox.Add(self.textctrl, 1, 0, 0)
hbox.Add(self.statusImage, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 10)
self.SetSizer(hbox)
def GetValue(self):
return self.textctrl.GetValue()
def onUpdate(self, evt):
txt = self.textctrl.GetValue()
ok, result = self.callbkCheck(txt)
if ok:
self.statusImage.SetBitmap(self.imGood)
self.statusImage.SetToolTip(wx.ToolTip("Method name OK"))
else:
self.statusImage.SetBitmap(self.imBad)
self.statusImage.SetToolTip(wx.ToolTip(result))
def onEnter(self, evt):
self.callbkDone()
| Python |
# vim:ts=4:sw=4:noet:
""" Main menubar """
import wx
from c.ui.wxw.ids import ids, shortcuts
class MainMenu(wx.MenuBar):
def __init__(self, parent):
wx.MenuBar.__init__(self)
# file menu
fileMenu = wx.Menu()
self.addItem(fileMenu, ids.FILE_NEW_PROJECT, "New Project")
fileMenu.AppendSeparator()
self.addItem(fileMenu, ids.FILE_OPEN, "Open ...")
self.examplesMenu = wx.Menu()
self.addSubMenu(fileMenu, ids.FILE_EXAMPLES, self.examplesMenu, "Open Example")
self.addItem(fileMenu, ids.FILE_SAVE, "Save", False)
self.addItem(fileMenu, ids.FILE_SAVE_AS, "Save As ...", False)
fileMenu.AppendSeparator()
self.addItem(fileMenu, ids.FILE_EXIT, "Exit")
# edit menu
editMenu = wx.Menu()
self.addItem(editMenu, ids.EDIT_UNDO, "Undo", False)
self.addItem(editMenu, ids.EDIT_REDO, "Redo", False)
editMenu.AppendSeparator()
self.addItem(editMenu, ids.EDIT_CUT, "Cut", False)
self.addItem(editMenu, ids.EDIT_COPY, "Copy", False)
self.addItem(editMenu, ids.EDIT_PASTE, "Paste", False)
# view menu
viewMenu = wx.Menu()
self.addItem(viewMenu, ids.VIEW_CONSOLE, "Toggle Console")
self.addItem(viewMenu, ids.VIEW_DOCUMENTATION, "Show Docs")
viewMenu.AppendSeparator()
self.addItem(viewMenu, ids.VIEW_JUMPTO, "Jump To ...", False)
# project menu
projectMenu = wx.Menu()
self.addItem(projectMenu, ids.PROJECT_COMPILE, "Check")
self.addItem(projectMenu, ids.PROJECT_RUN, "Run")
self.addItem(projectMenu, ids.PROJECT_STOP, "Stop")
projectMenu.AppendSeparator()
self.addItem(projectMenu, ids.PROJECT_NEW_CLASS, "New Class")
self.addItem(projectMenu, ids.PROJECT_NEW_METHOD, "New Method")
projectMenu.AppendSeparator()
self.addItem(projectMenu, ids.PROJECT_IMPORT_CLASS, "Import Class ...")
projectMenu.AppendSeparator()
self.addCheckItem(projectMenu, ids.PROJECT_EDIT_LIBRARY, "Editable Library")
self.addCheckItem(projectMenu, ids.PROJECT_AUTO_SWITCH, "Switch to Robot on Run")
# dev menu
devMenu = wx.Menu()
self.addItem(devMenu, ids.DEV_CRASH, "Crash")
self.addItem(devMenu, ids.VIEW_GET_INFO, "Get Info")
self.addItem(devMenu, ids.PROJECT_EXPORT_ALL, "Export All Classes")
# help menu
helpMenu = wx.Menu()
helpMenu.Append(ids.HELP_REFERENCE, "Reference Manual"+shortcuts.HELP_REFERENCE)
helpMenu.Append(ids.HELP_TUTORIAL, "Tutorial"+shortcuts.HELP_TUTORIAL)
helpMenu.AppendSeparator()
helpMenu.Append(ids.HELP_ABOUT, "About"+shortcuts.HELP_ABOUT)
self.Append(fileMenu, "&File")
self.Append(editMenu, "&Edit")
self.Append(viewMenu, "&View")
self.Append(projectMenu, "&Project")
#self.Append(devMenu, "&Dev")
self.Append(helpMenu, "&Help")
self.examples = {}
def addItem(self, menu, id, text, enabled=True):
sc = ids.shash[id]
menu.Append(id, text+sc)
menu.Enable(id, enabled)
def addSubMenu(self, menu, id, submenu, text, enabled=True):
sc = ids.shash[id]
menu.AppendMenu(id, text+sc, submenu)
menu.Enable(id, enabled)
def addCheckItem(self, menu, id, text, enabled=True):
sc = ids.shash[id]
menu.AppendCheckItem(id, text+sc)
menu.Enable(id, enabled)
def addExample(self, name, filename):
id = wx.NewId()
self.examples[id] = filename
self.examplesMenu.Append(id, name)
| Python |
# vim:ts=4:sw=4:noet:
""" Toolbar """
import wx
import c.ui.wxw.common as common
from c.ui.wxw.ids import ids, shortcuts
class MainToolBar(wx.ToolBar):
def __init__(self, parent):
if wx.Platform == '__WXMAC__':
wx.ToolBar.__init__(self, parent, style=(
wx.TB_HORIZONTAL|wx.NO_BORDER|wx.TB_FLAT|wx.TB_TEXT))
self.SetMargins(wx.Size(5, 4))
else:
wx.ToolBar.__init__(self, parent, style=(
wx.TB_HORIZONTAL|wx.NO_BORDER|wx.TB_FLAT))
self.SetToolBitmapSize(wx.Size(32, 32))
self.addButton(ids.PROJECT_RUN,
"Run", "IM_ToolRun.png", "Run Program")
self.addButton(ids.PROJECT_STOP,
"Stop", "IM_ToolStop.png", "Stop Program")
self.addButton(ids.PROJECT_COMPILE,
"Check", "IM_ToolCompile.png", "Check Code")
self.addButton(ids.VIEW_DOCUMENTATION,
"Docs", "IM_ToolDocs.png", "Show Documentation")
self.Bind(wx.EVT_TOOL, parent.OnToolClick)
def addButton(self, id, name, image, help):
self.AddLabelTool(
id,
name,
common.loadWxImage(image),
shortHelp=help,
longHelp=help)
| Python |
# vim:ts=4:sw=4:noet:
""" Base Frame class """
import wx
from c.base.platform import Platform
from c.ui.wxw.common import getProperPath
class BaseFrame(wx.Frame):
def __init__(self, parent, name, **kwargs):
wx.Frame.__init__(self, parent, -1, name, **kwargs)
icon = wx.Icon(getProperPath(Platform.getDataFilePath("fox.ico")), wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
self.firstShow = True
def Show(self, s):
if s and wx.Platform=="__WXMAC__" and self.firstShow:
self.Centre()
self.firstShow = False
wx.Frame.Show(self,s)
| Python |
"""
Miscellaneous Widgets
"""
from toolbar import MainToolBar
from mainmenu import MainMenu
from methodbar import MethodBar
from splitter import MainSplitter
from baseframe import BaseFrame
from checkedentry import CheckedEntry
| Python |
# vim:ts=4:sw=4:noet:
""" Class info panel """
import wx
from c.ui.wxw.widgets.checkedentry import CheckedEntry
from c.base.support import CoreException
import re
class NewIvarDialog(wx.Dialog):
def __init__(self, parent, supername="", clsname=""):
wx.Dialog.__init__(self, parent, -1, "New Instance Variable")
self.mw = parent
self.textctrl = CheckedEntry(self, self.doCheck, self.doDone, clsname)
self.ok = wx.Button(self, wx.ID_OK, "OK")
self.ok.Enable(False)
cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
dlgsizer = wx.BoxSizer(wx.VERTICAL)
dlgsizer.Add(self.textctrl, 1, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 10)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(self.ok)
btnsizer.AddButton(cancel)
btnsizer.Realize()
dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 10)
self.SetSizer(dlgsizer)
self.Fit()
self.Centre()
def GetValue(self):
return self.textctrl.GetValue()
def doCheck(self, val):
if val in [x.strip(" -") for x in self.mw.items]:
self.ok.Enable(False)
return False, "Instance name already exists"
if val=="":
self.ok.Enable(False)
return False, "Instance name must be non-empty"
if not re.match("^[a-zA-Z][a-zA-Z0-9]*$", val):
self.ok.Enable(False)
return False, "Invalid instance name"
self.ok.Enable(True)
return True, ""
def doDone(self):
if self.ok.IsEnabled():
self.EndModal(wx.ID_OK)
class VarListPanel(wx.Panel):
def __init__(self, parent, mw): #, obj):
wx.Panel.__init__(self, parent)
self.mw = mw
self.obj = None
self.items = []
self.editable = True
psizer = wx.BoxSizer(wx.VERTICAL)
varListId = wx.NewId()
self.varList = wx.ListBox(self, varListId, choices=self.items)
self.varList.Bind(wx.EVT_LISTBOX, self.onListBox, id=varListId)
psizer.Add(self.varList, 1, wx.ALL|wx.EXPAND, 10)
addId = wx.NewId()
self.add = wx.Button(self, addId, "Add new ...")
self.add.SetDefault()
self.Bind(wx.EVT_BUTTON, self.onAdd, id=addId)
remId = wx.NewId()
self.remove = wx.Button(self, remId, "Remove")
self.remove.Enable(False)
self.Bind(wx.EVT_BUTTON, self.onRemove, id=remId)
btnsizer = wx.BoxSizer(wx.HORIZONTAL)
btnsizer.Add(self.add, 0, wx.RIGHT, 10)
btnsizer.Add(self.remove)
psizer.Add(btnsizer, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT, 10)
psizer.Fit(self)
self.SetSizer(psizer)
self.Fit()
self.Layout()
def setEditable(self, editable):
self.editable = editable
if editable:
self.add.Enable(True)
else:
self.remove.Enable(False)
self.add.Enable(False)
def setObject(self, obj):
self.obj = obj
self.items = obj.getAllIvars()
for i in range(len(self.items)-len(obj.instanceNames)):
self.items[i] = "- "+self.items[i]
self.varList.Clear()
self.varList.AppendItems(self.items)
def onListBox(self, event):
sel = self.varList.GetSelection()
if (sel == wx.NOT_FOUND or
sel < (len(self.obj.getAllIvars())-len(self.obj.instanceNames)) or
not self.editable):
self.remove.Enable(False)
else:
self.remove.Enable(True)
def onAdd(self, event):
dialog = NewIvarDialog(self)
res = dialog.ShowModal()
if res == wx.ID_OK:
ivar = dialog.GetValue()
self.varList.AppendAndEnsureVisible(ivar)
self.items.append(ivar)
self.obj.addIvar(ivar)
def onRemove(self, event):
sel = self.varList.GetSelection()
if sel != wx.NOT_FOUND:
self.varList.Delete(sel)
self.obj.removeIvar(self.items[sel])
class ClassPanel(wx.Panel):
def __init__(self, parent, mc):
wx.Panel.__init__(self, parent, -1)
if wx.Platform=="__WXMAC__":
self.SetBackgroundColour(wx.Color(232,232,232))
self.mc = mc
vbox = wx.BoxSizer(wx.VERTICAL)
self.lblHdrName = wx.StaticText(self, -1, "Name")
self.lblName = wx.StaticText(self, -1, "")
self.lblHdrSuper = wx.StaticText(self, -1, "Superclass")
self.lblSuper = wx.StaticText(self, -1, "")
self.static_line_1 = wx.StaticLine(self, -1)
self.varsNotebook = wx.Notebook(self, -1)
self.ivarPanel = VarListPanel(self.varsNotebook, self)
self.varsNotebook.AddPage(self.ivarPanel, "Instance")
self.cvarPanel = VarListPanel(self.varsNotebook, self)
self.varsNotebook.AddPage(self.cvarPanel, "Class")
ft = self.lblName.GetFont()
newft = wx.Font(ft.GetPointSize(), wx.DECORATIVE, wx.NORMAL, wx.BOLD, 0, ft.GetFaceName())
self.lblHdrName.SetFont(newft)
self.lblHdrSuper.SetFont(newft)
grid_sizer_1 = wx.FlexGridSizer(2, 2, 5, 5)
grid_sizer_1.Add(self.lblHdrName, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblName, 0, wx.EXPAND, 0)
grid_sizer_1.Add(self.lblHdrSuper, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblSuper, 0, wx.EXPAND, 0)
vbox.Add(grid_sizer_1, 0, wx.ALL|wx.EXPAND, 5)
vbox.Add(self.static_line_1, 0, wx.EXPAND, 0)
vbox.Add(self.varsNotebook, 1, wx.ALL|wx.EXPAND, 5)
self.SetSizer(vbox)
vbox.Fit(self)
self.Layout()
self.SetMinSize(vbox.GetMinSize())
self.Fit()
def setObject(self, obj, inLibrary):
self.lblName.SetLabel(obj.name)
supername = "nil"
if obj.parent != self.mc.mem.nilObject:
supername = obj.parent.name
self.lblSuper.SetLabel(supername)
self.ivarPanel.setObject(obj)
self.cvarPanel.setObject(obj.cls)
editable = (not inLibrary) or self.mc.isLibraryEditable()
self.ivarPanel.setEditable(editable)
self.cvarPanel.setEditable(editable)
| Python |
# vim:ts=4:sw=4:noet:
""" Project browser view (tree/sidebar) """
import wx
import os
import common
from c.compiler.spy import *
from wx.lib import dialogs
from c.ui.projectcontroller import *
from c.ui.wxw.dialogs import NewClassDialog, NewMethodDialog, RenameMethodDialog
from c.ui.wxw.ids import ids
from c.ui.wxw.events import *
class ProjectBrowser(wx.TreeCtrl):
def __init__(self, parent, mainwin, mem):
wx.TreeCtrl.__init__(
self, parent, -1,
wx.DefaultPosition, wx.DefaultSize,
wx.TR_DEFAULT_STYLE|wx.TR_HIDE_ROOT)
self.il = wx.ImageList(16,16)
self.addIcons({
"package": "package.png",
"category": "bricks.png",
"class": "brick.png",
"method": "cog.png",
"cmethod": "cog_go.png",
"method-error": "cog_error.png",
"robot": "car.png",
"robots": "server.png",
})
self.SetImageList(self.il)
self.SetIndent(10)
self.mw = mainwin
if wx.Platform == "__WXMAC__":
self.SetBackgroundColour(wx.Color(0xD1,0xD7,0xE2))
self.root = self.AddRoot("root")
self.SetPyData(self.root, None)
self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick)
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)
self.mem = mem
self.controller = ProjectController(self, mainwin, mem)
self.lastSelected = None
self.libEditable = self.mw.controller.isLibraryEditable()
def __checkLastSelected(self):
if not self.lastSelected:
self.lastSelected = self.GetSelection()
return self.GetPyData(self.lastSelected)
def setLibraryEditable(self, v):
self.libEditable = v
item = self.GetSelection()
if item:
self.controller.selectItem(item)
def addIcons(self, ih):
self.icons = {}
for name in ih:
self.icons[name] = self.il.Add(common.loadWxImage(ih[name]))
def setItemIcon(self, item, icon):
self.SetItemImage(item, self.icons[icon], which = wx.TreeItemIcon_Normal)
def addItem(self, itemName, parent=None, icontype="package", pdata=None):
if not parent:
parent = self.root
child = self.AppendItem(parent, itemName)
self.SetPyData(child, pdata)
if wx.Platform == "__WXMAC__":
self.SetItemFont(child, wx.Font(
11,
wx.FONTFAMILY_DEFAULT,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL))
self.SetItemImage(child, self.icons[icontype], which = wx.TreeItemIcon_Normal)
return child
def OnCompareItems(self, item1, item2):
it1 = self.GetPyData(item1).type
it2 = self.GetPyData(item2).type
if it1 < it2: return -1
if it1 > it2: return 1
t1 = self.GetItemText(item1)
t2 = self.GetItemText(item2)
if t1 < t2: return -1
if t1 > t2: return 1
return 0
def OnRightClick(self, event):
itemId = self.HitTest(event.GetPoint())[0]
self.lastSelected = itemId
# only do this part the first time so the events are only bound once
if not hasattr(self, "getInfoId"):
self.getInfoId = ids.VIEW_GET_INFO
self.renameId = wx.NewId()
self.deleteId = ids.FILE_DELETE
self.newClassId = ids.PROJECT_NEW_CLASS
self.newMethodId = ids.PROJECT_NEW_METHOD
self.subclassId = wx.NewId()
self.disconnectId = wx.NewId()
self.exportClassId = ids.PROJECT_EXPORT_CLASS
self.exportPackageId = ids.PROJECT_EXPORT_PACKAGE
self.Bind(wx.EVT_MENU, self.OnGetInfo, id=self.getInfoId)
self.Bind(wx.EVT_MENU, self.OnRename, id=self.renameId)
self.Bind(wx.EVT_MENU, self.OnDelete, id=self.deleteId)
self.Bind(wx.EVT_MENU, self.OnNewMethod, id=self.newMethodId)
self.Bind(wx.EVT_MENU, self.OnSubclass, id=self.subclassId)
self.Bind(wx.EVT_MENU, self.OnExportClass, id=self.exportClassId)
self.Bind(wx.EVT_MENU, self.OnExportPackage, id=self.exportPackageId)
itype = self.GetItemPyData(itemId).type
iname = self.GetItemPyData(itemId).name
obj = self.GetItemPyData(itemId).obj
menu = wx.Menu()
show = False
if itype == "package" and iname == "Project":
menu.Append(self.newClassId, "New Class...")
menu.Append(self.exportPackageId, "Export ...")
show = True
elif itype == "class":
if self.libEditable or (not obj.inLibrary()):
menu.Append(self.newMethodId, "New Method...")
menu.AppendSeparator()
menu.Append(self.subclassId, "Subclass...")
menu.Append(self.deleteId, "Delete")
menu.Append(self.exportClassId, "Export")
else:
menu.Append(self.subclassId, "Subclass...")
menu.Append(self.exportClassId, "Export")
show = True
elif itype == "cmethod":
if self.libEditable or (not obj.incls.inLibrary()):
menu.Append(self.deleteId, "Delete")
menu.Append(self.renameId, "Rename...")
show = True
elif itype == "method":
if self.libEditable or (not obj.incls.inLibrary()):
menu.Append(self.deleteId, "Delete")
menu.Append(self.renameId, "Rename...")
show = True
elif itype == "robot":
menu.Append(self.getInfoId, "Get Info")
show = True
if show:
self.PopupMenu(menu)
menu.Destroy()
def OnSelChanged(self, event):
self.controller.selectItem(event.GetItem())
def OnRename(self, event):
pitem = self.__checkLastSelected()
if pitem:
clsitem = pitem.clsitem
oldsig = pitem.obj.sig
oldname = pitem.obj.name
isclsmeth = pitem.obj.incls.name[:4]=="Meta"
while 1:
dialog = RenameMethodDialog(self.mw, clsitem.obj, oldsig, isclsmeth)
res = dialog.ShowModal()
if res == wx.ID_OK:
x, methsig = dialog.GetValue() # ignore isclsmeth for now
cls = clsitem.obj
methtype = "method"
if isclsmeth:
cls = cls.cls
methtype = "cmethod"
methcount = len(cls.methods)
if cls.hasMethod(methsig):
dialogs.alertDialog(dialog,
"Class '%s' already has a method '%s'" % (cls.name, methsig),
"Method Exists")
else:
self.mw.controller.compiler.deleteCachedIRMethod(cls.name, oldname)
meth = self.controller.newMethod(cls, methsig)
meth.source = pitem.obj.source
meth.docs = pitem.obj.docs
self.mw.onProjectSelectItem(meth)
cls.removeMethod(pitem.name)
self.controller.removeMethodItem(pitem)
self.controller.addMethodItem(clsitem, meth, methtype)
self.mem.removeMessage(oldname)
self.mem.addMessage(meth.name)
cls.addMethod(meth.name, meth)
pitem = self.GetPyData(self.GetSelection())
pitem.deselect(forceCompile=True)
break
dialog.Destroy()
else:
dialog.Destroy()
break
self.lastSelected = None
self.controller.changed = True
def OnSubclass(self, event):
pitem = self.__checkLastSelected()
self.OnNewClass(None, pitem.name)
self.lastSelected = None
def OnDelete(self, event):
pitem = self.__checkLastSelected()
pitem.deleted = True
if pitem:
if pitem.type=="method":
self.controller.selectItem(pitem.clsitem.ui)
cls = pitem.clsitem.obj
cls.removeMethod(pitem.name)
self.controller.removeMethodItem(pitem)
self.mw.controller.deleteMethod(pitem.obj)
elif pitem.type=="cmethod":
self.controller.selectItem(pitem.clsitem.ui)
cls = pitem.clsitem.obj.cls
cls.removeMethod(pitem.name)
self.controller.removeMethodItem(pitem)
self.mw.controller.deleteMethod(pitem.obj)
elif pitem.type=="class":
self.controller.selectItem(pitem.pkgitem.ui)
self.mem.removeGlobal(pitem.name)
self.mem.removeGlobal("Meta"+pitem.name)
self.controller.removeClassItem(pitem)
self.lastSelected = None
def OnGetInfo(self, event):
pitem = self.__checkLastSelected()
self.controller.getInfo(pitem)
self.lastSelected = None
def OnExportClass(self, event):
pitem = self.__checkLastSelected()
if pitem and pitem.type=="class":
pitem.obj.fileOut(os.getcwd())
def OnExportPackage(self, event):
pitem = self.__checkLastSelected()
if pitem and pitem.type=="package":
dial = wx.DirDialog(self.mw, "Select Export Directory", os.getcwd())
res = dial.ShowModal()
if res == wx.ID_OK:
self.controller.exportPackage(self.lastSelected, dial.GetPath())
def OnNewMethod(self, event):
pitem = self.__checkLastSelected()
defclass = None
if pitem:
if pitem.type=="class":
defclass = pitem.name
elif "method" in pitem.type:
defclass = pitem.clsitem.name
classes = self.controller.getEditableClasses()
if defclass not in classes:
defclass = None
methsig = ""
isclsmeth = False
while 1:
dialog = NewMethodDialog(self.mw, classes, defclass, methsig, isclsmeth)
res = dialog.ShowModal()
if res == wx.ID_OK:
clsname, isclsmeth, methsig = dialog.GetValue()
defclass = clsname
clsitem = self.controller.getProjectItem(clsname)
createOk, meth, methtype = self.controller.createNewMethod(
methsig, clsname, isclsmeth)
if not createOk:
if meth == "toomany":
dialogs.alertDialog(dialog,
"Class '%s' has too many methods" % (clsitem.obj.name),
"Too Many Methods")
dialog.Destroy()
break
elif meth == "exists":
dialogs.alertDialog(dialog,
"Class '%s' already has a method '%s'" % (clsitem.obj.name, methsig),
"Method Exists")
else:
self.controller.addMethodItem(clsitem, meth, methtype)
break
dialog.Destroy()
else:
dialog.Destroy()
break
self.lastSelected = None
self.controller.changed = True
def OnNewClass(self, event, supername="Object"):
clsname = ""
classes = self.controller.getAllClasses()
while 1:
dialog = NewClassDialog(self.mw, classes, supername, clsname)
res = dialog.ShowModal()
if res == wx.ID_OK:
supername, clsname = dialog.GetValue()
if clsname in classes:
dialogs.alertDialog(dialog,
"Class '%s' already exists" % (clsname),
"Class Exists")
else:
cls = self.controller.createNewClass(clsname, supername)
self.mem.addGlobal("Meta"+clsname, cls.cls)
pkg = self.controller.projectPkg
self.controller.addClassItem(pkg, cls)
break
dialog.Destroy()
else:
dialog.Destroy()
break
| Python |
# vim:ts=4:sw=4:noet:
""" Main window view"""
import wx
import os
import sys
import logging
import webbrowser
from c.base.version import *
from c.base.platform import Platform
from c.base.attribute import attribute
from c.compiler.compiler import Compiler
from c.ui.wxw.ids import ids, shortcuts
from c.ui.wxw.console import ConsoleWindow
from c.ui.wxw.docwindow import DocumentationWindow
from c.ui.wxw.stacktrace import StackTraceWindow
from c.ui.wxw.simwindow2d import SimCanvas
from c.ui.wxw.classpanel import ClassPanel
from c.ui.wxw.editor import Editor
from c.ui.wxw.projectbrowser import *
from c.ui.wxw.platform import UITweaks
from c.ui.wxw.dialogs import NewProjectDialog, JumpToDialog
from c.ui.wxw.widgets import MainToolBar, MainMenu, MethodBar, MainSplitter, BaseFrame
from c.ui.wxw.introwindow import IntroWindow
from c.ui.maincontroller import MainController, UILogger
class MainWindow(BaseFrame):
controller = attribute("_controller", "r")
project = attribute("_project", "r")
def __init__(self, args):
if wx.Platform=="__WXMSW__":
os.chdir(os.path.dirname(args[0]))
self.uilog = UILogger(self)
self._controller = MainController(self, args)
# create window
BaseFrame.__init__(self, None, InfoStrings["shortname"])
self.SetMinSize((550, 350))
self.vertSplitter = MainSplitter(self)
## start of panel source ----
self.panelSource = wx.Panel(self.vertSplitter, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
# method bar
self.methodBar = MethodBar(self.panelSource)
vbox.Add(self.methodBar, 0, wx.EXPAND)
# editor
self.srctext = Editor(self.panelSource)
self.srctext.Enable(False)
if wx.Platform=="__WXMAC__":
vbox.Add(self.srctext, 1, wx.EXPAND | wx.RIGHT, -1)
else:
vbox.Add(self.srctext, 1, wx.EXPAND)
self.panelSource.SetSizer(vbox)
## start of panel sim ----
self.panelSim = SimCanvas(self.vertSplitter, self.controller)
self.panelSim.Show(False)
## start of panel sim ----
self.panelClass = ClassPanel(self.vertSplitter, self.controller)
self.panelClass.Show(False)
self.curPanel = "src"
self.panelLeft = wx.Panel(self.vertSplitter, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
# project browser
self._project = ProjectBrowser(self.panelLeft, self, self.controller.mem)
vbox.Add(self._project, 1, wx.EXPAND, UITweaks.divpad)
self.panelLeft.SetSizer(vbox)
# splitter
self.vertSplitter.SplitVertically(self.panelLeft, self.panelSource)
self.panelLeft.SetFocus()
# toolbar
self.toolBar = MainToolBar(self)
self.SetToolBar(self.toolBar)
self.toolBar.Realize()
# main menu
self.menuBar = MainMenu(self)
self.menuBar.Check(ids.PROJECT_EDIT_LIBRARY, self.controller.isLibraryEditable())
self.menuBar.Check(ids.PROJECT_AUTO_SWITCH, self.controller.shouldAutoSwitch())
self.SetMenuBar(self.menuBar)
self.Bind(wx.EVT_MENU, self.OnMenuClick)
uiUpdates = [
ids.FILE_SAVE, ids.FILE_SAVE_AS, ids.EDIT_UNDO, ids.EDIT_REDO,
ids.EDIT_CUT, ids.EDIT_COPY, ids.EDIT_PASTE,
ids.VIEW_JUMPTO, ids.PROJECT_EDIT_LIBRARY, ids.PROJECT_EXPORT_ALL,
ids.PROJECT_IMPORT_CLASS, ids.PROJECT_NEW_CLASS, ids.PROJECT_NEW_METHOD,
ids.PROJECT_COMPILE ]
for uid in uiUpdates:
self.Bind(wx.EVT_UPDATE_UI, self.onUpdateUI, id=uid)
self.Bind(wx.EVT_CLOSE, self.onQuit)
# status bar
self.statusBar = wx.StatusBar(self, -1)
self.SetStatusBar(self.statusBar)
# set button states
self.setButtonStates(0, 0, 0)
# misc setup
self.shuttingDown = False
self.viewMode = "empty"
self.controller.onStartComplete()
self.Connect(-1, -1, EVT_UISTATE_ID, self.uiStateChange)
self.Connect(-1, -1, EVT_DEVICEUPGRADE_ID, self.onDeviceUpgrade)
self.Connect(-1, -1, EVT_DEVICECHANGE_ID, self.onDeviceChange)
self.Connect(-1, -1, EVT_THREADEXCEPTION_ID, self.onThreadException)
self.Connect(-1, -1, EVT_COMPILE_ID, self.onCompileDone)
self._project.controller.populate()
self.cw = ConsoleWindow(self)
self.docs = DocumentationWindow(self)
self.stacktrace = StackTraceWindow(self, self.controller.r, self.controller.mem)
self.Show(True)
self.Layout()
self.Fit()
for menu, label in self.menuBar.GetMenus():
menu.UpdateUI()
for f in os.listdir(os.path.join(Platform.getDataPath(), "examples")):
if len(f)>0 and f[0]!=".":
self.menuBar.addExample(f.split(".")[0], f)
self.vertSplitter.SetSashPosition(180)
if self.controller.saveState.getOpt("firststart", True):
self.onFirstStart()
self.controller.saveState.setOpt("firststart", False)
elif self.controller.saveState.getOpt("lastproj"):
lastMeth = self.controller.saveState.getOpt("lastmeth")
if lastMeth:
self._project.controller.jumpTo(lastMeth)
logging.info("Foxtalk ready. (Python %s, WX %s)" % (
".".join(map(str, sys.version_info[:3])), wx.__version__))
self.controller.checkProjectUpgrade()
##############################################################################
def setRightPanel(self, which):
if self.curPanel == which:
return
if which not in ["src", "class", "sim"]:
logging.error("Failing to change right panel to '%s'" % which)
return
sashPos = self.vertSplitter.GetSashPosition()
self.panelSource.Show(which=="src")
self.panelClass.Show(which=="class")
self.panelSim.Show(which=="sim")
self.vertSplitter.Unsplit()
panels = {"src" : self.panelSource,
"sim" : self.panelSim,
"class" : self.panelClass }
self.vertSplitter.SplitVertically(self.panelLeft, panels[which])
self._project.Update()
self.vertSplitter.SetSashPosition(sashPos)
self.curPanel = which
def setStatusText(self, msg):
self.statusBar.SetStatusText(msg)
def setButtonStates(self, comp, go, stop):
self.menuBar.Enable(ids.PROJECT_COMPILE, comp)
self.toolBar.EnableTool(ids.PROJECT_COMPILE, comp)
self.menuBar.Enable(ids.PROJECT_RUN, go)
self.toolBar.EnableTool(ids.PROJECT_RUN, go)
self.menuBar.Enable(ids.PROJECT_STOP, stop)
self.toolBar.EnableTool(ids.PROJECT_STOP, stop)
def updateTitle(self):
name = InfoStrings["shortname"]
projname = os.path.basename(self.controller.projectFilename)
title = "%s - %s" % (name, projname)
if self.viewMode == "source":
title += " - %s" % self.titlestring
self.SetTitle(title)
def setSourceView(self, titlestring=""):
if self.shuttingDown:
return
self.viewMode = "source"
self.srctext.SetFocus()
if titlestring:
self.titlestring = titlestring
self.updateTitle()
def setEmptyView(self):
if self.shuttingDown:
return
self.viewMode = "empty"
self.updateTitle()
def uiStateChange(self, evt):
t = evt.type
d = evt.data
if t=="progress-update":
percent = d # unimplemented
elif t=="button":
comp, run, stop, insp = d[:4]
if not self.controller.dm.currentConnection():
run = stop = 0
self.setButtonStates(comp, run, stop)
elif t=="button-msg":
comp, run, stop, insp = d[:4]
if not self.controller.dm.currentConnection():
run = stop = 0
self.setButtonStates(comp, run, stop)
txt = d[4]
self.setStatusText(txt)
elif t=="trace":
txt = d
self.setStatusText(txt)
msg = self.controller.checkBotState([])
self.stacktrace.showBacktrace(msg)
elif t=="change-view":
if d=="sim":
self.jumpTo("/robot/sim:tcp")
else:
logging.warn("Unhandled change-view: %s" % d)
elif t=="post-run":
d()
elif t=="start":
self.stacktrace.hide()
elif t=="update-available":
dial = wx.MessageDialog(self,
"Version %s is available, do you want to visit the %s site to download it now?" % (
d.sparkle["version"], InfoStrings["shortname"]),
"New Version Available",
style = wx.YES_NO|wx.ICON_QUESTION)
val = dial.ShowModal()
if val == wx.ID_YES:
webbrowser.open(InfoStrings["urlDownload"])
else:
logging.warn("Unhandled ui state change: %s %s" % (t, d))
def jumpTo(self, value):
self._project.controller.jumpTo(value)
def logClear(self):
wx.PostEvent(self.cw.console, LogMsgEvent("~~clear~~"))
def logMessage(self, msg):
wx.PostEvent(self.cw.console, LogMsgEvent(msg))
def showSource(self, cls, meth, line):
if self._project.controller.showSource(cls, meth, line):
self.srctext.markLine(line)
def makeFileDialog(self, title, dir=None, filename="", filter="", type=0):
if not dir:
dir = self.controller.defaultDir
return wx.FileDialog(self, title, dir, filename, filter, type)
def postEvent(self, evt):
wx.PostEvent(self, evt)
##############################################################################
def onProjectSelectItem(self, item):
self.docs.setItem(item)
def onUpdateUI(self, event):
id = event.GetId()
projOpen = (self.controller.projectFilename!="")
if (id == ids.FILE_SAVE or
id == ids.FILE_SAVE_AS or
id == ids.VIEW_JUMPTO or
id == ids.PROJECT_EDIT_LIBRARY or
id == ids.PROJECT_AUTO_SWITCH or
id == ids.PROJECT_EXPORT_ALL or
id == ids.PROJECT_IMPORT_CLASS or
id == ids.PROJECT_NEW_CLASS or
id == ids.PROJECT_NEW_METHOD):
event.Enable(projOpen)
elif id == ids.EDIT_CUT: event.Enable(projOpen and self.srctext.canCut())
elif id == ids.EDIT_COPY: event.Enable(projOpen and self.srctext.canCopy())
elif id == ids.EDIT_PASTE: event.Enable(projOpen and self.srctext.canPaste())
elif id == ids.EDIT_UNDO: event.Enable(projOpen and self.srctext.CanUndo())
elif id == ids.EDIT_REDO: event.Enable(projOpen and self.srctext.CanRedo())
elif id == ids.PROJECT_COMPILE:
item = self._project.controller.getSelectedItem()
#event.Enable(item!=None and item.canCompile())
comp = (item!=None and item.canCompile())
self.menuBar.Enable(ids.PROJECT_COMPILE, comp)
self.toolBar.EnableTool(ids.PROJECT_COMPILE, comp)
else:
logging.warn("unhandled update ui event %s" % event)
def OnToolClick(self, event):
self.OnMenuClick(event)
def OnMenuClick(self, event):
idmap = {
ids.FILE_EXIT: self.onQuit,
ids.FILE_NEW_PROJECT: self.onNewProjectButton,
ids.FILE_OPEN: self.onOpenButton,
ids.FILE_SAVE: self.onSaveButton,
ids.FILE_SAVE_AS: self.onSaveAsButton,
ids.EDIT_UNDO: self.onUndoButton,
ids.EDIT_REDO: self.onRedoButton,
ids.EDIT_CUT: self.onCutButton,
ids.EDIT_COPY: self.onCopyButton,
ids.EDIT_PASTE: self.onPasteButton,
ids.PROJECT_COMPILE: self.onCompileButton,
ids.PROJECT_RUN: self.onGoButton,
ids.PROJECT_STOP: self.onStopButton,
ids.PROJECT_NEW_METHOD: self.onNewMethodButton,
ids.PROJECT_NEW_CLASS: self.onNewClassButton,
ids.PROJECT_EXPORT_ALL: self.onExportAllButton,
ids.PROJECT_EXPORT_CLASS: self.onExportClassButton,
ids.PROJECT_IMPORT_CLASS: self.onImportClassButton,
ids.PROJECT_EDIT_LIBRARY: self.onEditLibraryButton,
ids.PROJECT_AUTO_SWITCH: self.onAutoSwitchButton,
ids.VIEW_CONSOLE: self.onConsoleButton,
ids.VIEW_JUMPTO: self.onJumpToButton,
ids.VIEW_GET_INFO: self.onGetInfoButton,
ids.VIEW_DOCUMENTATION: self.onDocsButton,
ids.DEV_CRASH: self.onCrashButton,
ids.HELP_ABOUT: self.onAboutButton,
ids.HELP_REFERENCE: self.onReferenceButton,
ids.HELP_TUTORIAL: self.onTutorialButton,
}
id = event.GetId()
if id in idmap:
idmap[id](event)
elif id in self.menuBar.examples:
self.openExample(os.path.join(Platform.getDataPath(), "examples/%s" % self.menuBar.examples[id]))
else:
logging.warn("unhandled menu click: %s" % id)
def openExample(self, fn):
self.checkForChanges()
self.controller.openProject(fn)
def checkForChanges(self):
if self._project.controller.changed or self.srctext.hasChanged() or self.docs.hasChanged():
dial = wx.MessageDialog(self,
"Do you want to save the changes made in the project \"%s\"" % (
os.path.basename(self.controller.projectFilename)),
"Save Changes?",
style = wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
val = dial.ShowModal()
if val == wx.ID_YES:
self.controller.saveProject()
return val
def onQuit(self, event):
if self.checkForChanges() == wx.ID_CANCEL:
return None
self.Show(False)
self.controller.onShutdown()
self.shuttingDown = True
self.controller.dm.shutdown()
self.Destroy()
def onUndoButton(self, event):
self.srctext.Undo()
def onRedoButton(self, event):
self.srctext.Redo()
def onCutButton(self, event):
self.srctext.CmdKeyExecute(wx.stc.STC_CMD_CUT)
def onCopyButton(self, event):
self.srctext.CmdKeyExecute(wx.stc.STC_CMD_COPY)
def onPasteButton(self, event):
self.srctext.CmdKeyExecute(wx.stc.STC_CMD_PASTE)
def onExportAllButton(self, event):
self.controller.mem.fileOut("src")
def onExportClassButton(self, event):
self._project.OnExportClass(event)
def onImportClassButton(self, event):
dial = self.makeFileDialog("Import Class", filter="*.st", type=wx.FD_OPEN)
res = dial.ShowModal()
if res == wx.ID_OK:
srcfile = dial.GetDirectory()+"/"+dial.GetFilename()
self._project.controller.importClass(srcfile)
self.setStatusText("imported %s" % (srcfile))
def onAboutButton(self, event):
info = wx.AboutDialogInfo()
info.SetName(InfoStrings["longname"])
copy = InfoStrings["copyright"]
if wx.Platform=="__WXMSW__":
copy = copy.replace("&", "&&")
info.SetCopyright(copy)
if wx.Platform=="__WXMAC__":
info.SetDescription(InfoStrings["description"])
else:
info.SetDescription(InfoStrings["description"])
info.SetVersion(InfoStrings["versionString"])
info.SetWebSite(InfoStrings["urlHomepage"])
wx.AboutBox(info)
def onReferenceButton(self, event):
self.controller.openHTMLDocs("reference.html")
def onTutorialButton(self, event):
self.controller.openHTMLDocs("tutorial.html")
def onNewProjectButton(self, event):
self.checkForChanges()
dialog = NewProjectDialog(self)
res = dialog.ShowModal()
if res == wx.ID_OK:
projtype, projname = dialog.GetValue()
mainclass = None
if projtype == "Drawing Project":
mainclass = "DrawingRobot"
elif projtype == "Basic Project":
mainclass = "Robot"
try:
self.controller.newProject(projname, mainclass)
except:
dialog.Destroy()
dial = wx.MessageDialog(self,
"Couldn't find default project file, install is probably corrupt",
"Missing Default Project",
style = wx.OK|wx.ICON_QUESTION)
dial.ShowModal()
return
self.controller.projectFilename = os.path.join(
self.controller.defaultDir,
projname+"."+InfoStrings["imageExtension"])
self.controller.dm.refresh()
self.updateTitle()
self.controller.firstSave = True
dialog.Destroy()
self.setButtonStates(1, 1, 0)
def onOpenButton(self, event):
self.checkForChanges()
dial = self.makeFileDialog(
"Open Project",
filename=self.controller.projectFilename,
dir=self.controller.defaultDir,
filter="*.%s" % InfoStrings["imageExtension"],
type=wx.FD_OPEN)
res = dial.ShowModal()
if res == wx.ID_OK:
self.controller.openProject(dial.GetPath())
def onSaveButton(self, event):
if self.controller.firstSave:
self.onSaveAsButton(event)
else:
self.controller.saveProject()
def onSaveAsButton(self, event):
dial = self.makeFileDialog(
"Save Project",
filename=os.path.basename(self.controller.projectFilename),
dir=self.controller.defaultDir,
filter="*.%s" % InfoStrings["imageExtension"],
type=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
res = dial.ShowModal()
if res == wx.ID_OK:
self.controller.projectFilename = dial.GetPath()
self.controller.saveProject()
self.controller.firstSave = False
def onCompileButton(self, event):
selitem = self._project.controller.getSelectedItem()
if selitem:
selitem.deselect(forceCompile=True)
def onStopButton(self, event):
self.controller.doStop()
def onGoButton(self, event):
selitem = self._project.controller.getSelectedItem()
if selitem:
selitem.deselect(forceCompile=True, runAfter=True)
def onConsoleButton(self, event):
self.cw.toggleVisible()
def onDocsButton(self, event):
self.docs.Show(True)
def onNewMethodButton(self, event):
self._project.OnNewMethod(event)
def onNewClassButton(self, event):
self._project.OnNewClass(event)
def onEditLibraryButton(self, event):
editable = self.menuBar.FindItemById(ids.PROJECT_EDIT_LIBRARY).IsChecked()
self._project.setLibraryEditable(editable)
self.controller.onEditLibraryButton(editable)
def onAutoSwitchButton(self, event):
autoswitch = self.menuBar.FindItemById(ids.PROJECT_AUTO_SWITCH).IsChecked()
self.controller.onAutoSwitchButton(autoswitch)
def onGetInfoButton(self, event):
self._project.OnGetInfo(event)
def onJumpToButton(self, event):
dialog = JumpToDialog(self)
res = dialog.ShowModal()
if res == wx.ID_OK:
self.jumpTo(dialog.GetValue())
dialog.Destroy()
def onFirstStart(self):
IntroWindow(self).ShowModal()
def onCrashButton(self, event):
raise Exception("CRASH")
def onImportFailed(self, fn):
dial = wx.MessageDialog(self,
"Failed to import file '%s'" % fn,
"Import Failed",
style = wx.OK|wx.ICON_ERROR)
val = dial.ShowModal()
def onLoadFailed(self, excp):
dial = wx.MessageDialog(self,
"The project '%s' appears to be corrupt and could not be opened" % (
os.path.basename(self.controller.projectFilename)),
"Failed to Open Project",
style = wx.OK|wx.ICON_ERROR)
val = dial.ShowModal()
def onProjectUpgrade(self):
dial = wx.MessageDialog(self,
"A new Foxtalk library is available, would you like to upgrade this project?",
"Upgrade Project '%s'?" % os.path.basename(self.controller.projectFilename),
style = wx.YES_NO|wx.ICON_QUESTION)
val = dial.ShowModal()
if val == wx.ID_YES:
self._project.controller.upgradeProject()
self.controller.dm.refresh()
def onDeviceUpgrade(self, evt):
dial = wx.MessageDialog(self,
"New firmware (r%d) is available for the connected device, would you like to upgrade it?" % evt.data[0],
"Upgrade Firmware?",
style = wx.YES_NO|wx.ICON_QUESTION)
val = dial.ShowModal()
if val == wx.ID_YES:
self.controller.doUpgradeStart()
dial = wx.MessageDialog(self,
"Please reboot the connected device into bootloader mode then click OK to begin the upgrade.",
"Enter Bootloader Mode",
style = wx.OK|wx.CANCEL|wx.ICON_QUESTION)
val = dial.ShowModal()
if val == wx.ID_OK:
self.cw.show()
self.controller.doUpgrade(evt.data[1])
def onDeviceChange(self, evt):
if evt.conn:
self._project.controller.addRobot(evt.id, evt.name, evt.conn)
else:
self._project.controller.removeRobot(evt.id)
def onCompileDone(self, evt):
self._project.controller.compileDone(evt)
def onThreadException(self, evt):
raise evt.data
| Python |
# vim:ts=4:sw=4:noet:
""" Documentation window """
import wx
import logging
from c.ui.wxw.widgets.baseframe import BaseFrame
from c.ui.wxw.editor import Editor
from c.compiler.spy import SpyClass, SpyMethod
class DocumentationWindow(BaseFrame):
def __init__(self, parent):
self.parent = parent
BaseFrame.__init__(self, parent, "Documentation")
self.Bind(wx.EVT_CLOSE, self.onClose)
self.item = None
self.anyChange = False
self.panel = wx.Panel(self, -1)
self.splitter = wx.SplitterWindow(self.panel, -1, style=wx.SP_LIVE_UPDATE)
self.panelExample = wx.Panel(self.splitter, -1)
self.panelDescr = wx.Panel(self.splitter, -1)
self.lblHdrTopA = wx.StaticText(self.panel, -1, "")
self.lblTopA = wx.StaticText(self.panel, -1, "")
self.lblHdrTopB = wx.StaticText(self.panel, -1, "")
self.lblTopB = wx.StaticText(self.panel, -1, "")
self.static_line_1 = wx.StaticLine(self.panel, -1)
self.lblHdrDescr = wx.StaticText(self.panelDescr, -1, "Description:")
self.lblByteInfo = wx.StaticText(self.panelDescr, -1, "")
self.editorDesc = Editor(self.panelDescr)
self.editorDesc.disableSyntax()
self.lblHdrExample = wx.StaticText(self.panelExample, -1, "Examples:")
self.lblLitInfo = wx.StaticText(self.panelExample, -1, "")
self.editorExample = Editor(self.panelExample)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: GetInfoMethodDialog.__set_properties
ft = self.lblTopA.GetFont()
newft = wx.Font(ft.GetPointSize(), wx.DECORATIVE, wx.NORMAL, wx.BOLD, 0, ft.GetFaceName())
self.lblHdrTopA.SetFont(newft)
self.lblHdrTopB.SetFont(newft)
self.lblHdrDescr.SetFont(newft)
self.lblHdrExample.SetFont(newft)
# end wxGlade
def __do_layout(self):
# begin wxGlade: GetInfoMethodDialog.__do_layout
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
sizer_8 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_7 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
grid_sizer_1 = wx.FlexGridSizer(2, 2, 5, 5)
grid_sizer_1.Add(self.lblHdrTopA, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblTopA, 0, wx.EXPAND, 0)
grid_sizer_1.Add(self.lblHdrTopB, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblTopB, 0, wx.EXPAND, 0)
self.mainSizer.Add(grid_sizer_1, 0, wx.ALL|wx.EXPAND, 5)
self.mainSizer.Add(self.static_line_1, 0, wx.EXPAND, 0)
sizer_2.Add(self.lblHdrDescr, 0, wx.TOP|wx.BOTTOM, 5)
sizer_2.Add(self.lblByteInfo, 0, wx.LEFT|wx.TOP|wx.BOTTOM, 5)
sizer_7.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_7.Add(self.editorDesc, 1, wx.BOTTOM|wx.EXPAND, 5)
self.panelDescr.SetSizer(sizer_7)
sizer_3.Add(self.lblHdrExample, 0, wx.TOP|wx.BOTTOM, 5)
sizer_3.Add(self.lblLitInfo, 0, wx.LEFT|wx.TOP|wx.BOTTOM, 5)
sizer_8.Add(sizer_3, 0, wx.EXPAND, 0)
sizer_8.Add(self.editorExample, 1, wx.EXPAND, 0)
self.panelExample.SetSizer(sizer_8)
self.splitter.SplitHorizontally(self.panelDescr, self.panelExample)
self.mainSizer.Add(self.splitter, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 5)
self.panel.SetSizer(self.mainSizer)
self.mainSizer.Fit(self)
self.Layout()
def onClose(self, event):
self.Show(False)
def hasChanged(self):
if (self.item and (self.editorDesc.hasChanged() or
self.editorExample.hasChanged())):
self.item.docs = "Info:\n%s\nExamples:\n%s\n" % (
self.editorDesc.GetText().rstrip(" \n"),
self.editorExample.GetText().rstrip(" \n"))
self.anyChange = True
return True
if self.anyChange:
return True
return False
def setItem(self, item):
self.hasChanged()
self.item = item
if isinstance(item, SpyMethod) or isinstance(item, SpyClass):
d = item.docs
self.editorDesc.Enable(True)
self.editorExample.Enable(True)
if "Info:" in d and "Examples:" in d:
idxInfo = d.index("Info:")
idxExample = d.index("Examples:")
self.editorDesc.setText(d[idxInfo+6:idxExample].rstrip(" \n"))
self.editorExample.setText(d[idxExample+10:].rstrip(" \n"))
else:
self.editorDesc.setText(d.rstrip(" \n"))
self.editorExample.setText("")
self.lblHdrTopA.SetLabel("Name:")
self.lblTopA.SetLabel(item.name)
if isinstance(item, SpyMethod):
self.lblHdrTopB.SetLabel("In Class:")
self.lblTopB.SetLabel(item.incls.name)
elif isinstance(item, SpyClass):
self.lblHdrTopB.SetLabel("Superclass:")
if hasattr(item.parent,"name"):
self.lblTopB.SetLabel(item.parent.name)
else:
self.lblTopB.SetLabel("nil")
else:
self.lblTopA.SetLabel("")
self.lblTopB.SetLabel("")
self.editorDesc.setText("")
self.editorExample.setText("")
self.editorDesc.Enable(False)
self.editorExample.Enable(False)
self.panel.Layout()
self.splitter.SetSashPosition(-100)
| Python |
# vim:ts=4:sw=4:noet:
""" Code editor (StyledTextCtrl) """
import wx
import wx.stc
import re
DEFAULT_DOC_FONT_SIZE = 10
DEFAULT_FONT_SIZE = 10
if wx.Platform == '__WXMSW__':
DEFAULT_FONT_FACE = "Courier New"
DEFAULT_DOC_FONT_FACE = "Verdana"
elif wx.Platform == '__WXMAC__':
DEFAULT_FONT_FACE = "Monaco"
DEFAULT_DOC_FONT_FACE = "Helvetica"
DEFAULT_FONT_SIZE = 11
DEFAULT_DOC_FONT_SIZE = 12
else:
DEFAULT_FONT_FACE = "Monospace"
DEFAULT_DOC_FONT_FACE = "Bitstream Vera Serif"
class StyleItem:
def __init__(self, type, fore=None, back=None, bold=None, italic=None, size=None):
self.type = type
self.fore = fore
self.back = back
self.bold = bold
self.italic = italic
self.size = size
def getSpec(self):
r = "face:%s," % DEFAULT_FONT_FACE
if self.fore: r += "fore:%s," % self.fore
if self.back: r += "back:%s," % self.back
if self.bold: r += "bold,"
if self.italic: r += "italic,"
if self.size: r += "size:%d," % self.size
else: r += "size:%d," % DEFAULT_FONT_SIZE
return r[:-1]
class Style:
def __init__(self):
self.items = []
def add(self, i):
self.items.append(i)
def apply(self, ed):
for i in self.items:
t = getattr(wx.stc, "STC_%s" % i.type.upper())
ed.StyleSetSpec(t, i.getSpec())
class Editor(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.SUNKEN_BORDER):
wx.stc.StyledTextCtrl.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, style=style)
self.SetMargins(5,0)
self.SetViewWhiteSpace(False)
self.SetEOLMode(wx.stc.STC_EOL_LF)
self.SetUseAntiAliasing(False) #True)
self.SetWrapMode(wx.stc.STC_WRAP_WORD)
self.SetTabWidth(4)
self.IndicatorSetForeground(0,"#ff0000")
self.MarkerDefine(25, wx.stc.STC_MARK_CHARACTER+ord("!"), "#ff0000", "#ffeeee")
self.SetMarginWidth(0, 0)
self.SetMarginWidth(1, 0)
self.SetMarginWidth(2, 0)
self.AutoCompStops("()\s\033'")
self.AutoCompSetFillUps("\n\r")
self.AutoCompSetIgnoreCase(True)
#self.SetMarginType(0, wx.stc.STC_MARGIN_SYMBOL) #margin 2 for symbols
#self.SetMarginMask(0, wx.stc.STC_MASK_FOLDERS) #set up mask for folding symbols
#self.SetMarginSensitive(0, True) #this one needs to be mouse-aware
self.SetLexer(wx.stc.STC_LEX_SMALLTALK)
"""
self.keywords = ["self", "at:", "do", "ifTrue:", "ifFalse:",
"true", "false", "subclass:", "to","nil",
"class", "new:", "put:"]
self.SetKeyWords(0," ".join(self.keywords))
"""
defF, defS = DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE
# Global default styles for all languages
self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "face:%s,size:%d" % (defF, defS))
self.StyleClearAll() # Reset all to be like the default
# Global default styles for all languages
self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "face:%s,size:%d" % (defF, defS))
self.StyleSetSpec(wx.stc.STC_STYLE_CONTROLCHAR, "face:%s" % defF)
self.StyleSetSpec(wx.stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
self.StyleSetSpec(wx.stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
s = Style()
cNormal = "#222222"
cSpecial = "#d0711d"
cLiteral = "#579dfd"
cComment = "#0f7300"
cPunct = "#777777"
s.add(StyleItem("st_default", fore=cNormal))
s.add(StyleItem("st_comment", fore=cComment, italic=True))
s.add(StyleItem("st_number", fore=cLiteral))
s.add(StyleItem("st_string", fore=cLiteral))
s.add(StyleItem("st_character", fore=cLiteral))
s.add(StyleItem("st_symbol", fore=cLiteral))
s.add(StyleItem("st_bool", fore=cLiteral))
s.add(StyleItem("st_kwsend", fore=cSpecial))
s.add(StyleItem("st_spec_sel", fore=cSpecial))
s.add(StyleItem("st_binary", fore=cPunct))
s.add(StyleItem("st_return", fore=cPunct))
s.add(StyleItem("p_commentblock", fore=cPunct))
#s.add(StyleItem("st_assign", fore="#ff8822"))
#s.add(StyleItem("st_global", fore="#00ff00"))
#s.add(StyleItem("st_nil", fore="#00ff00"))
#s.add(StyleItem("st_self", fore="#00ff00"))
#s.add(StyleItem("st_special", fore="#0000ff"))
#s.add(StyleItem("st_super", fore="#ff00ff"))
s.apply(self)
self.originalText = ""
self.acWords = ""
self.setAutoWords([])
def disableSyntax(self):
defF, defS = DEFAULT_DOC_FONT_FACE, DEFAULT_DOC_FONT_SIZE
self.StyleClearAll()
self.SetLexer(wx.stc.STC_LEX_NULL)
self.StyleSetSpec(wx.stc.STC_ST_DEFAULT, "face:%s,size:%d" % (defF, defS))
def setText(self, text):
#self.SetScrollWidth(1000)
if self.GetReadOnly():
self.SetReadOnly(False)
self.SetText(text)
self.SetReadOnly(True)
else:
self.SetText(text)
#maxx = 0
#for n in range(self.GetLineCount()):
# x,y = self.PointFromPosition(self.GetLineEndPosition(n))
# if x>maxx:
# maxx = x
#print maxx
#self.SetScrollWidth(maxx)
self.originalText = "%s" % text
def hasChanged(self):
return self.originalText!=self.GetText()
def getKeyWordStr(self):
res = re.findall("[^\(\)\s]+$", self.GetTextRange(
self.PositionFromLine(self.GetCurrentLine()),
self.GetCurrentPos()))
if res and len(res)==1:
return res[0]
else:
return ""
def setAutoWords(self, words):
basewords = ["self", "super", "nil", "true", "false"]
self.acWords = [w for w in basewords]
self.acWords.extend(words)
#print self.acWords
def getWordList(self, word):
return ' '.join([w for w in self.acWords if w.find(word)==0])
def doAutocomplete(self):
r = self.getKeyWordStr()
if r=="":
return
matches = self.getWordList(r)
self.AutoCompShow(len(r), matches)
def errorLine(self, num):
start = num[2]
size = num[3]-num[2]
#print "errorline",num,start,size
if size<1:
print "error size negative"
size = 1
tl = len(self.GetText())
if start<0:
print "error start negative"
start = 0
if start>=tl:
print "error postion beyond text"
start = tl-2
self.StartStyling(start, 0x20)
self.SetStyling(size, 0x20)
self.MarkerAdd(num[0]-2,25)
def markLine(self, num):
self.MarkerDeleteAll(25)
self.MarkerAdd(num,25)
def errorClear(self):
self.StartStyling(0, 0x60)
self.SetStyling(len(self.GetText()),0x0)
self.MarkerDeleteAll(25)
def canCopy(self):
return self.GetSelectionStart() != self.GetSelectionEnd()
def canCut(self):
return self.canCopy() and self.canEdit()
def canEdit(self):
return not self.GetReadOnly()
def canPaste(self):
return wx.stc.StyledTextCtrl.CanPaste(self) and self.canEdit()
| Python |
"""
wxWindows UI
"""
| Python |
# vim:ts=4:sw=4:noet:
""" Method Info dialog """
import wx
from c.ui.wxw.editor import Editor
class GetInfoMethodDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: GetInfoMethodDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.THICK_FRAME
wx.Dialog.__init__(self, *args, **kwds)
self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE)
self.window_1.SetSashGravity(1.0)
self.panelLiterals = wx.Panel(self.window_1, -1)
self.panelBytecodes = wx.Panel(self.window_1, -1)
self.lblHdrSignature = wx.StaticText(self, -1, "Signature:")
self.lblSignature = wx.StaticText(self, -1, "")
self.lblHdrInClass = wx.StaticText(self, -1, "In Class:")
self.lblInClass = wx.StaticText(self, -1, "")
self.lblHdrStatus = wx.StaticText(self, -1, "State:")
self.lblState = wx.StaticText(self, -1, "Compiled")
self.static_line_1 = wx.StaticLine(self, -1)
self.lblHdrBytecodes = wx.StaticText(self.panelBytecodes, -1, "Bytecodes:")
self.lblByteInfo = wx.StaticText(self.panelBytecodes, -1, "")
self.textBytecodes = Editor(self.panelBytecodes)
self.panelBytecodes.SetMinSize((250,150))
self.lblHdrLiterals = wx.StaticText(self.panelLiterals, -1, "Literals:")
self.lblLitInfo = wx.StaticText(self.panelLiterals, -1, "")
self.listLiterals = wx.ListBox(self.panelLiterals, -1, choices=[])
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: GetInfoMethodDialog.__set_properties
self.SetTitle("Method - ")
ft = self.lblSignature.GetFont()
newft = wx.Font(ft.GetPointSize(), wx.DECORATIVE, wx.NORMAL, wx.BOLD, 0, ft.GetFaceName())
self.lblHdrSignature.SetFont(newft)
self.lblHdrInClass.SetFont(newft)
self.lblHdrStatus.SetFont(newft)
self.lblHdrBytecodes.SetFont(newft)
self.lblHdrLiterals.SetFont(newft)
# end wxGlade
def __do_layout(self):
# begin wxGlade: GetInfoMethodDialog.__do_layout
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
sizer_8 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_7 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
grid_sizer_1 = wx.FlexGridSizer(3, 2, 5, 5)
grid_sizer_1.Add(self.lblHdrSignature, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblSignature, 0, wx.EXPAND, 0)
grid_sizer_1.Add(self.lblHdrInClass, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblInClass, 0, wx.EXPAND, 0)
grid_sizer_1.Add(self.lblHdrStatus, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblState, 0, wx.EXPAND, 0)
self.mainSizer.Add(grid_sizer_1, 0, wx.ALL|wx.EXPAND, 5)
self.mainSizer.Add(self.static_line_1, 0, wx.EXPAND, 0)
sizer_2.Add(self.lblHdrBytecodes, 0, wx.TOP|wx.BOTTOM, 5)
sizer_2.Add(self.lblByteInfo, 0, wx.LEFT|wx.TOP|wx.BOTTOM, 5)
sizer_7.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_7.Add(self.textBytecodes, 1, wx.BOTTOM|wx.EXPAND, 5)
self.panelBytecodes.SetSizer(sizer_7)
sizer_3.Add(self.lblHdrLiterals, 0, wx.TOP|wx.BOTTOM, 5)
sizer_3.Add(self.lblLitInfo, 0, wx.LEFT|wx.TOP|wx.BOTTOM, 5)
sizer_8.Add(sizer_3, 0, wx.EXPAND, 0)
sizer_8.Add(self.listLiterals, 1, wx.EXPAND, 0)
self.panelLiterals.SetSizer(sizer_8)
self.window_1.SplitHorizontally(self.panelBytecodes, self.panelLiterals)
self.mainSizer.Add(self.window_1, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 5)
self.SetSizer(self.mainSizer)
self.mainSizer.Fit(self)
self.Layout()
# end wxGlade
# end of class GetInfoMethodDialog
| Python |
# vim:ts=4:sw=4:noet:
""" New Method dialog """
import wx
from c.ui.wxw.widgets.checkedentry import CheckedEntry
from c.base.support import CoreException
class RenameMethodDialog(wx.Dialog):
def __init__(self, parent, mclass, methSig, isClassMeth=False):
wx.Dialog.__init__(self, parent, -1, "New Method")
self.mw = parent
self.mclass = mclass
self.oldSig = methSig
self.oldName = self.mw.controller.compiler.checkMethodSig(methSig)
self.entry = CheckedEntry(self, self.doCheck, self.doDone, methSig)
self.ok = wx.Button(self, wx.ID_OK, "OK")
self.ok.SetDefault()
self.ok.Enable(False)
cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
dlgsizer = wx.BoxSizer(wx.VERTICAL)
dlgsizer.Add(self.entry, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 10)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(self.ok)
btnsizer.AddButton(cancel)
btnsizer.Realize()
dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 10)
self.SetSizer(dlgsizer)
self.Fit()
self.Centre()
def GetValue(self):
txt = self.entry.GetValue()
return (False, txt)
def doCheck(self, sig):
try:
methname = self.mw.controller.compiler.checkMethodSig(sig)
if self.oldName != methname and self.mclass.hasMethod(methname):
self.ok.Enable(False)
return False, "Method '%s' already exists" % methname
self.ok.Enable(True)
return True, ""
except CoreException,e:
self.ok.Enable(False)
return False, str(e)
def doDone(self):
if self.ok.IsEnabled():
self.EndModal(wx.ID_OK)
| Python |
# vim:ts=4:sw=4:noet:
""" New Class dialog """
import wx
import re
from c.ui.wxw.widgets.checkedentry import CheckedEntry
from c.base.support import CoreException
class NewClassDialog(wx.Dialog):
def __init__(self, parent, classes, supername="", clsname=""):
wx.Dialog.__init__(self, parent, -1, "New Class")
self.mw = parent
self.supercls = wx.Choice(self, -1, choices=classes)
if supername!="":
self.supercls.SetSelection(classes.index(supername))
else:
self.supercls.SetSelection(0)
self.validName = re.compile("^[A-Za-z][a-zA-Z0-9]*$")
self.entry = CheckedEntry(self, self.doCheck, self.doDone)
self.ok = wx.Button(self, wx.ID_OK, "OK")
self.ok.SetDefault()
self.ok.Enable(False)
cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
dlgsizer = wx.BoxSizer(wx.VERTICAL)
dlgsizer.Add(self.supercls, 0, wx.ALL | wx.EXPAND, 10)
dlgsizer.Add(self.entry, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(self.ok)
btnsizer.AddButton(cancel)
btnsizer.Realize()
dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 10)
self.SetSizer(dlgsizer)
self.Fit()
self.Centre()
def GetValue(self):
supercls = self.supercls.GetString(self.supercls.GetSelection())
return (supercls, self.entry.GetValue())
def doCheck(self, value):
if value:
cls = self.mw.controller.mem.getGlobal(value)
if cls:
self.ok.Enable(False)
return False, "Class '%s' exists" % value
if not self.validName.search(value):
self.ok.Enable(False)
return False, "Invalid name"
self.ok.Enable(True)
return True, ""
else:
self.ok.Enable(False)
return False, "Need non-empty class name"
def doDone(self):
if self.ok.IsEnabled():
self.EndModal(wx.ID_OK)
| Python |
# vim:ts=4:sw=4:noet:
""" Jump To dialog """
import wx
class JumpToDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, -1, "Jump To ...",
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
self.mw = parent
self.SetMinSize((300,200))
self.textctrl = wx.TextCtrl(self, -1, "", style = wx.TE_PROCESS_ENTER)
self.textctrl.Bind(wx.EVT_TEXT, self.onUpdate)
self.textctrl.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
self.textctrl.SetFocus()
ok = wx.Button(self, wx.ID_OK, "OK")
ok.SetDefault()
cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
dlgsizer = wx.BoxSizer(wx.VERTICAL)
dlgsizer.Add(self.textctrl, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
matchListId = wx.NewId()
self.matchList = wx.ListBox(self, matchListId, choices=[" "," "])
self.matchList.Bind(wx.EVT_LISTBOX_DCLICK, self.onListBoxSelect, id=matchListId)
self.matchList.MoveAfterInTabOrder(self.textctrl)
dlgsizer.Add(self.matchList, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(ok)
btnsizer.AddButton(cancel)
btnsizer.Realize()
dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 10)
self.SetSizer(dlgsizer)
self.Fit()
self.Centre()
self.matchList.Clear()
def onListBoxSelect(self, event):
self.EndModal(wx.ID_OK)
def onListBox(self, event):
if self.matchList.GetCount():
sel = self.matchList.GetSelection()
if sel == wx.NOT_FOUND:
self.matchList.SetSelection(0)
def GetValue(self):
sel = self.matchList.GetSelection()
if sel == wx.NOT_FOUND:
return self.textctrl.GetValue()
else:
return self.matchList.GetStringSelection()
def onUpdate(self, evt):
self.matchList.Clear()
text = self.textctrl.GetValue().lower()
if not text:
return
keys = self.mw.project.controller.getJumpkeys()
for k in keys:
if text in k:
self.matchList.Append(k)
def onEnter(self, evt):
self.EndModal(wx.ID_OK)
| Python |
# vim:ts=4:sw=4:noet:
""" Robot Info dialog """
import wx
class GetInfoRobotDialog(wx.Dialog):
def __init__(self, parent, title):
wx.Dialog.__init__(self, parent, -1, title)
self.lblHdrVersion = wx.StaticText(self, -1, "Version")
self.lblVersion = wx.StaticText(self, -1, "")
self.lblHdrPlatform = wx.StaticText(self, -1, "Platform")
self.lblPlatform = wx.StaticText(self, -1, "")
self.lblHdrMemory = wx.StaticText(self, -1, "Memory Used")
self.lblMemory = wx.StaticText(self, -1, "")
self.__set_properties()
self.__do_layout()
def __set_properties(self):
ft = self.lblVersion.GetFont()
newft = wx.Font(ft.GetPointSize(), wx.DECORATIVE, wx.NORMAL, wx.BOLD, 0, ft.GetFaceName())
self.lblHdrVersion.SetFont(newft)
self.lblHdrPlatform.SetFont(newft)
self.lblHdrMemory.SetFont(newft)
def __do_layout(self):
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
grid_sizer_1 = wx.FlexGridSizer(2, 2, 5, 5)
grid_sizer_1.Add(self.lblHdrVersion, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblVersion, 0, wx.EXPAND, 0)
grid_sizer_1.Add(self.lblHdrPlatform, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0)
grid_sizer_1.Add(self.lblPlatform, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 0)
grid_sizer_1.Add(self.lblHdrMemory, 0, wx.ALIGN_RIGHT, 0)
grid_sizer_1.Add(self.lblMemory, 0, wx.EXPAND, 0)
self.mainSizer.Add(grid_sizer_1, 0, wx.ALL|wx.EXPAND, 10)
self.SetSizer(self.mainSizer)
self.mainSizer.Fit(self)
self.Layout()
def fit(self):
self.SetMinSize(self.mainSizer.GetMinSize())
self.Fit()
self.Center()
| Python |
"""
Dialogs
"""
from getinforobot import GetInfoRobotDialog
from getinfomethod import GetInfoMethodDialog
from jumpto import JumpToDialog
from newclass import NewClassDialog
from newmethod import NewMethodDialog
from newproject import NewProjectDialog
from renamemethod import RenameMethodDialog
| Python |
# vim:ts=4:sw=4:noet:
""" New Method dialog """
import wx
from c.ui.wxw.widgets.checkedentry import CheckedEntry
from c.base.support import CoreException
class NewMethodDialog(wx.Dialog):
def __init__(self, parent, classes, chosenClass=None, methSig="", isClassMeth=False):
wx.Dialog.__init__(self, parent, -1, "New Method")
self.mw = parent
self.methcls = wx.Choice(self, -1, choices=classes)
if chosenClass:
self.methcls.SetSelection(classes.index(chosenClass))
else:
self.methcls.SetSelection(0)
self.clsmethCheck = wx.CheckBox(self, -1, "Class Method")
self.clsmethCheck.SetValue(isClassMeth)
self.entry = CheckedEntry(self, self.doCheck, self.doDone)
self.ok = wx.Button(self, wx.ID_OK, "OK")
self.ok.SetDefault()
self.ok.Enable(False)
cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
dlgsizer = wx.BoxSizer(wx.VERTICAL)
dlgsizer.Add(self.methcls, 0, wx.ALL | wx.EXPAND, 10)
dlgsizer.Add(self.clsmethCheck, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
dlgsizer.Add(self.entry, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 10)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(self.ok)
btnsizer.AddButton(cancel)
btnsizer.Realize()
dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 10)
self.SetSizer(dlgsizer)
self.Fit()
self.Centre()
def GetValue(self):
txt = self.entry.GetValue()
cls = self.methcls.GetString(self.methcls.GetSelection())
return (cls, self.clsmethCheck.IsChecked(), txt)
def doCheck(self, sig):
try:
clsname = self.methcls.GetString(self.methcls.GetSelection())
cls = self.mw.controller.mem.getGlobal(clsname)
methname = self.mw.controller.compiler.checkMethodSig(sig)
if cls.hasMethod(methname):
self.ok.Enable(False)
return False, "Method '%s' already exists" % methname
self.ok.Enable(True)
return True, ""
except CoreException,e:
self.ok.Enable(False)
return False, str(e)
def doDone(self):
if self.ok.IsEnabled():
self.EndModal(wx.ID_OK)
| Python |
""" New Project dialog """
import wx
import c.ui.wxw.common as common
colourList = [ "Empty Project", "Basic Project", "Drawing Project" ]
class NewProjectDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, -1, "New Project", style=wx.DEFAULT_DIALOG_STYLE)
self.mw = parent
self.SetMinSize((280,10))
self.projtype = wx.Choice(self, -1, choices=colourList)
self.projtype.SetSelection(len(colourList)-1)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
self.textctrl = wx.TextCtrl(self, -1, "", style = wx.TE_PROCESS_ENTER)
self.textctrl.Bind(wx.EVT_TEXT, self.onUpdate)
self.textctrl.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
self.textctrl.SetFocus()
hbox3.Add(wx.StaticText(self, -1, "Project Name"), 0, wx.ALIGN_CENTRE_VERTICAL, 0)
hbox3.Add(self.textctrl, 1, wx.EXPAND | wx.LEFT , 10)
self.ok = wx.Button(self, wx.ID_OK, "OK")
self.ok.SetDefault()
self.ok.Disable()
cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
dlgsizer = wx.BoxSizer(wx.VERTICAL)
dlgsizer.Add(self.projtype, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 10)
dlgsizer.Add(hbox3, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 10)
dlgsizer.Add(wx.StaticLine(self, -1), 0, wx.TOP | wx.EXPAND | wx.LEFT | wx.RIGHT, 10)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(self.ok)
btnsizer.AddButton(cancel)
btnsizer.Realize()
dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 10)
self.SetSizer(dlgsizer)
self.Fit()
self.Centre()
def GetValue(self):
pt = self.projtype.GetString(self.projtype.GetSelection())
return (pt, self.textctrl.GetValue())
def onUpdate(self, evt):
self.ok.Enable(self.textctrl.GetValue()!="")
def onEnter(self, evt):
self.EndModal(wx.ID_OK)
| Python |
# vim:ts=4:sw=4:noet:
""" Platform specific tweaks """
import os
import wx
from c.base.version import InfoStrings
class SPlatform:
def __init__(self):
self.divpad = 2
self.methpad = 2
self.methbarHeight = 26
if wx.Platform=="__WXMAC__":
wx.SystemOptions.SetOptionInt("mac.listctrl.always_use_generic", False)
self.divpad = 5
self.methpad = 4
self.methbarHeight = 18
UITweaks = SPlatform()
| Python |
# vim:ts=4:sw=4:noet:
""" Miscellaneous WX support code """
import wx
from c.base.platform import Platform
import os.path
import cStringIO
def getProperPath(fn):
if os.path.exists(fn):
return fn
elif os.path.exists(os.path.split(fn)[-1]):
return os.path.split(fn)[-1]
else:
raise Exception("File not found: %s" % fn)
def loadWxImage(fn):
data = file(getProperPath(Platform.getDataFilePath(fn)),"rb").read()
im = wx.ImageFromStream(cStringIO.StringIO(data))
return wx.BitmapFromImage(im)
def loadWxImagePlain(fn):
data = file(getProperPath(Platform.getDataFilePath(fn)),"rb").read()
return wx.ImageFromStream(cStringIO.StringIO(data))
| Python |
# vim:ts=4:sw=4:noet:
""" Console Window """
import wx
import wx.stc
from c.ui.wxw.widgets.baseframe import BaseFrame
from c.base.support import CoreException
from editor import DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE
from events import EVT_LOG_ID
import c.compiler.spy as spy
class Console(wx.stc.StyledTextCtrl):
def __init__(self, parent):
wx.stc.StyledTextCtrl.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, 0)
self.SetMargins(5,5)
self.SetMarginWidth(1,0)
self.SetViewWhiteSpace(False)
self.SetUseAntiAliasing(False)
self.SetWrapMode(wx.stc.STC_WRAP_WORD)
self.SetTabWidth(4)
self.SetCaretWidth(0)
self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "face:%s,size:%d" % (
DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE))
self.StyleClearAll()
style = "fore:#cccccc,back:#222222,face:%s,size:%d" % (
DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE)
self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, style)
self.StyleSetSpec(wx.stc.STC_ST_DEFAULT, style)
self.Connect(-1, -1, EVT_LOG_ID, self.logText)
def logText(self, evt):
self.SetReadOnly(False)
if evt.data=="~~clear~~":
self.ClearAll()
else:
self.AppendText(evt.data)
self.SetReadOnly(True)
def addText(self, text):
self.SetReadOnly(False)
self.AppendText(text)
self.SetReadOnly(True)
class ConsoleWindow(BaseFrame):
def __init__(self, parent):
BaseFrame.__init__(self, parent, "Console", size=(400, 200))
self.SetMinSize((400,200))
self.parent = parent
panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
self.console = Console(panel)
self.entry = wx.TextCtrl(panel, -1, "", style=wx.TE_PROCESS_ENTER)
self.entry.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
self.entry.SetFocus()
vbox.Add(self.console, 1, wx.EXPAND|wx.ALL, -1)
vbox.Add(self.entry, 0, wx.EXPAND|wx.ALL, -1)
panel.SetSizer(vbox)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.shown = False
self.Show(self.shown)
def onDoneRun(self):
controller = self.parent._controller
ret = controller.r.getLastReturn()
self.console.addText("%s\n" % controller.r.getLastReturn().asString())
def onEnter(self, evt):
text = self.entry.GetValue()
self.entry.SetValue("")
self.console.addText(">> %s\n" % text)
controller = self.parent._controller
mcls = controller.mem.getGlobal("mainClass")
if mcls:
try:
spymeth = controller.compiler.compileMethod(
mcls, "doit [ ^ %s ]" % text)
except CoreException, e:
self.console.addText("%s\n" % e)
return
methsize = 3+len(spymeth.literals)
MethodClass = controller.r.getGlobal("Method")
if not MethodClass:
print "couldn't get method class"
return
rmeth = controller.r.allocObject(methsize, MethodClass.ptr)
#print "alloced meth", methsize, rmeth
rmeth.setData(0, controller.r.allocSymbol("doit").ptr)
rmeth.setData(1, (((spymeth.maxStack<<6)|spymeth.maxTemps)<<2)|2)
rmeth.setData(2, controller.r.allocByteArray(spymeth.bytecodes).ptr)
for i, lit in enumerate(spymeth.literals):
if isinstance(lit, spy.SpySymbol):
v = lit.optr
else:
print "unhandled lit", lit
rmeth.setData(3+i, v)
#print "compiled:", mcls.methods.pdict
controller.r.runMethod(rmeth.ptr, controller.r.getGlobal("mainClass").ptr)
controller.doRun(self.onDoneRun)
def show(self):
self.shown = True
self.Show()
def onClose(self, event):
self.toggleVisible()
def toggleVisible(self):
self.shown = not self.shown
self.Show(self.shown)
| Python |
# vim:ts=4:sw=4:noet:
""" Custom UI events """
import wx
EVT_LOG_ID = wx.NewId()
class LogMsgEvent(wx.PyEvent):
def __init__(self, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_LOG_ID)
self.data = data
EVT_UISTATE_ID = wx.NewId()
class UiStateEvent(wx.PyEvent):
def __init__(self, type, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_UISTATE_ID)
self.type = type
self.data = data
EVT_COMPILE_ID = wx.NewId()
class CompileEvent(wx.PyEvent):
def __init__(self, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_COMPILE_ID)
self.data = data
EVT_DEVICEUPGRADE_ID = wx.NewId()
class DeviceUpgradeEvent(wx.PyEvent):
def __init__(self, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_DEVICEUPGRADE_ID)
self.data = data
EVT_DEVICECHANGE_ID = wx.NewId()
class DeviceChangeEvent(wx.PyEvent):
def __init__(self, id, name=None, conn=None):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_DEVICECHANGE_ID)
self.id = id
self.name = name
self.conn = conn
EVT_THREADEXCEPTION_ID = wx.NewId()
class ThreadExceptionEvent(wx.PyEvent):
def __init__(self, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_THREADEXCEPTION_ID)
self.data = data
| Python |
# vim:ts=4:sw=4:noet:
""" User interface state management """
import os
import pickle
from c.base.version import InfoStrings
from c.base.platform import Platform
SAVE_STATE_FILE = Platform.getConfigFilePath(InfoStrings["configfile"])
class UISaveState:
def __init__(self):
self.sdict = {}
if os.path.exists(SAVE_STATE_FILE):
f = file(SAVE_STATE_FILE, "rb")
self.sdict = pickle.load(f)
f.close()
def setOpt(self, n, v):
self.sdict[n] = v
def getOpt(self, n, ifNot=None):
if n in self.sdict:
return self.sdict[n]
else:
return ifNot
def save(self):
f = file(SAVE_STATE_FILE, "wb")
pickle.dump(self.sdict, f, 2)
f.close()
| Python |
# vim:ts=4:sw=4:noet:
""" Project browser controller """
from c.compiler.spy import SpyClass, STATE_COMPILED, STATE_ERROR
from c.compiler.compiler import Compiler
from c.base.attribute import attribute
from c.base.platform import Platform
from c.base.support import Status, CoreException
from c.ui.wxw.events import *
from dialogs import GetInfoRobot, GetInfoMethod
import logging
import os
class ProjectItem:
type = attribute("_type", "r")
obj = attribute("_obj", "r")
def __init__(self, pc, type):
self._pc = pc
self._type = type
self._obj = None
def select(self, sourceView=True):
pass
def deselect(self, forceCompile=False, runAfter=False):
if runAfter:
self._pc.mw.controller.doImageLoad()
def canCompile(self):
return False
################################################################################
class PackageItem(ProjectItem):
def __init__(self, pc, type, name):
ProjectItem.__init__(self, pc, type)
self.name = name
def select(self, sourceView="empty"):
if self._pc.mw.shuttingDown:
return
self._pc.mw.setRightPanel("src")
self._pc.mw.setEmptyView()
self._pc.mw.srctext.setText("")
self._pc.mw.srctext.Enable(False)
self._pc.mw.methodBar.setMethodName("")
################################################################################
class ClassItem(ProjectItem):
def __init__(self, pc, type, name, pkg, obj):
ProjectItem.__init__(self, pc, type)
self.name = name
self.pkgitem = pkg
self._obj = obj
self.ui = self._pc.addViewItem(self, self.pkgitem)
def select(self, sourceView="empty"):
self._pc.mw.setRightPanel("class")
inLib = self._obj.getPragma("category")[:7]=="Library"
self._pc.mw.panelClass.setObject(self._obj, inLib)
self._pc.mw.setEmptyView()
self._pc.mw.srctext.setText("")
self._pc.mw.srctext.Enable(False)
self._pc.mw.methodBar.setMethodName("")
################################################################################
class MethodItem(ProjectItem):
def __init__(self, pc, type, clsitem, name, obj):
ProjectItem.__init__(self, pc, type)
self.name = name
self.clsitem = clsitem
self._obj = obj
self.ui = self._pc.addViewItem(self, self.clsitem)
if obj.state != STATE_COMPILED:
self._pc.setViewItemIcon(self, "method-error")
self.sourceView = "source"
self.deleted = False
def select(self, sourceView="empty"):
self._pc.mw.setRightPanel("src")
if sourceView=="empty":
self._pc.mw.setSourceView()
sourceView = "source"
jname = "%s>>%s" % (self._obj.incls.name.lower(), self._obj.name.lower())
self._pc.mw.controller.saveState.setOpt("lastmeth",jname)
self.sourceView = sourceView
self._pc.mw.methodBar.setMethodName(self._obj.sig)
self._pc.mw.srctext.Enable(True)
if self.clsitem.obj.getPragma("category")[:7]=="Library":
self._pc.mw.srctext.SetReadOnly(not self._pc.isLibEditable())
else:
self._pc.mw.srctext.SetReadOnly(False)
self._pc.mw.Layout()
self._pc.mw.setSourceView(self.name)
stext = self._obj.source
self._pc.mw.srctext.setText(stext)
def deselect(self, forceCompile=False, runAfter=False):
if self.sourceView == "source":
srctext = self._pc.mw.srctext
shouldCompile = srctext.GetText()!=self._obj.source
if forceCompile or shouldCompile:
self._obj.source = srctext.GetText()
self._pc.mw.controller.doCompile(
self, self._obj.sig+" [\n"+srctext.GetText()+"\n]", runAfter)
def canCompile(self):
if self.clsitem.obj.getPragma("category")[:7]=="Library":
if not self._pc.isLibEditable():
return False
return True
def compileDone(self, state):
if self.deleted:
return
icon = self._type
if not state:
icon = "method-error"
self._pc.setViewItemIcon(self, icon)
################################################################################
class RobotItem(ProjectItem):
def __init__(self, pc, robot, name="Unnamed Robot"):
ProjectItem.__init__(self, pc, "robot")
self.robot = robot
self.name = name
self.ui = self._pc.addViewItem(self, self._pc.devicesPkg)
self._pc.view.Expand(self._pc.devicesPkg.ui)
def remove(self):
self._pc.view.Delete(self.ui)
def select(self, sourceView="empty"):
self._pc.mw.srctext.setText("")
self._pc.mw.methodBar.setMethodName("")
self._pc.mw.setEmptyView()
self._pc.mw.setRightPanel("sim")
################################################################################
class ProjectController:
view = attribute("_view", "r")
changed = attribute("_changed", "rw")
def __init__(self, view, mainwin, mem):
self.mw = mainwin
self.mem = mem
self._view = view
self._selectedItem = None
self._changed = False
def __createPackage(self, pname, icon="package", parent=None):
jname = "Pkg"+pname.lower()
if jname in self._jumphash:
return self._jumphash[jname]
pkgitem = PackageItem(self, "package", pname)
pui = None
if parent:
pui = parent.ui
pkg = self._view.addItem(pname, parent=pui, pdata=pkgitem, icontype=icon)
pkgitem.ui = pkg
self._jumphash[jname] = pkgitem
return pkgitem
def __populatePackages(self):
glbnames = self.mem.globals.keys()
glbnames.sort()
for name in glbnames:
if name[:4]!="Meta":
obj = self.mem.getGlobal(name)
if isinstance(obj, SpyClass):
# create class item
cat = obj.getPragma("category").split("-")
if cat[0]=="Library":
if len(cat)==1:
pkg = self.libraryPkg
else:
catpkg = self.__createPackage(
cat[1],
icon="category",
parent=self.libraryPkg)
pkg = catpkg
elif name=="mainClass":
continue
else:
pkg = self.projectPkg
self.addClassItem(pkg, obj, True, False)
def isLibEditable(self):
return self._view.libEditable
def clear(self):
self._selectedItem = None
self._view.DeleteChildren(self._view.root)
self._mhash = {}
self._jumphash = {}
self._classes = []
self._robots = {}
def populate(self):
self.clear()
self.libraryPkg = self.__createPackage("Library")
self.projectPkg = self.__createPackage("Project")
self.devicesPkg = self.__createPackage("Robots", "robots")
self.__populatePackages()
self._view.SortChildren(self.libraryPkg.ui)
self._changed = False
def getJumpkeys(self):
return self._jumphash.keys()
def getProjectItem(self, name):
jn = name.lower()
if jn in self._jumphash:
return self._jumphash[jn]
return None
def addRobot(self, id, name, connection):
if id in self._robots:
return
self._robots[id] = RobotItem(self, connection, name)
jn = "/robot/%s" % id
self._jumphash[jn] = self._robots[id]
def removeRobot(self, id):
self._robots[id].remove()
del self._robots[id]
jn = "/robot/%s" % id
del self._jumphash[jn]
def addViewItem(self, item, parent):
return self._view.addItem(item.name, parent.ui, item.type, item)
def setViewItemIcon(self, item, icon):
self._view.setItemIcon(item.ui, icon)
def addMethodItem(self, clsitem, meth, type):
methitem = MethodItem(self, type, clsitem, meth.name, meth)
self._mhash[methitem.ui] = methitem
if type=="method":
jn = "%s>>%s" % (clsitem.obj.name.lower(), meth.name.lower())
else:
jn = "meta%s>>%s" % (clsitem.obj.name.lower(), meth.name.lower())
self._jumphash[jn] = methitem
self._view.SortChildren(clsitem.ui)
self._view.SetFocus()
self._view.SelectItem(methitem.ui, True)
def addClassItem(self, pkg, cls, addMethods=False, sortPkg=True):
clsitem = ClassItem(self, "class", cls.name, pkg, cls)
self._mhash[clsitem.ui] = clsitem
self._jumphash[cls.name.lower()] = clsitem
self._classes.append(cls.name)
if sortPkg:
self._view.SortChildren(pkg.ui)
self._view.SetFocus()
self._view.SelectItem(clsitem.ui, True)
if addMethods:
if cls.cls:
for meth in cls.cls.methods.pdict:
m = cls.cls.methods.get(meth)
methitem = MethodItem(self,"cmethod", clsitem, meth, m)
self._mhash[methitem.ui] = methitem
jn = "%s>>%s" % (cls.cls.name.lower(), meth.lower())
self._jumphash[jn] = methitem
# add methods
for meth in cls.methods.pdict:
m = cls.methods.get(meth)
methitem = MethodItem(self,"method", clsitem, meth, m)
self._mhash[methitem.ui] = methitem
jn = "%s>>%s" % (cls.name.lower(), meth.lower())
self._jumphash[jn] = methitem
self._view.SortChildren(clsitem.ui)
def removeMethodItem(self, methitem):
del self._mhash[methitem.ui]
jn = "%s>>%s" % (methitem.obj.incls.name.lower(), methitem.obj.name.lower())
del self._jumphash[jn]
self.selectItem(methitem.clsitem.ui)
self._view.Delete(methitem.ui)
self._changed = True
def removeClassItem(self, clsitem):
del self._mhash[clsitem.ui]
del self._jumphash[clsitem.obj.name.lower()]
self._classes.remove(clsitem.obj.name)
self._view.UnselectAll()
item = clsitem.ui
child, foo = self._view.GetFirstChild( item )
extra = []
if child.IsOk():
while child.IsOk():
extra.append( child )
child, foo = self._view.GetNextChild( item, foo )
extra.append(item)
map( self._view.Delete, extra )
self._changed = True
def refreshCurrentItem(self):
self.selectItem(self._selectedItem)
def selectItem(self, itemId):
if self._selectedItem:
# FIXME: strange windows closing bug
try:
self._view.GetPyData(self._selectedItem).deselect()
except Exception, e:
logging.warn("BUG failed to deselect '%s'" % (
self._view.GetItemText(self._selectedItem)))
try:
item = self._view.GetPyData(itemId)
if item:
item.select(self.mw.viewMode)
self._selectedItem = itemId
self.mw.onProjectSelectItem(item.obj)
except Exception, e:
logging.warn("BUG failed to select '%s'" % (
self._view.GetItemText(self._selectedItem)))
def getSelectedItem(self):
if self._selectedItem:
return self._view.GetPyData(self._selectedItem)
else:
return None
def importClass(self, srcfile):
try:
c = Compiler(self.mw.controller.mem, mcheck=False)
clsname = c.compileFile(srcfile)
self.addClassItem(
self.projectPkg,
self.mw.controller.mem.getGlobal(clsname),
True)
except:
self.mw.onImportFailed(srcfile)
def getEditableClasses(self):
if not self.isLibEditable():
classes = []
for cn in self._classes:
cls = self._jumphash[cn.lower()].obj
if not cls.inLibrary():
classes.append(cn)
return classes
else:
return self._classes
def getAllClasses(self):
return self._classes
def upgradeProject(self):
bp = Platform.getBasePath()
classes = self.exportPackage(self.projectPkg, bp)
self.mw.controller.newProject("")
for c in classes:
self.mw.controller.mem.addGlobal(c, None)
for c in classes:
fn = os.path.join(bp, "%s.st" % c)
self.importClass(fn)
os.remove(fn)
for c in classes:
cls = self.mw.controller.mem.getGlobal(c)
for mn in cls.methods.pdict:
meth = cls.methods.pdict[mn]
source = "%s [ %s ]" % (meth.sig, meth.source)
try:
self.mw.controller.compiler.compileMethod(cls, source)
except CoreException, e:
self.mw.postEvent(UiStateEvent("button-msg", (1,1,0,1, "Check failed: %s" % e)))
self.mw.logMessage("%s\n" % e)
selItem = self.mw.project.controller.getSelectedItem()
meth.state = STATE_ERROR
self.populate()
mainCls = self.mw.controller.mem.getMainClass()
if mainCls:
self.jumpTo("%s>>main" % mainCls.name.lower())
self.mw.updateTitle()
self.mw.controller.firstSave = False
self._changed = True
def exportPackage(self, pitem, dir):
package = pitem.ui
if pitem and pitem.type=="package":
child,x = self._view.GetFirstChild(package)
classes = []
if child.IsOk():
while child.IsOk():
classes.append(self._view.GetPyData(child))
child,x = self._view.GetNextChild( package,x )
for cls in classes:
cls.obj.fileOut(dir)
return [c.obj.name for c in classes]
return []
def createNewClass(self, clsname, supername):
cls = SpyClass(self.mem, clsname, self.mem.getGlobal(supername))
cls.newClassInit()
self.mem.addGlobal(clsname, cls)
self._changed = True
return cls
def newMethod(self, cls, sig):
return Compiler(self.mem).compileMethod(cls, sig+" [\n\t\n]")
def createNewMethod(self, methsig, clsname, isclsmeth=False):
cls = self.mem.getGlobal(clsname)
methtype = "method"
if isclsmeth:
cls = cls.cls
methtype = "cmethod"
methcount = len(cls.methods)
if len(cls.methods)>50:
return False, "toomany", ""
elif cls.hasMethod(methsig):
return False, "exists", ""
else:
meth = self.newMethod(cls, methsig)
self.mem.addMessage(meth.name)
self._changed = True
return True, meth, methtype
def compileDone(self, evt):
if not evt or not evt.data:
print "bad compile"
return
obj, state = evt.data
obj.compileDone(state)
def jumpTo(self, value):
if value.lower() in self._jumphash:
self._view.SetFocus()
self._view.SelectItem(self._jumphash[value.lower()].ui, True)
return True
return False
def showSource(self, cls, meth, line):
jn = "%s>>%s" % (cls.lower(), meth.lower())
return self.jumpTo(jn)
def getInfo(self, pitem):
if pitem:
if pitem.type=="method":
res = GetInfoMethod(self.mw, pitem).do()
elif pitem.type=="cmethod":
res = GetInfoMethod(self.mw, pitem).do()
elif pitem.type=="robot":
res = GetInfoRobot(self.mw, pitem).do()
| Python |
# vim:ts=4:sw=4:noet:
""" Update Checker """
from c.base.version import InfoStrings
import urllib2
from xml.dom.minidom import parse
import threading
import logging
import time
import platform
class UpdaterException(Exception):
pass
class Update:
def __init__(self):
self.sparkle = {}
def __repr__(self):
r = "<update:"
for d in dir(self):
if "__" not in d:
r += " %s:'%s'" % (d, getattr(self,d))
r += ">"
return r
class Version:
def __init__(self, vstring):
self.version = vstring.split(".")
def __cmp__(self, other):
if other.__class__!=self.__class__:
return 1
for i in range(min(len(self.version), len(other.version))):
if self.version[i] > other.version[i]:
return 1
elif self.version[i] < other.version[i]:
return -1
if len(self.version) == len(other.version):
return 0
elif len(self.version) > len(other.version):
return 1
else:
return -1
def __repr__(self):
return '.'.join(self.version)
class Updater:
def __init__(self, currentVersion, updateAvailableCallback):
self.appcastUrl = InfoStrings["urlAppcast"]
self.currentVersion = Version(currentVersion)
self.updateAvailableCallback = updateAvailableCallback
def check(self):
self.thread = threading.Thread(
None,
self.__check)
self.thread.start()
def __check(self):
time.sleep(1)
try:
url = urllib2.urlopen(self.appcastUrl)
dom = parse(url)
url.close()
except Exception,e:
logging.warn("Update check failed - couldn't connect, or invalid data: %s" % e)
return
channels = dom.getElementsByTagName("channel")
if len(channels)!=1:
raise UpdaterException("too many channels")
self.updates = []
for item in channels[0].getElementsByTagName("item"):
update = Update()
children = [n for n in item.childNodes if n.nodeType == n.ELEMENT_NODE]
for c in children:
cname = c.tagName
cattrs = c.attributes
cchild = c.childNodes
if cname == "title":
update.title = cchild[0].data
elif cname == "pubDate":
update.pubdate = cchild[0].data
elif cname == "enclosure":
update.url = cattrs["url"].value
update.sparkle["version"] = Version(cattrs["sparkle:version"].value)
update.sparkle["md5"] = cattrs["sparkle:md5Sum"].value
update.sparkle["ostype"] = cattrs["sparkle:ostype"].value
update.type = cattrs["type"].value
update.length = cattrs["length"].value
elif cname[:8] == "sparkle:":
update.sparkle[cname[8:]] = cchild[0].data
else:
raise UpdaterException("unknown item %s" % cname)
self.updates.append(update)
# check updates
latestVersion = 0
newUpdate = None
myos = "win"
if platform.system()=="Darwin":
myos = "mac"
for update in self.updates:
if update.sparkle["version"] > latestVersion and myos==update.sparkle["ostype"]:
latestVersion = update.sparkle["version"]
newUpdate = update
if latestVersion > self.currentVersion:
self.updateAvailableCallback(newUpdate)
| Python |
# vim:ts=4:sw=4:noet:
""" Manager for long running tasks (compilation, etc) """
import threading
import logging
class TaskManager:
def __init__(self, mc):
self.mc = mc
self.tasks = {}
def __del__(self):
logging.info("[tm] killing old threads for shutdown")
for t in self.tasks:
self.stopTask(t)
def hasTask(self, name):
return ((name in self.tasks) and self.tasks[name].isAlive())
def createTask(self, name, workFunc, workFuncArgs=[], start=True, daemon=False):
if name in self.tasks:
task = self.tasks[name]
logging.info("[tm] killing old task '%s'" % name)
if task.isAlive():
task.join()
self.tasks[name] = threading.Thread(
None,
self._make_task_wrapper(workFunc, workFuncArgs))
if daemon:
self.tasks[name].setDaemon(True)
if start:
self.startTask(name)
def _make_task_wrapper(self, workFunc, workFuncArgs):
def _task_wrapper():
try:
workFunc(*workFuncArgs)
except Exception,e:
self.mc.handleThreadException(e)
return _task_wrapper
def startTask(self, name):
logging.info("[tm] starting task '%s' (%s)" % (name,
" ".join([t for t in self.tasks if self.tasks[t].isAlive()])))
self.tasks[name].start()
def stopTask(self, name):
if name in self.tasks:
task = self.tasks[name]
if task.isAlive():
logging.info("[tm] stopping task '%s'" % name)
task.join()
| Python |
"""
User Interface
"""
| Python |
# vim:ts=4:sw=4:noet:
""" App Entrypoint """
import sys
import wx
import re
import traceback
import c.base.log as log
from c.ui.wxw.mainwindow import MainWindow
log.initLogging()
class BaseApp(wx.PySimpleApp):
def BringWindowToFront(self):
try:
self.GetTopWindow().Raise()
except:
pass
def OnActivate(self, event):
if event.GetActive():
self.BringWindowToFront()
event.Skip()
def MacReopenApp(self):
self.BringWindowToFront()
class MainApp:
def __init__(self, args):
self.app = BaseApp()
self.mainFrame = MainWindow(args)
def excepthook(self, type, value, tb):
msg = ''.join(traceback.format_exception(type, value, tb))
msg = re.sub("\".*/c/","\"c/",msg)
msg = re.sub("\".*\\\\c\\\\","\"c\\\\",msg)
f = open("fail.log", "wb")
f.write(msg)
f.close()
dial = wx.MessageDialog(self.mainFrame,
"%s\nEverything may be going horribly awry; keep going?" % msg,
"Caught Unhandled Exception",
style = wx.YES_NO|wx.ICON_QUESTION)
val = dial.ShowModal()
if val == wx.ID_NO:
sys.exit(1)
def run(self):
sys.excepthook = self.excepthook
self.app.MainLoop()
| Python |
# vim:ts=4:sw=4:noet:
""" Main window controller """
import wx
import time
import os
import logging
import webbrowser
from c.base.attribute import attribute
from c.base.support import Status, CoreException
from c.base.version import InfoStrings
from c.base.platform import Platform
from c.compiler.mem import Memory
from c.compiler.cmg import CMG
from c.compiler.compiler import Compiler
from c.compiler.spy import STATE_ERROR, STATE_COMPILED
from c.device.manager import DeviceManager
from c.remote.remote import Remote, ERROR_BAD_MSG, ERROR_RUNTIME
from c.ui.taskmanager import TaskManager
from c.ui.savestate import UISaveState
from c.ui.updater import Updater
from c.ui.projectcontroller import MethodItem
from c.ui.wxw.events import *
class UILogger:
def __init__(self, ui):
self.ui = ui
def write(self, msg):
self.ui.logMessage(msg)
################################################################################
# #
################################################################################
class MainController:
view = attribute("_view", "r")
def __init__(self, view, args):
self._view = view
self._args = args
self.stat = Status({"exceptions" : True}, outstream=self._view.uilog)
self.mem = Memory(self.stat)
self.mem.loadDefaultDate(Platform.getDataFilePath("default.cfg"))
self.compiler = Compiler(self.mem)
self.tm = TaskManager(self)
self.dm = DeviceManager(self)
self.r = Remote(self.dm, self.stat)
self.botRunning = False
self.saveState = UISaveState()
self.projectFilename = self.saveState.getOpt("lastproj", "")
self.defaultDir = self.saveState.getOpt("defaultDir", Platform.getDefaultDir())
self.firstSave = False
self.latestImageSize = -1
self.compiledState = {}
logging.info("base path: %s" % Platform.getBasePath())
def onStartComplete(self):
self.dm.start()
if len(self._args)>1 and os.path.exists(self._args[1]):
self.projectFilename = self._args[1]
self.loadProject()
self._view.setButtonStates(1,1,0)
elif self.projectFilename and os.path.exists(self.projectFilename):
self.loadProject()
self._view.setButtonStates(1,1,0)
else:
self.projectFilename = ""
self.updater = Updater(InfoStrings["versionString"], self.updateAvailable)
doup = True #self.saveState.getOpt("updateOnStart")
if doup:
self.updater.check()
self.saveState.setOpt("updateOnStart", True)
elif doup==None:
self.saveState.setOpt("updateOnStart", True)
def onShutdown(self):
self.saveState.save()
def onEditLibraryButton(self, editable):
self.saveState.setOpt("editablelibrary", editable)
def onAutoSwitchButton(self, autoswitch):
self.saveState.setOpt("autoswitch", autoswitch)
def checkProjectUpgrade(self):
if self.mem.oldImage:
self._view.onProjectUpgrade()
def newProject(self, name, mainclass=None):
self.mem.load(Platform.getDataFilePath("default.%s" % InfoStrings["imageExtension"]))
if mainclass:
self._view.project.controller.createNewClass(name, mainclass)
self._view.project.controller.createNewMethod("main",name)
self._view.project.controller.populate()
self._view.project.controller.jumpTo("%s>>main" % name.lower())
def closeProject(self):
self.projectFilename = ""
def openProject(self, fn):
if self.projectFilename!="":
self.closeProject()
self.loadProject(fn)
self._view.project.controller.populate()
mainCls = self.mem.getMainClass()
if mainCls:
self._view.project.controller.jumpTo("%s>>main" % mainCls.name.lower())
else:
self._view.setEmptyView()
self._view.srctext.setText("")
self._view.srctext.Enable(False)
self.dm.refresh()
self.firstSave = False
self._view.setButtonStates(1, 1, 0)
def loadProject(self, filename=None):
if filename:
self.projectFilename = filename
try:
self.mem.load(self.projectFilename)
except Exception,e:
self._view.onLoadFailed(e)
return
self._view.project.controller.populate()
if filename:
self.checkProjectUpgrade()
self.saveState.setOpt("lastproj", self.projectFilename)
self.dm.refresh()
self._view.updateTitle()
def saveProject(self):
self.saveState.setOpt("lastproj", self.projectFilename)
self._view.project.controller.refreshCurrentItem()
self.mem.save(self.projectFilename)
self._view.setStatusText("Project saved to %s" % self.projectFilename)
self._view.project.controller.changed = False
self._view.updateTitle()
def checkBotState(self, args):
res = self.r.getVMState()
if not res or len(res)<2:
return
if res[1] == 2:
err = self.r.getLastError()
ename = err[2]
eval = str(err[1])
if err[0] == ERROR_BAD_MSG:
eval = "'%s'" % self.r.getObject(err[1]).asString()
elif err[0] == ERROR_RUNTIME:
eobj = self.r.getObject(err[1])
ecls = self.r.getObject(eobj.cls)
eclsName = self.r.getObject(ecls.data[0]).asString()
if eclsName in ["String", "Symbol"]:
eval = eobj.asString()
else:
eval = eobj.asPrettyString(self.r)
errormsg = "Error: %s (%s)\n" % (ename,eval)
self._view.logMessage(errormsg)
return errormsg
else:
raise CoreException("Bad bot state %s" % res)
def isLibraryEditable(self):
return self.saveState.getOpt("editablelibrary", False)
def shouldAutoSwitch(self):
return self.saveState.getOpt("autoswitch", True)
def updateAvailable(self, update):
self._view.postEvent(UiStateEvent("update-available", update))
def deleteMethod(self, m):
if m in self.compiledState:
del self.compiledState[m]
def openHTMLDocs(self, name):
url = "file://"+os.path.join(Platform.getDataPath(), "tutorial", name)
webbrowser.open(url)
##############################################################################
def showDeviceUpgrade(self, newver, filename):
self._view.postEvent(DeviceUpgradeEvent((newver, filename)))
def addDevice(self, id, name, conn):
self._view.postEvent(DeviceChangeEvent(id, name, conn))
def removeDevice(self, id):
self._view.postEvent(DeviceChangeEvent(id))
def handleThreadException(self, excp):
if wx:
self._view.postEvent(ThreadExceptionEvent(excp))
##############################################################################
def doCompile(self, item, source, runAfter):
self.tm.createTask("compile", self.__taskFuncCompile, (item, source, runAfter))
def doRun(self, postRunFunc=None):
self.botRunning = True
self.tm.createTask("run", self.__taskFuncRun, [postRunFunc])
def doStop(self):
self.botRunning = False
self.tm.stopTask("run")
self.r.setVMState(0)
self._view.setButtonStates(1,1,0)
def doImageLoad(self):
self.tm.createTask("load", self.__taskFuncLoad)
def doUpgradeStart(self):
pass
def doUpgrade(self, fn):
self.tm.createTask("upgrade", self.__taskFuncUpgrade, [fn])
##############################################################################
def __taskFuncUpgrade(self,fn):
def progressCb(percent): pass
#if (percent%10)==0:
# self._view.postEvent(UiStateEvent("progress-update",percent))
self._view.logClear()
self._view.postEvent(UiStateEvent("button-msg", (0,0,0,1,"Upgrading robot firmware ...")))
timeStart = time.time()
try:
self.r.upgrade(fn, progressCb)
timeEnd = time.time()
self._view.logMessage("Completed in %0.2fs\n" % (timeEnd - timeStart))
except Exception,e:
self._view.logMessage("Upgrade failed: %s\n" % e)
self._view.postEvent(UiStateEvent("button-msg", (0,1,0,1, "Upgrade failed: %s" % e)))
return False
def __taskFuncLoad(self):
def progressCb(percent): pass
#if (percent%10)==0:
# self._view.postEvent(UiStateEvent("progress-update", percent))
for meth in self.compiledState:
state, errdata = self.compiledState[meth]
if state==STATE_ERROR:
self._view.postEvent(UiStateEvent("button-msg", (1,1,0,1, "Can't run, error in project")))
self._view.project.controller.showSource(meth.incls.name,meth.name,0)
self._view.srctext.errorLine(errdata)
return False
self._view.logClear()
self._view.postEvent(UiStateEvent("button-msg", (0,0,0,1,"Uploading image to robot ...")))
timeStart = time.time()
compileOk = self.mem.readyForSave()
if not compileOk:
self._view.logMessage("Image generation failed: no main method found\n")
self._view.postEvent(UiStateEvent("button-msg",
(1,1,0,1, "Image generation failed: no main method found")))
return False
img = CMG(self.mem)
imgbuf = img.saveToBuf()
self.latestImageSize = img.imageSize
self._view.logMessage("%d/24Kb (%d%%) used\n" % (
(img.imageSize/1024),int(img.imageSize)/(24.0*1024)*100.0))
try:
self.r.uploadCMG(imgbuf, progressCb)
timeEnd = time.time()
self._view.logMessage("Completed in %0.2fs\n" % (timeEnd - timeStart))
except Exception,e:
self._view.logMessage("Upload failed: %s\n" % e)
self._view.postEvent(UiStateEvent("button-msg", (0,1,0,1, "Upload failed: %s" % e)))
return False
self.doRun()
def __taskFuncRun(self, postRunFunc):
self._view.postEvent(UiStateEvent("start", None))
self._view.postEvent(UiStateEvent("button-msg", (0,0,1,1, "Running ...")))
if self.shouldAutoSwitch():
self._view.postEvent(UiStateEvent("change-view", "sim"))
self.r.setVMState(1)
while self.botRunning:
res = self.r.getVMState()
if not res or len(res)<2:
break
if (res[1]!=1):
if res[1]!=0:
self._view.postEvent(UiStateEvent("trace", "Runtime Error"))
break
time.sleep(0.01)
self.botRunning = False
if postRunFunc:
self._view.postEvent(UiStateEvent("post-run", postRunFunc))
self._view.postEvent(UiStateEvent("button-msg", (1,1,0,1,"")))
def __taskFuncCompile(self, item, source, runAfter=False):
self._view.postEvent(UiStateEvent("button", (0,0,0,1)))
method = item.obj
self._view.logClear()
timeStart = time.time()
self._view.srctext.errorClear()
try:
c = self.compiler
c.compileMethod(method.incls, source)
except CoreException, e:
self._view.postEvent(UiStateEvent("button-msg", (1,1,0,1, "Check failed: %s" % e)))
self._view.logMessage("Check of %s in %s failed:\n" % (
method.name, method.incls.name))
self._view.logMessage("%s\n" % e)
selItem = self._view.project.controller.getSelectedItem()
if isinstance(selItem, MethodItem) and selItem.obj == method and e.data:
self._view.srctext.errorLine(e.data)
method.state = STATE_ERROR
self.compiledState[method] = (method.state, e.data)
self._view.postEvent(CompileEvent((item, 0)))
return False
except Exception, e:
self._view.postEvent(UiStateEvent("button-msg", (1,1,0,1, "Fatal compile error: %s" % e)))
self._view.logMessage("Compilation of %s in %s failed fatally:\n" % (
method.name, method.incls.name))
self._view.logMessage("%s\n" % e)
method.state = STATE_ERROR
self.compiledState[method] = (method.state, None)
self._view.postEvent(CompileEvent((item, 0)))
return False
nbytes = len(method.bytecodes)
if not runAfter:
self._view.postEvent(UiStateEvent("button-msg", (1,1,0,1, "Check OK")))
self._view.project.controller.changed = True
msg = "Check of %s in %s succeeded\n" % (
method.name, method.incls.name)
self._view.logMessage(msg)
self._view.logMessage("%d bytes used\n" % nbytes)
method.state = STATE_COMPILED
self.compiledState[method] = (method.state, None)
self._view.postEvent(CompileEvent((item, 1)))
time.sleep(0.1)
if runAfter:
self.doImageLoad()
return True
| Python |
# vim:ts=4:sw=4:noet:
""" Dialog Controllers """
from c.ui.wxw.dialogs import GetInfoMethodDialog, GetInfoRobotDialog
from c.compiler.disassemble import *
import c.compiler.spy as spy
class GetInfoMethod:
def __init__(self, parent, pitem):
self.dialog = GetInfoMethodDialog(parent=parent, id=-1, title="Method - %s" % pitem.name)
obj = pitem.obj
cls = pitem.clsitem.obj
if pitem.type=="cmethod":
cls = cls.cls
self.dialog.SetTitle("Method - %s" % obj.name)
# name
self.dialog.lblSignature.SetLabel(obj.name)
self.dialog.lblInClass.SetLabel(cls.name)
# bytecodes
asm, instCount = disassembleMethod(obj.bytecodes, obj.literals)
self.dialog.lblByteInfo.SetLabel("%d instructions, %d bytes" % (instCount, len(obj.bytecodes)))
self.dialog.textBytecodes.setText(asm)
self.dialog.textBytecodes.SetReadOnly(True)
# literals
self.dialog.lblLitInfo.SetLabel("%d literals" % len(obj.literals))
for lit in obj.literals:
self.dialog.listLiterals.Append(lit.asString())
# state
if obj.state==spy.STATE_COMPILED:
self.dialog.lblState.SetLabel("Compiled")
elif obj.state==spy.STATE_ERROR:
self.dialog.lblState.SetLabel("Error")
else:
self.dialog.lblState.SetLabel("Uncompiled")
self.dialog.SetMinSize(self.dialog.mainSizer.GetMinSize())
self.dialog.Fit()
self.dialog.Centre()
def do(self):
return self.dialog.ShowModal()
class GetInfoRobot:
def __init__(self, parent, pitem):
self.dialog = GetInfoRobotDialog(parent, "Robot - %s" % pitem.name)
vdate, vtime, rev = parent.controller.r.getVersion()
lval = "%s (%s/%s/%s)" % (rev, vdate[4:], vdate[2:4], vdate[:2])
self.dialog.lblVersion.SetLabel(lval)
plat, arch = parent.controller.r.getPlatform()
lval = "%s (%s)" % (plat, arch)
self.dialog.lblPlatform.SetLabel(lval)
mused = parent.controller.latestImageSize
mtotal = 24*1024
mval = "Unknown"
if mused!=-1:
mval = "%d/%dKb (%d%%)" % (mused/1024, mtotal/1024, mused/float(mtotal)*100.0)
self.dialog.lblMemory.SetLabel(mval)
self.dialog.fit()
def do(self):
return self.dialog.ShowModal()
| Python |
# vim:ts=4:sw=4:noet:
import sys
installbin = "#release"
if sys.platform == 'darwin':
installdata = "%s/Foxtalk.app/Contents/Resources" % installbin
else:
installdata = "%s/data" % installbin
Export('installbin', 'installdata')
SConscript(["foxtalk/SConstruct"])
| Python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "four_year_plan_v1.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'afshar@google.com (Ali Afshar)'
# Add the library location to the path
import sys
sys.path.insert(0, 'lib')
import os
import httplib2
import sessions
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build
from apiclient.http import MediaUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from oauth2client.client import AccessTokenRefreshError
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
def SibPath(name):
"""Generate a path that is a sibling of this file.
Args:
name: Name of sibling file.
Returns:
Path to sibling file.
"""
return os.path.join(os.path.dirname(__file__), name)
# Load the secret that is used for client side sessions
# Create one of these for yourself with, for example:
# python -c "import os; print os.urandom(64)" > session-secret
SESSION_SECRET = open(SibPath('session.secret')).read()
INDEX_HTML = open(SibPath('index.html')).read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials.
The CredentialsProperty is provided by the Google API Python Client, and is
used by the Storage classes to store OAuth 2.0 credentials in the data store."""
credentials = CredentialsProperty()
def CreateService(service, version, creds):
"""Create a Google API service.
Load an API service from a discovery document and authorize it with the
provided credentials.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
# Instantiate an Http instance
http = httplib2.Http()
# Authorize the Http instance with the passed credentials
creds.authorize(http)
# Build a service from the passed discovery document path
return build(service, version, http=http)
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
"""Create a new instance of drive state.
Parse and load the JSON state parameter.
Args:
state: State query parameter as a string.
"""
if state:
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
else:
self.action = 'create'
self.ids = []
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get('state'))
class BaseDriveHandler(webapp.RequestHandler):
"""Base request handler for drive applications.
Adds Authorization support for Drive.
"""
def CreateOAuthFlow(self):
"""Create OAuth2.0 flow controller
This controller can be used to perform all parts of the OAuth 2.0 dance
including exchanging an Authorization code.
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = flow_from_clientsecrets('client_secrets.json', scope='')
# Dynamically set the redirect_uri based on the request URL. This is extremely
# convenient for debugging to an alternative host without manually setting the
# redirect URI.
flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0]
return flow
def GetCodeCredentials(self):
"""Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0.
The authorization code is extracted form the URI parameters. If it is absent,
None is returned immediately. Otherwise, if it is present, it is used to
perform step 2 of the OAuth 2.0 web server flow.
Once a token is received, the user information is fetched from the userinfo
service and stored in the session. The token is saved in the datastore against
the user ID received from the userinfo service.
Args:
request: HTTP request used for extracting an authorization code and the
session information.
Returns:
OAuth2.0 credentials suitable for authorizing clients or None if
Authorization could not take place.
"""
# Other frameworks use different API to get a query parameter.
code = self.request.get('code')
if not code:
# returns None to indicate that no code was passed from Google Drive.
return None
# Auth flow is a controller that is loaded with the client information,
# including client_id, client_secret, redirect_uri etc
oauth_flow = self.CreateOAuthFlow()
# Perform the exchange of the code. If there is a failure with exchanging
# the code, return None.
try:
creds = oauth_flow.step2_exchange(code)
except FlowExchangeError:
return None
# Create an API service that can use the userinfo API. Authorize it with our
# credentials that we gained from the code exchange.
users_service = CreateService('oauth2', 'v2', creds)
# Make a call against the userinfo service to retrieve the user's information.
# In this case we are interested in the user's "id" field.
userid = users_service.userinfo().get().execute().get('id')
# Store the user id in the user's cookie-based session.
session = sessions.LilCookies(self, SESSION_SECRET)
session.set_secure_cookie(name='userid', value=userid)
# Store the credentials in the data store using the userid as the key.
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(self):
"""Get OAuth 2.0 credentials for an HTTP session.
If the user has a user id stored in their cookie session, extract that value
and use it to load that user's credentials from the data store.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
# Try to load the user id from the session
session = sessions.LilCookies(self, SESSION_SECRET)
userid = session.get_secure_cookie(name='userid')
if not userid:
# return None to indicate that no credentials could be loaded from the
# session.
return None
# Load the credentials from the data store, using the userid as a key.
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
# if the credentials are invalid, return None to indicate that the credentials
# cannot be used.
if creds and creds.invalid:
return None
return creds
def RedirectAuth(self):
"""Redirect a handler to an authorization page.
Used when a handler fails to fetch credentials suitable for making Drive API
requests. The request is redirected to an OAuth 2.0 authorization approval
page and on approval, are returned to application.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = self.CreateOAuthFlow()
# Manually add the required scopes. Since this redirect does not originate
# from the Google Drive UI, which authomatically sets the scopes that are
# listed in the API Console.
flow.scope = ALL_SCOPES
# Create the redirect URI by performing step 1 of the OAuth 2.0 web server
# flow.
uri = flow.step1_get_authorize_url(flow.redirect_uri)
# Perform the redirect.
self.redirect(uri)
def RespondJSON(self, data):
"""Generate a JSON response and return it to the client.
Args:
data: The data that will be converted to JSON to return.
"""
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(data))
def CreateAuthorizedService(self, service, version):
"""Create an authorize service instance.
The service can only ever retrieve the credentials from the session.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
Returns:
Authorized service or redirect to authorization flow if no credentials.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create a Drive service
# instance.
return CreateService(service, version, creds)
else:
# If no credentials could be loaded from the session, redirect the user to
# the authorization page.
self.RedirectAuth()
def CreateDrive(self):
"""Create a drive client instance."""
return self.CreateAuthorizedService('drive', 'v2')
def CreateUserInfo(self):
"""Create a user info client instance."""
return self.CreateAuthorizedService('oauth2', 'v2')
class MainPage(BaseDriveHandler):
"""Web handler for the main page.
Handles requests and returns the user interface for Open With and Create
cases. Responsible for parsing the state provided from the Drive UI and acting
appropriately.
"""
def get(self):
"""Handle GET for Create New and Open With.
This creates an authorized client, and checks whether a resource id has
been passed or not. If a resource ID has been passed, this is the Open
With use-case, otherwise it is the Create New use-case.
"""
# Generate a state instance for the request, this includes the action, and
# the file id(s) that have been sent from the Drive user interface.
drive_state = DriveState.FromRequest(self.request)
if drive_state.action == 'open' and len(drive_state.ids) > 0:
code = self.request.get('code')
if code:
code = '?code=%s' % code
self.redirect('/#edit/%s%s' % (drive_state.ids[0], code))
return
# Fetch the credentials by extracting an OAuth 2.0 authorization code from
# the request URL. If the code is not present, redirect to the OAuth 2.0
# authorization URL.
creds = self.GetCodeCredentials()
if not creds:
return self.RedirectAuth()
# Extract the numerical portion of the client_id from the stored value in
# the OAuth flow. You could also store this value as a separate variable
# somewhere.
client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0]
self.RenderTemplate()
def RenderTemplate(self):
"""Render a named template in a context."""
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write(INDEX_HTML)
class ServiceHandler(BaseDriveHandler):
"""Web handler for the service to read and write to Drive."""
def post(self):
"""Called when HTTP POST requests are received by the web application.
The POST body is JSON which is deserialized and used as values to create a
new file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
# Create a new file data structure.
resource = {
'title': data['title'],
'description': data['description'],
'mimeType': data['mimeType'],
}
try:
# Make an insert request to create a new file. A MediaInMemoryUpload
# instance is used to upload the file body.
resource = service.files().insert(
body=resource,
media_body=MediaInMemoryUpload(
data.get('content', ''),
data['mimeType'],
resumable=True)
).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def get(self):
"""Called when HTTP GET requests are received by the web application.
Use the query parameter file_id to fetch the required file's metadata then
content and return it as a JSON object.
Since DrEdit deals with text files, it is safe to dump the content directly
into JSON, but this is not the case with binary files, where something like
Base64 encoding is more appropriate.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
# Requests are expected to pass the file_id query parameter.
file_id = self.request.get('file_id')
if file_id:
# Fetch the file metadata by making the service.files().get method of
# the Drive API.
f = service.files().get(fileId=file_id).execute()
downloadUrl = f.get('downloadUrl')
# If a download URL is provided in the file metadata, use it to make an
# authorized request to fetch the file ontent. Set this content in the
# data to return as the 'content' field. If there is no downloadUrl,
# just set empty content.
if downloadUrl:
resp, f['content'] = service._http.request(downloadUrl)
else:
f['content'] = ''
else:
f = None
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(f)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
def put(self):
"""Called when HTTP PUT requests are received by the web application.
The PUT body is JSON which is deserialized and used as values to update
a file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
try:
# Create a new file data structure.
content = data.get('content')
if 'content' in data:
data.pop('content')
if content is not None:
# Make an update request to update the file. A MediaInMemoryUpload
# instance is used to upload the file body. Because of a limitation, this
# request must be made in two parts, the first to update the metadata, and
# the second to update the body.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data,
media_body=MediaInMemoryUpload(
content, data['mimeType'], resumable=True)
).execute()
else:
# Only update the metadata, a patch request is prefered but not yet
# supported on Google App Engine; see
# http://code.google.com/p/googleappengine/issues/detail?id=6316.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def RequestJSON(self):
"""Load the request body as JSON.
Returns:
Request body loaded as JSON or None if there is no request body.
"""
if self.request.body:
return json.loads(self.request.body)
class UserHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateUserInfo()
if service is None:
return
try:
result = service.userinfo().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class AboutHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
result = service.about().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
# Create an WSGI application suitable for running on App Engine
application = webapp.WSGIApplication(
[('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler),
('/user', UserHandler)],
# XXX Set to False in production.
debug=True
)
def main():
"""Main entry point for executing a request with this handler."""
run_wsgi_app(application)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'afshar@google.com (Ali Afshar)'
import os
import httplib2
import sessions
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build_from_document
from apiclient.http import MediaUpload
from oauth2client import client
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
APIS_BASE = 'https://www.googleapis.com'
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
CODE_PARAMETER = 'code'
STATE_PARAMETER = 'state'
SESSION_SECRET = open('session.secret').read()
DRIVE_DISCOVERY_DOC = open('drive.json').read()
USERS_DISCOVERY_DOC = open('users.json').read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials."""
credentials = CredentialsProperty()
def CreateOAuthFlow(request):
"""Create OAuth2.0 flow controller
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = client.flow_from_clientsecrets('client-debug.json', scope='')
flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/')
return flow
def GetCodeCredentials(request):
"""Create OAuth2.0 credentials by extracting a code and performing OAuth2.0.
Args:
request: HTTP request used for extracting an authorization code.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
code = request.get(CODE_PARAMETER)
if code:
oauth_flow = CreateOAuthFlow(request)
creds = oauth_flow.step2_exchange(code)
users_service = CreateService(USERS_DISCOVERY_DOC, creds)
userid = users_service.userinfo().get().execute().get('id')
request.session.set_secure_cookie(name='userid', value=userid)
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(request):
"""Get OAuth2.0 credentials for an HTTP session.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
userid = request.session.get_secure_cookie(name='userid')
if userid:
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
if creds and not creds.invalid:
return creds
def CreateService(discovery_doc, creds):
"""Create a Google API service.
Args:
discovery_doc: Discovery doc used to configure service.
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
http = httplib2.Http()
creds.authorize(http)
return build_from_document(discovery_doc, APIS_BASE, http=http)
def RedirectAuth(handler):
"""Redirect a handler to an authorization page.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = CreateOAuthFlow(handler.request)
flow.scope = ALL_SCOPES
uri = flow.step1_get_authorize_url(flow.redirect_uri)
handler.redirect(uri)
def CreateDrive(handler):
"""Create a fully authorized drive service for this handler.
Args:
handler: RequestHandler from which drive service is generated.
Returns:
Authorized drive service, generated from the handler request.
"""
request = handler.request
request.session = sessions.LilCookies(handler, SESSION_SECRET)
creds = GetCodeCredentials(request) or GetSessionCredentials(request)
if creds:
return CreateService(DRIVE_DISCOVERY_DOC, creds)
else:
RedirectAuth(handler)
def ServiceEnabled(view):
"""Decorator to inject an authorized service into an HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
response_data = view(handler, service)
handler.response.headers['Content-Type'] = 'text/html'
handler.response.out.write(response_data)
return ServiceDecoratedView
def ServiceEnabledJson(view):
"""Decorator to inject an authorized service into a JSON HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
if handler.request.body:
data = json.loads(handler.request.body)
else:
data = None
response_data = json.dumps(view(handler, service, data))
handler.response.headers['Content-Type'] = 'application/json'
handler.response.out.write(response_data)
return ServiceDecoratedView
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
self.ParseState(state)
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get(STATE_PARAMETER))
def ParseState(self, state):
"""Parse a state parameter and set internal values.
Args:
state: State parameter to parse.
"""
if state.startswith('{'):
self.ParseJsonState(state)
else:
self.ParsePlainState(state)
def ParseJsonState(self, state):
"""Parse a state parameter that is JSON.
Args:
state: State parameter to parse
"""
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
def ParsePlainState(self, state):
"""Parse a state parameter that is a plain resource id or missing.
Args:
state: State parameter to parse
"""
if state:
self.action = 'open'
self.ids = [state]
else:
self.action = 'create'
self.ids = []
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def RenderTemplate(name, **context):
"""Render a named template in a context.
Args:
name: Template name.
context: Keyword arguments to render as template variables.
"""
return template.render(name, context)
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import base64
import urllib
import time
import random
import urlparse
import hmac
import binascii
import httplib2
try:
from urlparse import parse_qs
parse_qs # placate pyflakes
except ImportError:
# fall back for Python 2.5
from cgi import parse_qs
try:
from hashlib import sha1
sha = sha1
except ImportError:
# hashlib was added in Python 2.5
import sha
import _version
__version__ = _version.__version__
OAUTH_VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class Error(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occurred.'):
self._message = message
@property
def message(self):
"""A hack to get around the deprecation errors in 2.6."""
return self._message
def __str__(self):
return self._message
class MissingSignature(Error):
pass
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def build_xoauth_string(url, consumer, token=None):
"""Build an XOAUTH string for use in SMTP/IMPA authentication."""
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.iteritems()):
if v is not None:
params.append('%s="%s"' % (k, escape(v)))
return "%s %s %s" % ("GET", url, ','.join(params))
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. """
if not isinstance(s, unicode):
if not isinstance(s, str):
raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s))
try:
s = s.decode('utf-8')
except UnicodeDecodeError, le:
raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,))
return s
def to_utf8(s):
return to_unicode(s).encode('utf-8')
def to_unicode_if_string(s):
if isinstance(s, basestring):
return to_unicode(s)
else:
return s
def to_utf8_if_string(s):
if isinstance(s, basestring):
return to_utf8(s)
else:
return s
def to_unicode_optional_iterator(x):
"""
Raise TypeError if x is a str containing non-utf8 bytes or if x is
an iterable which contains such a str.
"""
if isinstance(x, basestring):
return to_unicode(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_unicode(e) for e in l ]
def to_utf8_optional_iterator(x):
"""
Raise TypeError if x is a str or if x is an iterable which
contains a str.
"""
if isinstance(x, basestring):
return to_utf8(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_utf8_if_string(e) for e in l ]
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s.encode('utf-8'), safe='~')
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class Consumer(object):
"""A consumer of OAuth-protected services.
The OAuth consumer is a "third-party" service that wants to access
protected resources from an OAuth service provider on behalf of an end
user. It's kind of the OAuth client.
Usually a consumer must be registered with the service provider by the
developer of the consumer software. As part of that process, the service
provider gives the consumer a *key* and a *secret* with which the consumer
software can identify itself to the service. The consumer will include its
key in each request to identify itself, but will use its secret only when
signing requests, to prove that the request is from that particular
registered consumer.
Once registered, the consumer can then use its consumer credentials to ask
the service provider for a request token, kicking off the OAuth
authorization process.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def __str__(self):
data = {'oauth_consumer_key': self.key,
'oauth_consumer_secret': self.secret}
return urllib.urlencode(data)
class Token(object):
"""An OAuth credential used to request authorization or a protected
resource.
Tokens in OAuth comprise a *key* and a *secret*. The key is included in
requests to identify the token being used, but the secret is used only in
the signature, to prove that the requester is who the server gave the
token to.
When first negotiating the authorization, the consumer asks for a *request
token* that the live user authorizes with the service provider. The
consumer then exchanges the request token for an *access token* that can
be used to access protected resources.
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
"""Returns this token as a plain string, suitable for storage.
The resulting string includes the token's secret, so you should never
send or store this string where a third party can read it.
"""
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
@staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
def __str__(self):
return self.to_string()
def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter)
class Request(dict):
"""The parameters and information for an HTTP request, suitable for
authorizing with OAuth credentials.
When a consumer wants to access a service's protected resources, it does
so using a signed HTTP request identifying itself (the consumer) with its
key, and providing an access token authorized by the end user to access
those resources.
"""
version = OAUTH_VERSION
def __init__(self, method=HTTP_METHOD, url=None, parameters=None,
body='', is_form_encoded=False):
if url is not None:
self.url = to_unicode(url)
self.method = method
if parameters is not None:
for k, v in parameters.iteritems():
k = to_unicode(k)
v = to_unicode_optional_iterator(v)
self[k] = v
self.body = body
self.is_form_encoded = is_form_encoded
@setter
def url(self, value):
self.__dict__['url'] = value
if value is not None:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
if scheme not in ('http', 'https'):
raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
# Normalized URL excludes params, query, and fragment.
self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
else:
self.normalized_url = None
self.__dict__['url'] = None
@setter
def method(self, value):
self.__dict__['method'] = value.upper()
def _get_timestamp_nonce(self):
return self['oauth_timestamp'], self['oauth_nonce']
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
return dict([(k, v) for k, v in self.iteritems()
if not k.startswith('oauth_')])
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
params_header = ', '.join(header_params)
auth_header = 'OAuth realm="%s"' % realm
if params_header:
auth_header = "%s, %s" % (auth_header, params_header)
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
d = {}
for k, v in self.iteritems():
d[k.encode('utf-8')] = to_utf8_optional_iterator(v)
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will
# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
return urllib.urlencode(d, True).replace('+', '%20')
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse.urlparse(self.url)
try:
query = base_url.query
except AttributeError:
# must be python <2.5
query = base_url[4]
query = parse_qs(query)
for k, v in self.items():
query.setdefault(k, []).append(v)
try:
scheme = base_url.scheme
netloc = base_url.netloc
path = base_url.path
params = base_url.params
fragment = base_url.fragment
except AttributeError:
# must be python <2.5
scheme = base_url[0]
netloc = base_url[1]
path = base_url[2]
params = base_url[3]
fragment = base_url[5]
url = (scheme, netloc, path, params,
urllib.urlencode(query, True), fragment)
return urlparse.urlunparse(url)
def get_parameter(self, parameter):
ret = self.get(parameter)
if ret is None:
raise Error('Parameter not found: %s' % parameter)
return ret
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
items = []
for key, value in self.iteritems():
if key == 'oauth_signature':
continue
# 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
# so we unpack sequence values into multiple items for sorting.
if isinstance(value, basestring):
items.append((to_utf8_if_string(key), to_utf8(value)))
else:
try:
value = list(value)
except TypeError, e:
assert 'is not iterable' in str(e)
items.append((to_utf8_if_string(key), to_utf8_if_string(value)))
else:
items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value)
# Include any query string parameters from the provided URL
query = urlparse.urlparse(self.url)[4]
url_items = self._split_url_string(query).items()
url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ]
items.extend(url_items)
items.sort()
encoded_str = urllib.urlencode(items)
# Encode signature parameters per Oauth Core 1.0 protocol
# spec draft 7, section 3.6
# (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
# Spaces must be encoded with "%20" instead of "+"
return encoded_str.replace('+', '%20').replace('%7E', '~')
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of sign."""
if not self.is_form_encoded:
# according to
# http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
# section 4.1.1 "OAuth Consumers MUST NOT include an
# oauth_body_hash parameter on requests with form-encoded
# request bodies."
self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest())
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
@classmethod
def make_timestamp(cls):
"""Get seconds since epoch (UTC)."""
return str(int(time.time()))
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = cls._split_header(auth_header)
parameters.update(header_params)
except:
raise Error('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = cls._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = cls._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return cls(http_method, http_url, parameters)
return None
@classmethod
def from_consumer_and_token(cls, consumer, token=None,
http_method=HTTP_METHOD, http_url=None, parameters=None,
body='', is_form_encoded=False):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': consumer.key,
'oauth_timestamp': cls.make_timestamp(),
'oauth_nonce': cls.make_nonce(),
'oauth_version': cls.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.verifier:
parameters['oauth_verifier'] = token.verifier
return Request(http_method, http_url, parameters, body=body,
is_form_encoded=is_form_encoded)
@classmethod
def from_token_and_callback(cls, token, callback=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return cls(http_method, http_url, parameters)
@staticmethod
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
@staticmethod
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
class Client(httplib2.Http):
"""OAuthClient is a worker to attempt to execute a request."""
def __init__(self, consumer, token=None, cache=None, timeout=None,
proxy_info=None):
if consumer is not None and not isinstance(consumer, Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, Token):
raise ValueError("Invalid token.")
self.consumer = consumer
self.token = token
self.method = SignatureMethod_HMAC_SHA1()
httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
def set_signature_method(self, method):
if not isinstance(method, SignatureMethod):
raise ValueError("Invalid signature method.")
self.method = method
def request(self, uri, method="GET", body='', headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
if method == "POST":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_POST_CONTENT_TYPE)
is_form_encoded = \
headers.get('Content-Type') == 'application/x-www-form-urlencoded'
if is_form_encoded and body:
parameters = parse_qs(body)
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters, body=body, is_form_encoded=is_form_encoded)
req.sign_request(self.method, self.consumer, self.token)
schema, rest = urllib.splittype(uri)
if rest.startswith('//'):
hierpart = '//'
else:
hierpart = ''
host, rest = urllib.splithost(rest)
realm = schema + ':' + hierpart + host
if is_form_encoded:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header(realm=realm))
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
class Server(object):
"""A skeletal implementation of a service provider, providing protected
resources to requests from authorized consumers.
This class implements the logic to check requests for authorization. You
can use it with your web server or web framework to protect certain
resources with OAuth.
"""
timestamp_threshold = 300 # In seconds, five minutes.
version = OAUTH_VERSION
signature_methods = None
def __init__(self, signature_methods=None):
self.signature_methods = signature_methods or {}
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.name] = signature_method
return self.signature_methods
def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
self._check_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _check_version(self, request):
"""Verify the correct version of the request for this server."""
version = self._get_version(request)
if version and version != self.version:
raise Error('OAuth version %s not supported.' % str(version))
def _get_version(self, request):
"""Return the version of the request for this server."""
try:
version = request.get_parameter('oauth_version')
except:
version = OAUTH_VERSION
return version
def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_verifier(self, request):
return request.get_parameter('oauth_verifier')
def _check_signature(self, request, consumer, token):
timestamp, nonce = request._get_timestamp_nonce()
self._check_timestamp(timestamp)
signature_method = self._get_signature_method(request)
try:
signature = request.get_parameter('oauth_signature')
except:
raise MissingSignature('Missing oauth_signature.')
# Validate the signature.
valid = signature_method.check(request, consumer, token, signature)
if not valid:
key, base = signature_method.signing_base(request, consumer, token)
raise Error('Invalid signature. Expected signature base '
'string: %s' % base)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' % (timestamp, now,
self.timestamp_threshold))
class SignatureMethod(object):
"""A way of signing requests.
The OAuth protocol lets consumers and service providers pick a way to sign
requests. This interface shows the methods expected by the other `oauth`
modules for signing requests. Subclass it and implement its methods to
provide a new way to sign requests.
"""
def signing_base(self, request, consumer, token):
"""Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.
"""
raise NotImplementedError
def sign(self, request, consumer, token):
"""Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.
"""
raise NotImplementedError
def check(self, request, consumer, token, signature):
"""Returns whether the given signature is the correct signature for
the given consumer and token signing the given request."""
built = self.sign(request, consumer, token)
return built == signature
class SignatureMethod_HMAC_SHA1(SignatureMethod):
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token):
if not hasattr(request, 'normalized_url') or request.normalized_url is None:
raise ValueError("Base URL for request is not set.")
sig = (
escape(request.method),
escape(request.normalized_url),
escape(request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class SignatureMethod_PLAINTEXT(SignatureMethod):
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def sign(self, request, consumer, token):
key, raw = self.signing_base(request, consumer, token)
return raw
| Python |
# This is the version of this source code.
manual_verstr = "1.5"
auto_build_num = "211"
verstr = manual_verstr + "." + auto_build_num
try:
from pyutil.version_class import Version as pyutil_Version
__version__ = pyutil_Version(verstr)
except (ImportError, ValueError):
# Maybe there is no pyutil installed.
from distutils.version import LooseVersion as distutils_Version
__version__ = distutils_Version(verstr)
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import imaplib
class IMAP4_SSL(imaplib.IMAP4_SSL):
"""IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
lambda x: oauth2.build_xoauth_string(url, consumer, token))
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import smtplib
import base64
class SMTP(smtplib.SMTP):
"""SMTP wrapper for smtplib.SMTP that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
self.docmd('AUTH', 'XOAUTH %s' % \
base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line tools for authenticating via OAuth 2.0
Do the OAuth 2.0 Web Server dance for a command line application. Stores the
generated credentials in a common file that is used by other example apps in
the same directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ['run']
import BaseHTTPServer
import gflags
import socket
import sys
import webbrowser
from client import FlowExchangeError
from client import OOB_CALLBACK_URN
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True,
('Run a local web server to handle redirects during '
'OAuth authorization.'))
gflags.DEFINE_string('auth_host_name', 'localhost',
('Host name to use when running a local web server to '
'handle redirects during OAuth authorization.'))
gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
('Port to use when running a local web server to '
'handle redirects during OAuth authorization.'))
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
"""A server to handle OAuth 2.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into query_params and then stops serving.
"""
query_params = {}
class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler for OAuth 2.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into the servers query_params and then stops serving.
"""
def do_GET(s):
"""Handle a GET request.
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
def log_message(self, format, *args):
"""Do not log messages to stdout while running as command line program."""
pass
def run(flow, storage, http=None):
"""Core code for a command-line application.
Args:
flow: Flow, an OAuth 2.0 Flow to step through.
storage: Storage, a Storage to store the credential in.
http: An instance of httplib2.Http.request
or something that acts like it.
Returns:
Credentials, the obtained credential.
"""
if FLAGS.auth_local_webserver:
success = False
port_number = 0
for port in FLAGS.auth_host_port:
port_number = port
try:
httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
ClientRedirectHandler)
except socket.error, e:
pass
else:
success = True
break
FLAGS.auth_local_webserver = success
if not success:
print 'Failed to start a local webserver listening on either port 8080'
print 'or port 9090. Please check your firewall settings and locally'
print 'running programs that may be blocking or using those ports.'
print
print 'Falling back to --noauth_local_webserver and continuing with',
print 'authorization.'
print
if FLAGS.auth_local_webserver:
oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
else:
oauth_callback = OOB_CALLBACK_URN
authorize_url = flow.step1_get_authorize_url(oauth_callback)
if FLAGS.auth_local_webserver:
webbrowser.open(authorize_url, new=1, autoraise=True)
print 'Your browser has been opened to visit:'
print
print ' ' + authorize_url
print
print 'If your browser is on a different machine then exit and re-run this'
print 'application with the command-line parameter '
print
print ' --noauth_local_webserver'
print
else:
print 'Go to the following link in your browser:'
print
print ' ' + authorize_url
print
code = None
if FLAGS.auth_local_webserver:
httpd.handle_request()
if 'error' in httpd.query_params:
sys.exit('Authentication request was rejected.')
if 'code' in httpd.query_params:
code = httpd.query_params['code']
else:
print 'Failed to find "code" in the query parameters of the redirect.'
sys.exit('Try running with --noauth_local_webserver.')
else:
code = raw_input('Enter verification code: ').strip()
try:
credential = flow.step2_exchange(code, http)
except FlowExchangeError, e:
sys.exit('Authentication has failed: %s' % e)
storage.put(credential)
credential.set_store(storage)
print 'Authentication successful.'
return credential
| Python |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Multi-credential file store with lock support.
This module implements a JSON credential store where multiple
credentials can be stored in one file. That file supports locking
both in a single process and across processes.
The credential themselves are keyed off of:
* client_id
* user_agent
* scope
The format of the stored data is like so:
{
'file_version': 1,
'data': [
{
'key': {
'clientId': '<client id>',
'userAgent': '<user agent>',
'scope': '<scope>'
},
'credential': {
# JSON serialized Credentials.
}
}
]
}
"""
__author__ = 'jbeda@google.com (Joe Beda)'
import base64
import errno
import logging
import os
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
from locked_file import LockedFile
logger = logging.getLogger(__name__)
# A dict from 'filename'->_MultiStore instances
_multistores = {}
_multistores_lock = threading.Lock()
class Error(Exception):
"""Base error for this module."""
pass
class NewerCredentialStoreError(Error):
"""The credential store is a newer version that supported."""
pass
def get_credential_storage(filename, client_id, user_agent, scope,
warn_on_readonly=True):
"""Get a Storage instance for a credential.
Args:
filename: The JSON file storing a set of credentials
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: string or list of strings, Scope(s) being requested
warn_on_readonly: if True, log a warning if the store is readonly
Returns:
An object derived from client.Storage for getting/setting the
credential.
"""
filename = os.path.realpath(os.path.expanduser(filename))
_multistores_lock.acquire()
try:
multistore = _multistores.setdefault(
filename, _MultiStore(filename, warn_on_readonly))
finally:
_multistores_lock.release()
if type(scope) is list:
scope = ' '.join(scope)
return multistore._get_storage(client_id, user_agent, scope)
class _MultiStore(object):
"""A file backed store for multiple credentials."""
def __init__(self, filename, warn_on_readonly=True):
"""Initialize the class.
This will create the file if necessary.
"""
self._file = LockedFile(filename, 'r+b', 'rb')
self._thread_lock = threading.Lock()
self._read_only = False
self._warn_on_readonly = warn_on_readonly
self._create_file_if_needed()
# Cache of deserialized store. This is only valid after the
# _MultiStore is locked or _refresh_data_cache is called. This is
# of the form of:
#
# (client_id, user_agent, scope) -> OAuth2Credential
#
# If this is None, then the store hasn't been read yet.
self._data = None
class _Storage(BaseStorage):
"""A Storage object that knows how to read/write a single credential."""
def __init__(self, multistore, client_id, user_agent, scope):
self._multistore = multistore
self._client_id = client_id
self._user_agent = user_agent
self._scope = scope
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
self._multistore._lock()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._multistore._unlock()
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
credential = self._multistore._get_credential(
self._client_id, self._user_agent, self._scope)
if credential:
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._update_credential(credentials, self._scope)
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._delete_credential(self._client_id, self._user_agent,
self._scope)
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._file.filename()):
old_umask = os.umask(0177)
try:
open(self._file.filename(), 'a+b').close()
finally:
os.umask(old_umask)
def _lock(self):
"""Lock the entire multistore."""
self._thread_lock.acquire()
self._file.open_and_lock()
if not self._file.is_locked():
self._read_only = True
if self._warn_on_readonly:
logger.warn('The credentials file (%s) is not writable. Opening in '
'read-only mode. Any refreshed credentials will only be '
'valid for this run.' % self._file.filename())
if os.path.getsize(self._file.filename()) == 0:
logger.debug('Initializing empty multistore file')
# The multistore is empty so write out an empty file.
self._data = {}
self._write()
elif not self._read_only or self._data is None:
# Only refresh the data if we are read/write or we haven't
# cached the data yet. If we are readonly, we assume is isn't
# changing out from under us and that we only have to read it
# once. This prevents us from whacking any new access keys that
# we have cached in memory but were unable to write out.
self._refresh_data_cache()
def _unlock(self):
"""Release the lock on the multistore."""
self._file.unlock_and_close()
self._thread_lock.release()
def _locked_json_read(self):
"""Get the raw content of the multistore file.
The multistore must be locked when this is called.
Returns:
The contents of the multistore decoded as JSON.
"""
assert self._thread_lock.locked()
self._file.file_handle().seek(0)
return simplejson.load(self._file.file_handle())
def _locked_json_write(self, data):
"""Write a JSON serializable data structure to the multistore.
The multistore must be locked when this is called.
Args:
data: The data to be serialized and written.
"""
assert self._thread_lock.locked()
if self._read_only:
return
self._file.file_handle().seek(0)
simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2)
self._file.file_handle().truncate()
def _refresh_data_cache(self):
"""Refresh the contents of the multistore.
The multistore must be locked when this is called.
Raises:
NewerCredentialStoreError: Raised when a newer client has written the
store.
"""
self._data = {}
try:
raw_data = self._locked_json_read()
except Exception:
logger.warn('Credential data store could not be loaded. '
'Will ignore and overwrite.')
return
version = 0
try:
version = raw_data['file_version']
except Exception:
logger.warn('Missing version for credential data store. It may be '
'corrupt or an old version. Overwriting.')
if version > 1:
raise NewerCredentialStoreError(
'Credential file has file_version of %d. '
'Only file_version of 1 is supported.' % version)
credentials = []
try:
credentials = raw_data['data']
except (TypeError, KeyError):
pass
for cred_entry in credentials:
try:
(key, credential) = self._decode_credential_from_json(cred_entry)
self._data[key] = credential
except:
# If something goes wrong loading a credential, just ignore it
logger.info('Error decoding credential, skipping', exc_info=True)
def _decode_credential_from_json(self, cred_entry):
"""Load a credential from our JSON serialization.
Args:
cred_entry: A dict entry from the data member of our format
Returns:
(key, cred) where the key is the key tuple and the cred is the
OAuth2Credential object.
"""
raw_key = cred_entry['key']
client_id = raw_key['clientId']
user_agent = raw_key['userAgent']
scope = raw_key['scope']
key = (client_id, user_agent, scope)
credential = None
credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
return (key, credential)
def _write(self):
"""Write the cached data back out.
The multistore must be locked.
"""
raw_data = {'file_version': 1}
raw_creds = []
raw_data['data'] = raw_creds
for (cred_key, cred) in self._data.items():
raw_key = {
'clientId': cred_key[0],
'userAgent': cred_key[1],
'scope': cred_key[2]
}
raw_cred = simplejson.loads(cred.to_json())
raw_creds.append({'key': raw_key, 'credential': raw_cred})
self._locked_json_write(raw_data)
def _get_credential(self, client_id, user_agent, scope):
"""Get a credential from the multistore.
The multistore must be locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
The credential specified or None if not present
"""
key = (client_id, user_agent, scope)
return self._data.get(key, None)
def _update_credential(self, cred, scope):
"""Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
cred: The OAuth2Credential to update/set
scope: The scope(s) that this credential covers
"""
key = (cred.client_id, cred.user_agent, scope)
self._data[key] = cred
self._write()
def _delete_credential(self, client_id, user_agent, scope):
"""Delete a credential and write the multistore.
This must be called when the multistore is locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: The scope(s) that this credential covers
"""
key = (client_id, user_agent, scope)
try:
del self._data[key]
except KeyError:
pass
self._write()
def _get_storage(self, client_id, user_agent, scope):
"""Get a Storage object to get/set a credential.
This Storage is a 'view' into the multistore.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
A Storage object that can be used to get/set this cred
"""
return self._Storage(self, client_id, user_agent, scope)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An OAuth 2.0 client.
Tools for interacting with OAuth 2.0 protected resources.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import clientsecrets
import copy
import datetime
import httplib2
import logging
import os
import sys
import time
import urllib
import urlparse
from anyjson import simplejson
HAS_OPENSSL = False
try:
from oauth2client.crypt import Signer
from oauth2client.crypt import make_signed_jwt
from oauth2client.crypt import verify_signed_jwt_with_certs
HAS_OPENSSL = True
except ImportError:
pass
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
logger = logging.getLogger(__name__)
# Expiry is stored in RFC3339 UTC format
EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
# Which certs to use to validate id_tokens received.
ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs'
# Constant to use for the out of band OAuth 2.0 flow.
OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob'
class Error(Exception):
"""Base error for this module."""
pass
class FlowExchangeError(Error):
"""Error trying to exchange an authorization grant for an access token."""
pass
class AccessTokenRefreshError(Error):
"""Error trying to refresh an expired access token."""
pass
class UnknownClientSecretsFlowError(Error):
"""The client secrets file called for an unknown type of OAuth 2.0 flow. """
pass
class AccessTokenCredentialsError(Error):
"""Having only the access_token means no refresh is possible."""
pass
class VerifyJwtTokenError(Error):
"""Could on retrieve certificates for validation."""
pass
def _abstract():
raise NotImplementedError('You need to override this function')
class MemoryCache(object):
"""httplib2 Cache implementation which only caches locally."""
def __init__(self):
self.cache = {}
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cache[key] = value
def delete(self, key):
self.cache.pop(key, None)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method that applies the credentials to
an HTTP transport.
Subclasses must also specify a classmethod named 'from_json' that takes a JSON
string as input and returns an instaniated Credentials object.
"""
NON_SERIALIZED_MEMBERS = ['store']
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
_abstract()
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
_abstract()
def _to_json(self, strip):
"""Utility function for creating a JSON representation of an instance of Credentials.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
for member in strip:
if member in d:
del d[member]
if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime):
d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT)
# Add in information we will need later to reconsistitue this instance.
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Creating a JSON representation of an instance of Credentials.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a Credentials subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of Credentials that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
try:
m = __import__(module)
except ImportError:
# In case there's an object from the old package structure, update it
module = module.replace('.apiclient', '')
m = __import__(module)
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it.
The JSON should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
return Credentials()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential. This class supports locking
such that multiple processes and threads can operate on a single
store.
"""
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
pass
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
pass
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
_abstract()
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
"""
_abstract()
def get(self):
"""Retrieve credential.
The Storage lock must *not* be held when this is called.
Returns:
oauth2client.client.Credentials
"""
self.acquire_lock()
try:
return self.locked_get()
finally:
self.release_lock()
def put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self.acquire_lock()
try:
self.locked_put(credentials)
finally:
self.release_lock()
def delete(self):
"""Delete credential.
Frees any resources associated with storing the credential.
The Storage lock must *not* be held when this is called.
Returns:
None
"""
self.acquire_lock()
try:
return self.locked_delete()
finally:
self.release_lock()
class OAuth2Credentials(Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the authorize()
method, which then adds the OAuth 2.0 access token to each request.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent, id_token=None):
"""Create an instance of OAuth2Credentials.
This constructor is not usually called by the user, instead
OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
Args:
access_token: string, access token.
client_id: string, client identifier.
client_secret: string, client secret.
refresh_token: string, refresh token.
token_expiry: datetime, when the access_token expires.
token_uri: string, URI of token endpoint.
user_agent: string, The HTTP User-Agent to provide for this application.
id_token: object, The identity of the resource owner.
Notes:
store: callable, A callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has expired and been refreshed.
"""
self.access_token = access_token
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token = refresh_token
self.store = None
self.token_expiry = token_expiry
self.token_uri = token_uri
self.user_agent = user_agent
self.id_token = id_token
# True if the credentials have been revoked or expired and can't be
# refreshed.
self.invalid = False
def authorize(self, http):
"""Authorize an httplib2.Http instance with these credentials.
The modified http.request method will add authentication headers to each
request and will refresh access_tokens when a 401 is received on a
request. In addition the http.request method has a credentials property,
http.request.credentials, which is the Credentials object that authorized
it.
Args:
http: An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth subclass of httplib2.Authenication
because it never gets passed the absolute URI, which is needed for
signing. So instead we have to overload 'request' with a closure
that adds in the Authorization header and then calls the original
version of 'request()'.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if not self.access_token:
logger.info('Attempting refresh to obtain initial access_token')
self._refresh(request_orig)
# Modify the request headers to add the appropriate
# Authorization header.
if headers is None:
headers = {}
self.apply(headers)
if self.user_agent is not None:
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
if resp.status == 401:
logger.info('Refreshing due to a 401')
self._refresh(request_orig)
self.apply(headers)
return request_orig(uri, method, body, headers,
redirections, connection_type)
else:
return (resp, content)
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
setattr(http.request, 'credentials', self)
return http
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
self._refresh(http.request)
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
headers['Authorization'] = 'Bearer ' + self.access_token
def to_json(self):
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it. The JSON
should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
data = simplejson.loads(s)
if 'token_expiry' in data and not isinstance(data['token_expiry'],
datetime.datetime):
try:
data['token_expiry'] = datetime.datetime.strptime(
data['token_expiry'], EXPIRY_FORMAT)
except:
data['token_expiry'] = None
retval = OAuth2Credentials(
data['access_token'],
data['client_id'],
data['client_secret'],
data['refresh_token'],
data['token_expiry'],
data['token_uri'],
data['user_agent'],
data.get('id_token', None))
retval.invalid = data['invalid']
return retval
@property
def access_token_expired(self):
"""True if the credential is expired or invalid.
If the token_expiry isn't set, we assume the token doesn't expire.
"""
if self.invalid:
return True
if not self.token_expiry:
return False
now = datetime.datetime.utcnow()
if now >= self.token_expiry:
logger.info('access_token is expired. Now: %s, token_expiry: %s',
now, self.token_expiry)
return True
return False
def set_store(self, store):
"""Set the Storage for the credential.
Args:
store: Storage, an implementation of Stroage object.
This is needed to store the latest access_token if it
has expired and been refreshed. This implementation uses
locking to check for updates before updating the
access_token.
"""
self.store = store
def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
self.__dict__.update(other.__getstate__())
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def _generate_refresh_request_body(self):
"""Generate the body that will be used in the refresh request."""
body = urllib.urlencode({
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
})
return body
def _generate_refresh_request_headers(self):
"""Generate the headers that will be used in the refresh request."""
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
return headers
def _refresh(self, http_request):
"""Refreshes the access_token.
This method first checks by reading the Storage object if available.
If a refresh is still needed, it holds the Storage lock until the
refresh is completed.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
if not self.store:
self._do_refresh_request(http_request)
else:
self.store.acquire_lock()
try:
new_cred = self.store.locked_get()
if (new_cred and not new_cred.invalid and
new_cred.access_token != self.access_token):
logger.info('Updated access_token read from Storage')
self._updateFromCredential(new_cred)
else:
self._do_refresh_request(http_request)
finally:
self.store.release_lock()
def _do_refresh_request(self, http_request):
"""Refresh the access_token using the refresh_token.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
body = self._generate_refresh_request_body()
headers = self._generate_refresh_request_headers()
logger.info('Refreshing access_token')
resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if loads fails?
d = simplejson.loads(content)
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
self.token_expiry = datetime.timedelta(
seconds=int(d['expires_in'])) + datetime.datetime.utcnow()
else:
self.token_expiry = None
if self.store:
self.store.locked_put(self)
else:
# An {'error':...} response body means the token is expired or revoked,
# so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
self.invalid = True
if self.store:
self.store.locked_put(self)
except:
pass
raise AccessTokenRefreshError(error_msg)
class AccessTokenCredentials(OAuth2Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the
authorize() method, which then signs each request from that object
with the OAuth 2.0 access token. This set of credentials is for the
use case where you have acquired an OAuth 2.0 access_token from
another place such as a JavaScript client or another web
application, and wish to use it from Python. Because only the
access_token is present it can not be refreshed and will in time
expire.
AccessTokenCredentials objects may be safely pickled and unpickled.
Usage:
credentials = AccessTokenCredentials('<an access token>',
'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
Exceptions:
AccessTokenCredentialsExpired: raised when the access_token expires or is
revoked.
"""
def __init__(self, access_token, user_agent):
"""Create an instance of OAuth2Credentials
This is one of the few types if Credentials that you should contrust,
Credentials objects are usually instantiated by a Flow.
Args:
access_token: string, access token.
user_agent: string, The HTTP User-Agent to provide for this application.
Notes:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
"""
super(AccessTokenCredentials, self).__init__(
access_token,
None,
None,
None,
None,
None,
user_agent)
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = AccessTokenCredentials(
data['access_token'],
data['user_agent'])
return retval
def _refresh(self, http_request):
raise AccessTokenCredentialsError(
"The access_token is expired or invalid and can't be refreshed.")
class AssertionCredentials(OAuth2Credentials):
"""Abstract Credentials object used for OAuth 2.0 assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens. It must
be subclassed to generate the appropriate assertion string.
AssertionCredentials objects may be safely pickled and unpickled.
"""
def __init__(self, assertion_type, user_agent,
token_uri='https://accounts.google.com/o/oauth2/token',
**unused_kwargs):
"""Constructor for AssertionFlowCredentials.
Args:
assertion_type: string, assertion type that will be declared to the auth
server
user_agent: string, The HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
"""
super(AssertionCredentials, self).__init__(
None,
None,
None,
None,
None,
token_uri,
user_agent)
self.assertion_type = assertion_type
def _generate_refresh_request_body(self):
assertion = self._generate_assertion()
body = urllib.urlencode({
'assertion_type': self.assertion_type,
'assertion': assertion,
'grant_type': 'assertion',
})
return body
def _generate_assertion(self):
"""Generate the assertion string that will be used in the access token
request.
"""
_abstract()
if HAS_OPENSSL:
# PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
# don't create the SignedJwtAssertionCredentials or the verify_id_token()
# method.
class SignedJwtAssertionCredentials(AssertionCredentials):
"""Credentials object used for OAuth 2.0 Signed JWT assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens.
"""
MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
def __init__(self,
service_account_name,
private_key,
scope,
private_key_password='notasecret',
user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for SignedJwtAssertionCredentials.
Args:
service_account_name: string, id for account, usually an email address.
private_key: string, private key in P12 format.
scope: string or list of strings, scope(s) of the credentials being
requested.
private_key_password: string, password for private_key.
user_agent: string, HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
kwargs: kwargs, Additional parameters to add to the JWT token, for
example prn=joe@xample.org."""
super(SignedJwtAssertionCredentials, self).__init__(
'http://oauth.net/grant_type/jwt/1.0/bearer',
user_agent,
token_uri=token_uri,
)
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.private_key = private_key
self.private_key_password = private_key_password
self.service_account_name = service_account_name
self.kwargs = kwargs
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = SignedJwtAssertionCredentials(
data['service_account_name'],
data['private_key'],
data['private_key_password'],
data['scope'],
data['user_agent'],
data['token_uri'],
data['kwargs']
)
retval.invalid = data['invalid']
return retval
def _generate_assertion(self):
"""Generate the assertion that will be used in the request."""
now = long(time.time())
payload = {
'aud': self.token_uri,
'scope': self.scope,
'iat': now,
'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
'iss': self.service_account_name
}
payload.update(self.kwargs)
logger.debug(str(payload))
return make_signed_jwt(
Signer.from_string(self.private_key, self.private_key_password),
payload)
# Only used in verify_id_token(), which is always calling to the same URI
# for the certs.
_cached_http = httplib2.Http(MemoryCache())
def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATON_CERTS):
"""Verifies a signed JWT id_token.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.
Returns:
The deserialized JSON in the JWT.
Raises:
oauth2client.crypt.AppIdentityError if the JWT fails to verify.
"""
if http is None:
http = _cached_http
resp, content = http.request(cert_uri)
if resp.status == 200:
certs = simplejson.loads(content)
return verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: %d' % resp.status)
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
segments = id_token.split('.')
if (len(segments) != 3):
raise VerifyJwtTokenError(
'Wrong number of segments in token: %s' % id_token)
return simplejson.loads(_urlsafe_b64decode(segments[1]))
def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri = 'postmessage',
http=None, user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token'):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
"""
flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
'https://accounts.google.com/o/oauth2/auth',
token_uri)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
def credentials_from_clientsecrets_and_code(filename, scope, code,
message = None,
redirect_uri = 'postmessage',
http=None):
"""Returns OAuth2Credentials from a clientsecrets file and an auth code.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of clientsecrets.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
flow = flow_from_clientsecrets(filename, scope, message)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, client_id, client_secret, scope, user_agent=None,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for OAuth2WebServerFlow.
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.client_id = client_id
self.client_secret = client_secret
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.user_agent = user_agent
self.auth_uri = auth_uri
self.token_uri = token_uri
self.params = {
'access_type': 'offline',
}
self.params.update(kwargs)
self.redirect_uri = None
def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN):
"""Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the callback from
the authorization server.
If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
self.redirect_uri = redirect_uri
query = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': redirect_uri,
'scope': self.scope,
}
query.update(self.params)
parts = list(urlparse.urlparse(self.auth_uri))
query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part
parts[4] = urllib.urlencode(query)
return urlparse.urlunparse(parts)
def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token.
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
if 'code' not in code:
if 'error' in code:
error_msg = code['error']
else:
error_msg = 'No code was supplied in the query parameters.'
raise FlowExchangeError(error_msg)
else:
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body,
headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if simplejson.loads fails?
d = simplejson.loads(content)
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
seconds=int(d['expires_in']))
if 'id_token' in d:
d['id_token'] = _extract_id_token(d['id_token'])
logger.info('Successfully retrieved access token: %s' % content)
return OAuth2Credentials(access_token, self.client_id,
self.client_secret, refresh_token, token_expiry,
self.token_uri, self.user_agent,
id_token=d.get('id_token', None))
else:
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
except:
pass
raise FlowExchangeError(error_msg)
def flow_from_clientsecrets(filename, scope, message=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) to request.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
Returns:
A Flow object.
Raises:
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
return OAuth2WebServerFlow(
client_info['client_id'],
client_info['client_secret'],
scope,
None, # user_agent
client_info['auth_uri'],
client_info['token_uri'])
except clientsecrets.InvalidClientSecretsError:
if message:
sys.exit(message)
else:
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 2.0
credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os
import stat
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant."""
self._lock.acquire()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._lock.release()
def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
credentials = None
try:
f = open(self._filename, 'rb')
content = f.read()
f.close()
except IOError:
return credentials
try:
credentials = Credentials.new_from_json(content)
credentials.set_store(self)
except ValueError:
pass
return credentials
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
old_umask = os.umask(0177)
try:
open(self._filename, 'a+b').close()
finally:
os.umask(old_umask)
def locked_put(self, credentials):
"""Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._create_file_if_needed()
f = open(self._filename, 'wb')
f.write(credentials.to_json())
f.close()
def locked_delete(self):
"""Delete Credentials file.
Args:
credentials: Credentials, the credentials to store.
"""
os.unlink(self._filename)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""OAuth 2.0 utilities for Django.
Utilities for using OAuth 2.0 in conjunction with
the Django datastore.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import oauth2client
import base64
import pickle
from django.db import models
from oauth2client.client import Storage as BaseStorage
class CredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
class FlowField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Flow):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from
the datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsField
on a db model class.
"""
def __init__(self, model_class, key_name, key_value, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the credentials
property_name: string, name of the property that is an CredentialsProperty
"""
self.model_class = model_class
self.key_name = key_name
self.key_value = key_value
self.property_name = property_name
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
credential = None
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
args = {self.key_name: self.key_value}
entity = self.model_class(**args)
setattr(entity, self.property_name, credentials)
entity.save()
def locked_delete(self):
"""Delete Credentials from the datastore."""
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query).delete()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Google App Engine
Utilities for making it easier to use OAuth 2.0 on Google App Engine.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import httplib2
import logging
import pickle
import time
import clientsecrets
from anyjson import simplejson
from client import AccessTokenRefreshError
from client import AssertionCredentials
from client import Credentials
from client import Flow
from client import OAuth2WebServerFlow
from client import Storage
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.api import app_identity
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns'
class InvalidClientSecretsError(Exception):
"""The client_secrets.json file is malformed or missing required fields."""
pass
class AppAssertionCredentials(AssertionCredentials):
"""Credentials object for App Engine Assertion Grants
This object will allow an App Engine application to identify itself to Google
and other OAuth 2.0 servers that can verify assertions. It can be used for
the purpose of accessing data stored under an account assigned to the App
Engine application itself.
This credential does not require a flow to instantiate because it represents
a two legged flow, and therefore has all of the required information to
generate and refresh its own access tokens.
"""
def __init__(self, scope, **kwargs):
"""Constructor for AppAssertionCredentials
Args:
scope: string or list of strings, scope(s) of the credentials being requested.
"""
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
super(AppAssertionCredentials, self).__init__(
None,
None,
None)
@classmethod
def from_json(cls, json):
data = simplejson.loads(json)
return AppAssertionCredentials(data['scope'])
def _refresh(self, http_request):
"""Refreshes the access_token.
Since the underlying App Engine app_identity implementation does its own
caching we can skip all the storage hoops and just to a refresh using the
API.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
try:
(token, _) = app_identity.get_access_token(self.scope)
except app_identity.Error, e:
raise AccessTokenRefreshError(str(e))
self.access_token = token
class FlowProperty(db.Property):
"""App Engine datastore Property for Flow.
Utility property that allows easy storage and retreival of an
oauth2client.Flow"""
# Tell what the user type is.
data_type = Flow
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
flow = super(FlowProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(flow))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, Flow):
raise db.BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowProperty, self).validate(value)
def empty(self, value):
return not value
class CredentialsProperty(db.Property):
"""App Engine datastore Property for Credentials.
Utility property that allows easy storage and retrieval of
oath2client.Credentials
"""
# Tell what the user type is.
data_type = Credentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
logging.info("get: Got type " + str(type(model_instance)))
cred = super(CredentialsProperty,
self).get_value_for_datastore(model_instance)
if cred is None:
cred = ''
else:
cred = cred.to_json()
return db.Blob(cred)
# For reading from datastore.
def make_value_from_datastore(self, value):
logging.info("make: Got type " + str(type(value)))
if value is None:
return None
if len(value) == 0:
return None
try:
credentials = Credentials.new_from_json(value)
except ValueError:
credentials = None
return credentials
def validate(self, value):
value = super(CredentialsProperty, self).validate(value)
logging.info("validate: Got type " + str(type(value)))
if value is not None and not isinstance(value, Credentials):
raise db.BadValueError('Property %s must be convertible '
'to a Credentials instance (%s)' %
(self.name, value))
#if value is not None and not isinstance(value, Credentials):
# return None
return value
class StorageByKeyName(Storage):
"""Store and retrieve a single credential to and from
the App Engine datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsProperty
on a datastore model class, and that entities
are stored by key_name.
"""
def __init__(self, model, key_name, property_name, cache=None):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is a CredentialsProperty
cache: memcache, a write-through cache to put in front of the datastore
"""
self._model = model
self._key_name = key_name
self._property_name = property_name
self._cache = cache
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
if self._cache:
json = self._cache.get(self._key_name)
if json:
return Credentials.new_from_json(json)
credential = None
entity = self._model.get_by_key_name(self._key_name)
if entity is not None:
credential = getattr(entity, self._property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
if self._cache:
self._cache.set(self._key_name, credential.to_json())
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity = self._model.get_or_insert(self._key_name)
setattr(entity, self._property_name, credentials)
entity.put()
if self._cache:
self._cache.set(self._key_name, credentials.to_json())
def locked_delete(self):
"""Delete Credential from datastore."""
if self._cache:
self._cache.delete(self._key_name)
entity = self._model.get_by_key_name(self._key_name)
if entity is not None:
entity.delete()
class CredentialsModel(db.Model):
"""Storage for OAuth 2.0 Credentials
Storage of the model is keyed by the user.user_id().
"""
credentials = CredentialsProperty()
class OAuth2Decorator(object):
"""Utility for making OAuth 2.0 easier.
Instantiate and then use with oauth_required or oauth_aware
as decorators on webapp.RequestHandler methods.
Example:
decorator = OAuth2Decorator(
client_id='837...ent.com',
client_secret='Qh...wwI',
scope='https://www.googleapis.com/auth/plus')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
http = decorator.http()
# http is authorized with the user's Credentials and can be used
# in API calls
"""
def __init__(self, client_id, client_secret, scope,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
user_agent=None,
message=None, **kwargs):
"""Constructor for OAuth2Decorator
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
user_agent: string, User agent of your application, default to None.
message: Message to display if there are problems with the OAuth 2.0
configuration. The message may contain HTML and will be presented on the
web interface for any method that uses the decorator.
**kwargs: dict, Keyword arguments are be passed along as kwargs to the
OAuth2WebServerFlow constructor.
"""
self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
auth_uri, token_uri, **kwargs)
self.credentials = None
self._request_handler = None
self._message = message
self._in_error = False
def _display_error_message(self, request_handler):
request_handler.response.out.write('<html><body>')
request_handler.response.out.write(self._message)
request_handler.response.out.write('</body></html>')
def oauth_required(self, method):
"""Decorator that starts the OAuth 2.0 dance.
Starts the OAuth dance for the logged in user if they haven't already
granted access for this application.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def check_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
# Store the request URI in 'state' so we can use it later
self.flow.params['state'] = request_handler.request.url
self._request_handler = request_handler
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
if not self.has_credentials():
return request_handler.redirect(self.authorize_url())
try:
method(request_handler, *args, **kwargs)
except AccessTokenRefreshError:
return request_handler.redirect(self.authorize_url())
return check_oauth
def oauth_aware(self, method):
"""Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def setup_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self.flow.params['state'] = request_handler.request.url
self._request_handler = request_handler
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
method(request_handler, *args, **kwargs)
return setup_oauth
def has_credentials(self):
"""True if for the logged in user there are valid access Credentials.
Must only be called from with a webapp.RequestHandler subclassed method
that had been decorated with either @oauth_required or @oauth_aware.
"""
return self.credentials is not None and not self.credentials.invalid
def authorize_url(self):
"""Returns the URL to start the OAuth dance.
Must only be called from with a webapp.RequestHandler subclassed method
that had been decorated with either @oauth_required or @oauth_aware.
"""
callback = self._request_handler.request.relative_url('/oauth2callback')
url = self.flow.step1_get_authorize_url(callback)
user = users.get_current_user()
memcache.set(user.user_id(), pickle.dumps(self.flow),
namespace=OAUTH2CLIENT_NAMESPACE)
return str(url)
def http(self):
"""Returns an authorized http instance.
Must only be called from within an @oauth_required decorated method, or
from within an @oauth_aware decorated method where has_credentials()
returns True.
"""
return self.credentials.authorize(httplib2.Http())
class OAuth2DecoratorFromClientSecrets(OAuth2Decorator):
"""An OAuth2Decorator that builds from a clientsecrets file.
Uses a clientsecrets file as the source for all the information when
constructing an OAuth2Decorator.
Example:
decorator = OAuth2DecoratorFromClientSecrets(
os.path.join(os.path.dirname(__file__), 'client_secrets.json')
scope='https://www.googleapis.com/auth/plus')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
http = decorator.http()
# http is authorized with the user's Credentials and can be used
# in API calls
"""
def __init__(self, filename, scope, message=None):
"""Constructor
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML and
will be presented on the web interface for any method that uses the
decorator.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.')
super(OAuth2DecoratorFromClientSecrets,
self).__init__(
client_info['client_id'],
client_info['client_secret'],
scope,
client_info['auth_uri'],
client_info['token_uri'],
message)
except clientsecrets.InvalidClientSecretsError:
self._in_error = True
if message is not None:
self._message = message
else:
self._message = "Please configure your application for OAuth 2.0"
def oauth2decorator_from_clientsecrets(filename, scope, message=None):
"""Creates an OAuth2Decorator populated from a clientsecrets file.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML and
will be presented on the web interface for any method that uses the
decorator.
Returns: An OAuth2Decorator
"""
return OAuth2DecoratorFromClientSecrets(filename, scope, message)
class OAuth2Handler(webapp.RequestHandler):
"""Handler for the redirect_uri of the OAuth 2.0 dance."""
@login_required
def get(self):
error = self.request.get('error')
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: %s' % errormsg)
else:
user = users.get_current_user()
flow = pickle.loads(memcache.get(user.user_id(),
namespace=OAUTH2CLIENT_NAMESPACE))
# This code should be ammended with application specific error
# handling. The following cases should be considered:
# 1. What if the flow doesn't exist in memcache? Or is corrupt?
# 2. What if the step2_exchange fails?
if flow:
credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').put(credentials)
self.redirect(str(self.request.get('state')))
else:
# TODO Add error handling here.
pass
application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)])
def main():
run_wsgi_app(application)
| Python |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import hashlib
import logging
import time
from OpenSSL import crypto
from anyjson import simplejson
CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds
MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds
class AppIdentityError(Exception):
pass
class Verifier(object):
"""Verifies the signature on a message."""
def __init__(self, pubkey):
"""Constructor.
Args:
pubkey, OpenSSL.crypto.PKey, The public key to verify with.
"""
self._pubkey = pubkey
def verify(self, message, signature):
"""Verifies a message against a signature.
Args:
message: string, The message to verify.
signature: string, The signature on the message.
Returns:
True if message was singed by the private key associated with the public
key that this object was constructed with.
"""
try:
crypto.verify(self._pubkey, signature, message, 'sha256')
return True
except:
return False
@staticmethod
def from_string(key_pem, is_x509_cert):
"""Construct a Verified instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is
expected to be an RSA key in PEM format.
Returns:
Verifier instance.
Raises:
OpenSSL.crypto.Error if the key_pem can't be parsed.
"""
if is_x509_cert:
pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
else:
pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
return Verifier(pubkey)
class Signer(object):
"""Signs messages with a private key."""
def __init__(self, pkey):
"""Constructor.
Args:
pkey, OpenSSL.crypto.PKey, The private key to sign with.
"""
self._key = pkey
def sign(self, message):
"""Signs a message.
Args:
message: string, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
return crypto.sign(self._key, message, 'sha256')
@staticmethod
def from_string(key, password='notasecret'):
"""Construct a Signer instance from a string.
Args:
key: string, private key in P12 format.
password: string, password for the private key file.
Returns:
Signer instance.
Raises:
OpenSSL.crypto.Error if the key can't be parsed.
"""
pkey = crypto.load_pkcs12(key, password).get_privatekey()
return Signer(pkey)
def _urlsafe_b64encode(raw_bytes):
return base64.urlsafe_b64encode(raw_bytes).rstrip('=')
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _json_encode(data):
return simplejson.dumps(data, separators = (',', ':'))
def make_signed_jwt(signer, payload):
"""Make a signed JWT.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
signer: crypt.Signer, Cryptographic signer.
payload: dict, Dictionary of data to convert to JSON and then sign.
Returns:
string, The JWT for the payload.
"""
header = {'typ': 'JWT', 'alg': 'RS256'}
segments = [
_urlsafe_b64encode(_json_encode(header)),
_urlsafe_b64encode(_json_encode(payload)),
]
signing_input = '.'.join(segments)
signature = signer.sign(signing_input)
segments.append(_urlsafe_b64encode(signature))
logging.debug(str(segments))
return '.'.join(segments)
def verify_signed_jwt_with_certs(jwt, certs, audience):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
jwt: string, A JWT.
certs: dict, Dictionary where values of public keys in PEM format.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError if any checks are failed.
"""
segments = jwt.split('.')
if (len(segments) != 3):
raise AppIdentityError(
'Wrong number of segments in token: %s' % jwt)
signed = '%s.%s' % (segments[0], segments[1])
signature = _urlsafe_b64decode(segments[2])
# Parse token.
json_body = _urlsafe_b64decode(segments[1])
try:
parsed = simplejson.loads(json_body)
except:
raise AppIdentityError('Can\'t parse token: %s' % json_body)
# Check signature.
verified = False
for (keyname, pem) in certs.items():
verifier = Verifier.from_string(pem, True)
if (verifier.verify(signed, signature)):
verified = True
break
if not verified:
raise AppIdentityError('Invalid token signature: %s' % jwt)
# Check creation timestamp.
iat = parsed.get('iat')
if iat is None:
raise AppIdentityError('No iat field in token: %s' % json_body)
earliest = iat - CLOCK_SKEW_SECS
# Check expiration timestamp.
now = long(time.time())
exp = parsed.get('exp')
if exp is None:
raise AppIdentityError('No exp field in token: %s' % json_body)
if exp >= now + MAX_TOKEN_LIFETIME_SECS:
raise AppIdentityError(
'exp field too far in future: %s' % json_body)
latest = exp + CLOCK_SKEW_SECS
if now < earliest:
raise AppIdentityError('Token used too early, %d < %d: %s' %
(now, earliest, json_body))
if now > latest:
raise AppIdentityError('Token used too late, %d > %d: %s' %
(now, latest, json_body))
# Check audience.
if audience is not None:
aud = parsed.get('aud')
if aud is None:
raise AppIdentityError('No aud field in token: %s' % json_body)
if aud != audience:
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
(aud, audience, json_body))
return parsed
| Python |
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for reading OAuth 2.0 client secret files.
A client_secrets.json file contains all the information needed to interact with
an OAuth 2.0 protected service.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from anyjson import simplejson
# Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed'
VALID_CLIENT = {
TYPE_WEB: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
},
TYPE_INSTALLED: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
}
}
class Error(Exception):
"""Base error for this module."""
pass
class InvalidClientSecretsError(Error):
"""Format of ClientSecrets file is invalid."""
pass
def _validate_clientsecrets(obj):
if obj is None or len(obj) != 1:
raise InvalidClientSecretsError('Invalid file format.')
client_type = obj.keys()[0]
if client_type not in VALID_CLIENT.keys():
raise InvalidClientSecretsError('Unknown client type: %s.' % client_type)
client_info = obj[client_type]
for prop_name in VALID_CLIENT[client_type]['required']:
if prop_name not in client_info:
raise InvalidClientSecretsError(
'Missing property "%s" in a client type of "%s".' % (prop_name,
client_type))
for prop_name in VALID_CLIENT[client_type]['string']:
if client_info[prop_name].startswith('[['):
raise InvalidClientSecretsError(
'Property "%s" is not configured.' % prop_name)
return client_type, client_info
def load(fp):
obj = simplejson.load(fp)
return _validate_clientsecrets(obj)
def loads(s):
obj = simplejson.loads(s)
return _validate_clientsecrets(obj)
def loadfile(filename):
try:
fp = file(filename, 'r')
try:
obj = simplejson.load(fp)
finally:
fp.close()
except IOError:
raise InvalidClientSecretsError('File not found: "%s"' % filename)
return _validate_clientsecrets(obj)
| Python |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Locked file interface that should work on Unix and Windows pythons.
This module first tries to use fcntl locking to ensure serialized access
to a file, then falls back on a lock file if that is unavialable.
Usage:
f = LockedFile('filename', 'r+b', 'rb')
f.open_and_lock()
if f.is_locked():
print 'Acquired filename with r+b mode'
f.file_handle().write('locked data')
else:
print 'Aquired filename with rb mode'
f.unlock_and_close()
"""
__author__ = 'cache@google.com (David T McWherter)'
import errno
import logging
import os
import time
logger = logging.getLogger(__name__)
class AlreadyLockedException(Exception):
"""Trying to lock a file that has already been locked by the LockedFile."""
pass
class _Opener(object):
"""Base class for different locking primitives."""
def __init__(self, filename, mode, fallback_mode):
"""Create an Opener.
Args:
filename: string, The pathname of the file.
mode: string, The preferred mode to access the file with.
fallback_mode: string, The mode to use if locking fails.
"""
self._locked = False
self._filename = filename
self._mode = mode
self._fallback_mode = fallback_mode
self._fh = None
def is_locked(self):
"""Was the file locked."""
return self._locked
def file_handle(self):
"""The file handle to the file. Valid only after opened."""
return self._fh
def filename(self):
"""The filename that is being locked."""
return self._filename
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
"""
pass
def unlock_and_close(self):
"""Unlock and close the file."""
pass
class _PosixOpener(_Opener):
"""Lock files using Posix advisory lock files."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Tries to create a .lock file next to the file we're trying to open.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
self._locked = False
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
lock_filename = self._posix_lockfile(self._filename)
start_time = time.time()
while True:
try:
self._lock_fd = os.open(lock_filename,
os.O_CREAT|os.O_EXCL|os.O_RDWR)
self._locked = True
break
except OSError, e:
if e.errno != errno.EEXIST:
raise
if (time.time() - start_time) >= timeout:
logger.warn('Could not acquire lock %s in %s seconds' % (
lock_filename, timeout))
# Close the file and open in fallback_mode.
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Unlock a file by removing the .lock file, and close the handle."""
if self._locked:
lock_filename = self._posix_lockfile(self._filename)
os.unlink(lock_filename)
os.close(self._lock_fd)
self._locked = False
self._lock_fd = None
if self._fh:
self._fh.close()
def _posix_lockfile(self, filename):
"""The name of the lock file to use for posix locking."""
return '%s.lock' % filename
try:
import fcntl
class _FcntlOpener(_Opener):
"""Open, lock, and unlock a file using fcntl.lockf."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
start_time = time.time()
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
# We opened in _mode, try to lock the file.
while True:
try:
fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX)
self._locked = True
return
except IOError, e:
# If not retrying, then just pass on the error.
if timeout == 0:
raise e
if e.errno != errno.EACCES:
raise e
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Close and unlock the file using the fcntl.lockf primitive."""
if self._locked:
fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN)
self._locked = False
if self._fh:
self._fh.close()
except ImportError:
_FcntlOpener = None
try:
import pywintypes
import win32con
import win32file
class _Win32Opener(_Opener):
"""Open, lock, and unlock a file using windows primitives."""
# Error #33:
# 'The process cannot access the file because another process'
FILE_IN_USE_ERROR = 33
# Error #158:
# 'The segment is already unlocked.'
FILE_ALREADY_UNLOCKED_ERROR = 158
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
start_time = time.time()
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
# We opened in _mode, try to lock the file.
while True:
try:
hfile = win32file._get_osfhandle(self._fh.fileno())
win32file.LockFileEx(
hfile,
(win32con.LOCKFILE_FAIL_IMMEDIATELY|
win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000,
pywintypes.OVERLAPPED())
self._locked = True
return
except pywintypes.error, e:
if timeout == 0:
raise e
# If the error is not that the file is already in use, raise.
if e[0] != _Win32Opener.FILE_IN_USE_ERROR:
raise
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Close and unlock the file using the win32 primitive."""
if self._locked:
try:
hfile = win32file._get_osfhandle(self._fh.fileno())
win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED())
except pywintypes.error, e:
if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR:
raise
self._locked = False
if self._fh:
self._fh.close()
except ImportError:
_Win32Opener = None
class LockedFile(object):
"""Represent a file that has exclusive access."""
def __init__(self, filename, mode, fallback_mode, use_native_locking=True):
"""Construct a LockedFile.
Args:
filename: string, The path of the file to open.
mode: string, The mode to try to open the file with.
fallback_mode: string, The mode to use if locking fails.
use_native_locking: bool, Whether or not fcntl/win32 locking is used.
"""
opener = None
if not opener and use_native_locking:
if _Win32Opener:
opener = _Win32Opener(filename, mode, fallback_mode)
if _FcntlOpener:
opener = _FcntlOpener(filename, mode, fallback_mode)
if not opener:
opener = _PosixOpener(filename, mode, fallback_mode)
self._opener = opener
def filename(self):
"""Return the filename we were constructed with."""
return self._opener._filename
def file_handle(self):
"""Return the file_handle to the opened file."""
return self._opener.file_handle()
def is_locked(self):
"""Return whether we successfully locked the file."""
return self._opener.is_locked()
def open_and_lock(self, timeout=0, delay=0.05):
"""Open the file, trying to lock it.
Args:
timeout: float, The number of seconds to try to acquire the lock.
delay: float, The number of seconds to wait between retry attempts.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
self._opener.open_and_lock(timeout, delay)
def unlock_and_close(self):
"""Unlock and close a file."""
self._opener.unlock_and_close()
| Python |
__version__ = "1.0c2"
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.