home *** CD-ROM | disk | FTP | other *** search
- ##########################################################################################
- ## ///////////////////////////////////////////////////////////////////////////////////////
- ## //
- ## // nasty.py
- ## //
- ## // Authors: Eggert J≤n Magn·sson, Matthφas Gu≡mundsson
- ## // Created: November 2001
- ## // Project: EVE
- ## //
- ## // Description:
- ## //
- ## // Nasty, the managed-object system.
- ## //
- ## // Dependencies:
- ## //
- ## // None
- ## //
- ## // (c) CCP 2001
- ## //
- ## //
-
- import log
- import types
- import blue
- import sys
- sysold = sys
- import imp
- from stackless import getcurrent
- import copy
- import weakref
- import tokenize
-
- #########################################################################################
- ## //////////////////////////////////////////////////////////////////////////////////////
- ## //
- ## // Class NamespaceFailedException
- ## //
- ## // Raised when exceptions
- ## //
- ## //
-
-
-
- class NamespaceFailedException(Exception):
- __guid__ = 'exceptions.NamespaceFailed'
- __persistvars__ = ['args']
- def __init__(self,*args):
- self.args = args
- def __repr__(self):
- return 'NamespaceFailed: The namespace '+self.args[0]+' was not found.'
- NamespaceFailedException.__module__ = 'exceptions'
-
-
- #########################################################################################
- ## //////////////////////////////////////////////////////////////////////////////////////
- ## //
- ## // Class NamespaceAttributeFailedException
- ## //
- ## // Does stuff yah!!
- ## //
- ## //
-
- class NamespaceAttributeFailedException(NamespaceFailedException):
- __guid__ = 'exceptions.NamespaceAttributeFailed'
- __persistvars__ = ['args']
- def __repr__(self):
- return 'NamespaceAttributeFailed: The namespace member '+self.args[0]+'.'+self.args[1]+' was not found.'
-
- NamespaceAttributeFailedException.__module__ = 'exceptions'
-
-
-
- class Namespace:
- def __init__(self,name,space):
- self.__dict__['name'] = name
- self.__dict__["space"] = space
- def __getattr__(self,attr):
- if self.space.has_key(attr):
- return self.space[attr]
- else:
- raise AttributeError, (attr, self.space) #NamespaceAttributeFailedException,(self.name,str(attr))
- def __setattr__(self,attr):
- raise NamespaceAttributeFailedException,(self.name,str(attr))
-
-
- #########################################################################################
- ## //////////////////////////////////////////////////////////////////////////////////////
- ## //
- ## // Class Nasty
- ## //
- ## // Does stuff yah!!
- ## //
- ## //
-
- # -----------------------------------------------------------------------------------
- '''
- The UTLS for the main dude.
-
-
- LocalStorage is actually "session local storage" as currently used, with thread
- inheritance
-
- PrivateStorage is thread local storage, without inheritance.
- '''
-
- # -----------------------------------------------------------------------------------
- mainPrivateStorage = {}
-
- # -----------------------------------------------------------------------------------
- def GetPrivateStorage():
- '''
- Gets the uthread private storage, whether this is the main tasklet or a taskletext
- '''
- t = getcurrent()
- if not hasattr(t,"privateStorage"):
- global mainPrivateStorage
- return mainPrivateStorage
- else:
- if t.privateStorage is None:
- t.privateStorage = {}
- return t.privateStorage
-
- # -----------------------------------------------------------------------------------
- def GetLocalStorage():
- '''
- Gets the uthread local storage, whether this is the main tasklet or a taskletext
- '''
- t = getcurrent()
-
- if not hasattr(t,"localStorage"):
- return mainLocalStorage
- else:
- if t.localStorage is None:
- t.localStorage = {}
- return t.localStorage
-
- # -----------------------------------------------------------------------------------
- def GetOtherLocalStorage(t):
- '''
- Gets the uthread local storage for t, whether this is the main tasklet or a taskletext
- '''
- if not hasattr(t,"localStorage"):
- return mainLocalStorage
- else:
- if t.localStorage is None:
- t.localStorage = {}
- return t.localStorage
-
- # -----------------------------------------------------------------------------------
- def SetLocalStorage(s):
- '''
- Sets the uthread local storage, whether this is the main tasklet or a taskletext
- '''
- t = getcurrent()
-
- if not hasattr(t,"localStorage"):
- global mainLocalStorage
- mainLocalStorage = s
- else:
- t.localStorage = s
-
- # -----------------------------------------------------------------------------------
- def UpdateLocalStorage(props):
- '''
- Adds the given properties to the local storage, and returns the storage that
- you should restore to.
- '''
- ls = GetLocalStorage()
- ret = ls
- ls = copy.copy(ls)
- ls.update(props)
- SetLocalStorage(ls)
- return ret
-
- # -----------------------------------------------------------------------------------
- class Sissy:
- '''
- A Sissy is a wrapper for a uthread local storage object, kept in builtins,
- that forwards all the appropriate stuff to an internal object.
- '''
-
- def __init__(self,what):
- self.__dict__["__sissywhat__"] = what
-
- def __nonzero__(self):
- try:
- sissy = GetLocalStorage().get(self.__sissywhat__,None)
- if (sissy is not None) and (type(sissy)!=types.StringType):
- sissy = sissy()
- except ReferenceError:
- sissy = None
- return sissy is not None
-
- def __str__(self):
- try:
- sissy = GetLocalStorage().get(self.__sissywhat__,None)
- if (sissy is not None) and (type(sissy)!=types.StringType):
- sissy = sissy()
- except ReferenceError:
- sissy = None
- return 'Sissy:'+str(sissy)
-
- def __repr__(self):
- return self.__str__()
-
- def __getattr__(self,k):
- if self.__dict__.has_key(k):
- return self.__dict__[k]
- # if the internal object is None, we want to raise the same as getattr(None,k) would anyway.
- try:
- sissy = GetLocalStorage().get(self.__sissywhat__,None)
- if (sissy is not None) and (type(sissy)!=types.StringType):
- sissy = sissy()
- except ReferenceError:
- sissy = None
- return getattr(sissy, k)
-
- def __setattr__(self,k,v):
- try:
- sissy = GetLocalStorage().get(self.__sissywhat__,None)
- if (sissy is not None) and (type(sissy)!=types.StringType):
- sissy = sissy()
- except ReferenceError:
- sissy = None
- setattr(sissy, k, v)
-
- class Nasty:
- # -----------------------------------------------------------------------------------
- # Nasty - Constructor
- # -----------------------------------------------------------------------------------
- def __init__(self):
-
- self.compiledCode = {}
- self.loadeddlls = []
-
- # const replacement
- self.constants = None
-
- import __builtin__
-
- if hasattr(__builtin__, "Using"):
- raise "Only one instance of nasty can be running, i.e. only load nasty.py once"
- __builtin__.Import = self.Import
- __builtin__.Using = self.Using
- __builtin__.GetPrivateStorage = GetPrivateStorage
- __builtin__.GetLocalStorage = GetLocalStorage
- __builtin__.GetOtherLocalStorage = GetOtherLocalStorage
- __builtin__.SetLocalStorage = SetLocalStorage
- __builtin__.UpdateLocalStorage = UpdateLocalStorage
- __builtin__.RecompileFile = self.RecompileFile
-
- blue.pyos.AddExitProc(self.Release)
-
- self.lastModified = 0 #blue.os.GetTime()
- blue.pyos.SpyDirectory("script:/", self.OnFileModified)
-
- self.waiting = {}
- self.files = {}
- self.namespaces = {"exceptions":{"NamespaceFailed":NamespaceFailedException,"NamespaceAttributeFailed":NamespaceAttributeFailedException}}
- self.globs = {}
- self.preloads = {}
- self.mods = {}
- __builtin__.Sissy = Sissy
- __builtin__.mainLocalStorage = {}
- __builtin__.charsession = Sissy("base.charsession")
- __builtin__.currentcall = Sissy("base.currentcall")
- __builtin__.session = Sissy("base.session")
- __builtin__.caller = Sissy("base.caller")
- self.__fallbackimport__ = __builtin__.__import__
- __builtin__.__import__ = self.ImportBackwards
- __builtin__.Using = self.Using
- __builtin__.Import = self.Import
- __builtin__.CreateInstance = self.CreateInstance
- __builtin__.RegisterConstant = self.RegisterConstant
-
- # Guard against reetrancy to OnFileModified
- self.willCheckModifieds = 0
-
- # Blue MUST be in the namespace and Uthread MUST be loaded,
- # or runner.py will go nuts in case of any error. If service
- # is ommitted here, everything will also go haywire.
- self.Run(["blue.dll"])
-
- self.Run(["script:/common/sys/uthread.py"])
- self.Run(["script:/common/sys/service.py"])
-
-
- def ImportBackwards(self,name, glob=None, loc=None, fromlist=None):
- if not self.mods.has_key(name):
- if self.namespaces.has_key(name):
- # ret = self.Import(name)
- haveOldModule = 0
- try:
- self.mods[name] = imp.new_module(name)
- if name+'.dll' not in self.loadeddlls:
- ret1 = self.__fallbackimport__(name,glob,loc,fromlist)
- else:
- ret1 = imp.new_module(name) #dll loading import! what's up with that ?
- #print 'name',ret1
- self.mods[name] = ret1
- haveOldModule = 1
- except ImportError,e:
- #print 'Importing',name,'failed'
- ret1 = imp.new_module(name)
- # self.mods[name] = ret1
- try:
- ret = self.Import(name,0)
- for i in ret.space.iterkeys():
- if i != '__class__': #grumble, NetClient exposes this?
- setattr(ret1,i,getattr(ret,i))
-
- #
- except ImportError,e:
- if not haveOldModule:
- raise
-
- self.mods[name] = ret1
- if self.mods.has_key(name):
- return self.mods[name]
-
- return self.__fallbackimport__(name,glob,loc,fromlist)
-
- # -----------------------------------------------------------------------------------
- # Initialize
- # -----------------------------------------------------------------------------------
- def Initialize(self):
- now = blue.os.GetTime(1)
- files = self.BrowseScriptFile("script:/")
-
- # We'll recompile everything if any .py file is newer than
- # the compiled.code file.
- codefile = blue.os.CreateInstance("blue.ResFile")
- check = blue.os.CreateInstance("blue.ResFile")
- recompile = 1
- codedate = None
-
- args = blue.pyos.GetArg()
-
- for each in args:
- if each.startswith("/wait"):
- blue.pyos.synchro.Sleep(1000 * int(each[6:]))
-
- if ("/recompile" not in args) and (codefile.Open("script:/compiled.code") and codefile.size > 0):
- modified = codefile.GetFileInfo()["ftLastWriteTime"]
- codedate = blue.os.FormatUTC(modified)
- recompile = 0
-
- # Enumerate all python files
- for file in files:
- if file.find("uthread.py") != -1:
- continue
- if file.find("service.py") != -1:
- continue
- if check.Open(file) and check.GetFileInfo()["ftLastWriteTime"] >= modified:
- recompile = 1
- new = blue.os.FormatUTC(check.GetFileInfo()["ftLastWriteTime"])
- print "Rebuilding code file from %s %s, %s is dated %s %s" % (codedate[0], codedate[2], file, new[0], new[2])
- break
-
- del check
-
- if not recompile:
- import cPickle
- from marshal import loads
- datain = cPickle.loads(str(codefile.Read()))
- for k, v in datain:
- self.compiledCode[k] = loads(v)
-
- codefile.Close()
-
- if not recompile:
- print "Using compiled code from %s %s" % (codedate[0], codedate[2])
- else:
- constfile = blue.os.CreateInstance("blue.ResFile")
- if constfile.Open("script:/constants.marshal"):
- self.constants = blue.marshal.Load(constfile.Read())
- else:
- self.constants = None
-
- self.Run(files)
- self.lastModified = blue.os.GetTime()
-
- if recompile:
- import cPickle
- out = blue.os.CreateInstance("blue.ResFile")
- out.Create("script:/compiled.code")
-
- # Need to marshal pickle the code objects
- from marshal import dumps
- dataout = []
-
- for k, v in self.compiledCode.iteritems():
- dataout.append((k, dumps(v)))
-
- out.Write(cPickle.dumps(dataout, 1))
-
- self.constants = None
- print "Code initialized in %.2f sec." % (float(blue.os.GetTime(1) - now) / 10000000.0, )
-
- if "/compile" in blue.pyos.GetArg():
- rot = blue.os.CreateInstance("blue.Rot")
- report = blue.os.CreateInstance("blue.ResFile")
- report.Create(blue.os.rootpath + "../codefiles.txt")
-
- for name in self.compiledCode.iterkeys():
- if name.find("uthread.py") != -1:
- continue
- if name.find("service.py") != -1:
- continue
- name = rot.PathToFilename(name)
- name = name.replace("/", "\\")
- report.Write(name + "\r\n")
- del report
-
- blue.pyos.Quit("Quitting after compile-only run.")
-
-
-
- # -----------------------------------------------------------------------------------
- # OnFileModified
- # -----------------------------------------------------------------------------------
- def OnFileModified(self):
- if self.willCheckModifieds:
- return
-
- self.willCheckModifieds = 1
- Import("uthread")
- uthread.new(self.OnFileModified_)
-
- def OnFileModified_(self):
-
- try:
- # Give files chance to write completely to disk
- blue.pyos.synchro.Sleep(550)
- fl = []
-
- for each in self.files.itervalues():
- if each not in fl and each[-3:] == '.py':
- fl.append(each)
- x = blue.os.CreateInstance('blue.ResFile')
- lm = 0
- files = []
- now = blue.os.GetTime()
-
- for each in fl:
- x.OpenAlways(each)
- ftLast = x.GetFileInfo()['ftLastWriteTime']
- if ftLast > now:
- # File from the future - very mysterious
- print "File from the future detected. It might scew up my auto-compile feature."
- print " ", blue.os.FormatUTC(ftLast)[0], blue.os.FormatUTC(ftLast)[2], each
-
- if ftLast > self.lastModified:
- print 'Change detected in file',each,'reloading classes'
- files.append(each)
- # Without this check, after a syntax error, this del fails everytime the
- # file is modified.
- if self.compiledCode.has_key(each):
- del self.compiledCode[each]
- lm = max(ftLast,lm)
-
-
- guids = self.GatherFileGuids()
- servicesToReload = []
- for each in files:
- for guid in guids[each]:
- if len(guid) > 4 and guid[:4] == 'svc.':
- servicesToReload.append(guid[4:])
-
- self.Run(files,1)
- import __builtin__
- if hasattr(__builtin__,'sm'):
- sm.Reload(servicesToReload)
- import linecache
- linecache.clearcache()
- self.lastModified = max(lm,self.lastModified)
- finally:
- self.willCheckModifieds = 0
-
- # -----------------------------------------------------------------------------------
- # ReloadFile
- # -----------------------------------------------------------------------------------
- def RecompileFile(self, fileName):
- '''
- Reloads the specified file. Filename should be script:/ based, f.ex.
- script:/util/format.py
- '''
- print 'Recompiling ',fileName
- if fileName in self.compiledCode:
- del self.compiledCode[fileName]
- guids = self.GatherFileGuids()
- servicesToReload = []
- if fileName in guids:
- for guid in guids[fileName]:
- if len(guid) > 4 and guid[:4] == 'svc.':
- servicesToReload.append(guid[4:])
- self.Run([fileName],1)
- import __builtin__
- if hasattr(__builtin__,'sm'):
- sm.Reload(servicesToReload)
- import linecache
- linecache.clearcache()
-
- # -----------------------------------------------------------------------------------
- # BrowseScriptFile
- # -----------------------------------------------------------------------------------
- def BrowseScriptFile(self, directory):
- files = []
- file = blue.os.CreateInstance("blue.ResFile")
- filename = directory + "index.txt"
-
- if not file.Open(filename):
- return []
-
- lines = str(file.Read()).split("\r\n")
- filecount = 0
- dircount = 0
-
- for line in lines:
- if len(line) and line[0] != ' ' and line[0] != '#':
- #print "candidate:",line
- if line[-1] == '/':
- # directory
- dircount = dircount + 1
- files = files + self.BrowseScriptFile(directory + line)
- else:
- # a file, hopefully
- if line[-3:] == ".py":
- filecount = filecount + 1
- files.append(directory + line)
- return files
-
- print "%s (%d files, %d directories)" % (filename, filecount, dircount)
-
-
- # -----------------------------------------------------------------------------------
- # ExtractClassfiles
- # -----------------------------------------------------------------------------------
- def ExtractClassfiles(self):
- for guid, filename in self.files.iteritems():
- print 'Guid: ',guid,'Filename:',filename
-
-
- # -----------------------------------------------------------------------------------
- # Run
- # -----------------------------------------------------------------------------------
- def Run(self,filesToScan,fromReload = 0):
- #print 'Scanning %d files' % (len(filesToScan), )
- unsuccessful = list(filesToScan[:])
-
- stacktrace = 0
- while len(unsuccessful):
- resolveFailures = {}
- files = unsuccessful[:]
- removed = 0
- for each in files:
-
- try:
- # if each[-3:]=='dll':
- # print 'browsing class file',each
- self.BrowseClassFile(each,0,fromReload)
- #print "Loading", each
- unsuccessful.remove(each)
- removed = 1
- except ImportError,val:
- if stacktrace:
- StackTrace()
- if not resolveFailures.has_key(each):
- resolveFailures[each]= [(val,None)]
- else:
- resolveFailures[each].append((val,None))
- #print 'Namespace lookup failed in file "%s" for namespace "%s"'%(each,val)
- except AttributeError,val:
- if stacktrace:
- StackTrace()
- if not resolveFailures.has_key(each):
- resolveFailures[each]= [val]
- else:
- resolveFailures[each].append(val)
- except:
- StackTrace()
- unsuccessful.remove(each) #we don't want to run this file again.
- raise
-
- if removed == 0:
- if stacktrace==0:
- import log
- log.general.Log("All hope lost while loading '%s'"%each, log.fatal)
- stacktrace = 1
- else:
- for filename in unsuccessful:
- log.general.Log("Failed loading file %s"%filename,log.fatal)
- raise RuntimeError("ResolutionFailure")
-
- # -----------------------------------------------------------------------------------
- # ReloadClass
- # -----------------------------------------------------------------------------------
- def ReloadClass(self,cid):
- if self.files.has_key(cid):
- self.BrowseClassFile(self.files[cid])
-
-
- # -----------------------------------------------------------------------------------
- # ReloadFile
- # -----------------------------------------------------------------------------------
- def ReloadFile(self, filename):
- return self.BrowseClassFile(filename)
-
-
- # -----------------------------------------------------------------------------------
- # Import
- # -----------------------------------------------------------------------------------
- def Import(self,name,hack = 1):
- #if name == 'PyAIO':
- #raise 'heha'
- if hack:
- loc = sysold._getframe().f_back.f_globals
- #if name == 'PyAIO':
- # print 'Importing PyAIO'
-
- if not self.namespaces.has_key(name):
- #raise ImportError,name
- success = 0
- try:
- prefix = "script:"
-
- f = sysold._getframe().f_back
- currdir = f.f_code.co_filename
-
- idx = currdir.find("script/")
- if currdir[-len(name)-3:-3] == name:
- return
- #if currdir.rfind(name) == len(name) +3:
-
- if idx != -1:
- # do path mangling
- if name[0] == "/":
- prefix = "script:"
- else:
- prefix = currdir[idx+7:]
- prefix = prefix[:prefix.rfind("/")]
- prefix = "script:/" + prefix
- #print "%s importing %s, result is %s" % (currdir, name, prefix + "/" + name + '.py')
-
- #print "### %s importing %s, result is %s" % (currdir, name, prefix + "/" + name + '.py')
- #self.BrowseClassFile("script:/" + name + '.py')
- #import log
- ###log.general.Log("###### " + prefix + "/" + name + '.py')
- # if name == 'PyAIO':
- # print 'Browsing file',prefix + "/" + name + '.py'
- self.BrowseClassFile(prefix + "/" + name + '.py')
- # if name == 'PyAIO':
- # print 'Imported PyAIO, that was a good success',prefix + "/" + name + '.py'
- success = 1
- except IOError,val:
- pass
- except blue.error,val:
- pass
- #if not success:
- # try:
- # self.BrowseClassFile(self.ExpandFiles('script:/'+name+'/'))
- # success = 1
- # except IOError,val:
- # pass
- if not success:
- # only try if .dll is found
- check = blue.os.CreateInstance("blue.ResFile")
-
- if check.Open("%s%s.dll" % (blue.os.binpath, name)):
- del check
- # if name == 'PyAIO':
- # print 'found file, '+name+'.dll, browsing'
- self.BrowseClassFile(name + '.dll')
- success = 1
- # else:
- # if name == 'PyAIO':
- # print "Didn't find no file, PyAIO.dll"
-
- if name.find('/'):
- name = name.split('/')[-1]
- if not self.namespaces.has_key(name):
- raise ImportError,name
-
- ns = Namespace(name,self.namespaces[name])
- if hack:
- loc[name] = ns
- return ns
-
-
- # -----------------------------------------------------------------------------------
- # Release
- # -----------------------------------------------------------------------------------
- def Release(self):
- blue.pyos.SpyDirectory()
- import __builtin__
- if getattr(__builtin__,"Using") == self.Using:
- delattr(__builtin__,"Using")
- #delattr(__builtin__,"Include")
- delattr(__builtin__,"CreateInstance")
- del __builtin__.RegisterConstant
- self.namespaces = {}
- self.globs = {}
- self.preloads = {}
-
-
- # -----------------------------------------------------------------------------------
- # AddPreLoadVariable
- # -----------------------------------------------------------------------------------
- def AddPreLoadVariable(self,name,var):
- self.preloads[name] = var
-
-
- # -----------------------------------------------------------------------------------
- def Compile(self, filename):
- print filename
-
- if self.constants is None:
- file = blue.os.CreateInstance("blue.ResFile")
- file.OpenAlways(filename)
- try:
- code = compile(str(file.Read()).replace("\r\n", "\n") + "\n", filename, "exec")
- except Exception, e:
- import log
- log.general.Log("Compile failed on %s: %s" % (filename, e), log.fatal)
- print "Compile failed on %s: %s" % (filename, e)
- raise
- return code
-
-
- print " Preprocessing..",
- rot = blue.os.CreateInstance("blue.Rot")
- source = open(rot.PathToFilename(filename))
- tokens = tokenize.generate_tokens(source.readline)
- processed = []
- replaced = 0
-
- for token in tokens:
- toktype, string, begin, end, linetext = token
-
- if toktype == tokenize.NAME and string == "const":
- # replace a little
- dot = tokens.next() # skip dot
- tok = tokens.next() # this is the const name
- if dot[1] == "." and tok[1] in self.constants:
- newtoken = (tokenize.NUMBER, str(self.constants[tok[1]]), begin, tok[3], linetext)
- processed.append(newtoken)
- replaced += 1
- else:
- # leave as is
- processed.append(token)
- processed.append(dot)
- processed.append(tok)
- else:
- processed.append(token)
-
- src = ""
- lastop = -1
- ind = 0
- indentNow = 0
-
- for token in processed:
- if token[0] == tokenize.INDENT:
- ind += 1
- elif token[0] == tokenize.DEDENT:
- ind -= 1
- elif token[0] in (tokenize.NEWLINE, tokenize.NL):
- if lastop != tokenize.COMMENT or src[-1] != '\n' or token[4] == '\n':
- src += '\n'
- indentNow = 1
- elif token[0] == tokenize.COMMENT:
- if lastop in (tokenize.NEWLINE, tokenize.NL):
- src += token[4]
- else:
- src += " " + token[1]
- else:
- if indentNow:
- indentNow = 0
- src += " " * ind
-
- if lastop == token[0] == tokenize.NAME:
- src += " "
-
- if token[0] == tokenize.OP:
- if token[1][0] in ('+-*/=i%'):
- src += " " + token[1] + " "
- elif token[1][0] in (','):
- src += token[1] + " "
- else:
- src += token[1]
- elif token[0] == tokenize.STRING:
- if lastop in (tokenize.NAME, ) and src[-1] != ' ':
- src += " " + token[1]
- else:
- src += token[1]
- elif token[0] == tokenize.NUMBER:
- if lastop in (tokenize.NAME, ):
- src += " " + token[1]
- else:
- src += token[1]
- elif token[0] == tokenize.NAME and token[1] == "in":
- if src[-1] != ' ':
- src += " "
- src += token[1] + " "
- else:
- src += token[1]
-
- lastop = token[0]
-
- src += '\n'
-
- # For debugging, this writes out the processed source
- ##file = blue.os.CreateInstance("blue.ResFile")
- ##file.Create(filename + ".processed.py")
- ##file.Write(src)
- ##del file
-
- try:
- print "%s consts replaced" % replaced
- print " Compiling..",
- code = compile(src, filename, "exec")
- print "finished."
- except Exception, e:
- print "Compile failed on %s: %s" % (filename, e)
- file = blue.os.CreateInstance("blue.ResFile")
- file.Create(filename + ".failed.py")
- file.Write(src)
- del file
- self.constants = None
- raise
-
- print ""
- return code
-
-
- # -----------------------------------------------------------------------------------
- # BrowseClassFile
- # -----------------------------------------------------------------------------------
- def BrowseClassFile(self,filename,noReload=0,fromReload=1):
- #print 'BrowseClassFile',filename
- #if filename == "PyAIO":
- # raise "wtf!!!"
-
- ret = []
- #if type(filename) == type('fokk'):
- # filename = [filename]
-
- if not len(filename):
- return
-
- import blue, types
-
- #for each in filename:
- if noReload and filename in self.files.itervalues():
- return self.GatherFileGuids()[filename]
-
-
-
- if filename[:8] == 'script:/':
- globaldict = {}
- globaldict.update(self.preloads)
- oldKeys = globaldict.keys()
- #blue.pyos.ExecFile(filename, globaldict)
- scriptfile = blue.os.scriptpath + filename[8:]
- #check = blue.os.CreateInstance("blue.ResFile")
- #if not check.Open(scriptfile):
- # raise IOError,filename
- #if not self.compiledCode.has_key(filename):
- # raise IOError,filename
-
-
- #check.Close()
- #check = None
- #execfile(blue.os.rootpath + "script/"+filename[8:],globaldict)
-
- if self.compiledCode.has_key(filename):
- code = self.compiledCode[filename]
- exec(code, globaldict)
- else:
- check = blue.os.CreateInstance("blue.ResFile")
- if not check.Open(scriptfile):
- raise IOError,filename
- check.Close()
- try:
- code = self.Compile(scriptfile)
- self.compiledCode[filename] = code
- exec(code, globaldict)
- except:
- import log
- log.general.Log("Failed to execute script '%s'"%scriptfile, log.warn)
- raise
- self.compiledCode[filename] = code
-
-
- if globaldict.has_key("exports"):
- exports = globaldict["exports"]
- else:
- exports = {}
-
- for each in globaldict.iterkeys():
- if each not in oldKeys:
- v = globaldict[each]
- # if type(v) == type(self.__class__): #as a test, ejm 03/06/02
- if hasattr(v,"__guid__"):
- if not exports.has_key(v.__guid__):
- exports[v.__guid__] = v
- for cid in exports.iterkeys():
- ret.append(cid)
-
- namespace,name = cid.split(".")
- var = exports[cid]
- if self.mods.has_key(namespace):
- setattr(self.mods[namespace],name,var)
-
- if not self.namespaces.has_key(namespace):
- self.namespaces[namespace] = {}
- if type(var) == types.ClassType:
- var.__module__ = namespace
- if self.files.has_key(cid) and fromReload:
- self.RecurseBases(self.namespaces[namespace][name],exports.keys())
- self.namespaces[namespace][name] = var
- if not self.globs.has_key(namespace):
- self.globs[namespace] = {}
- self.globs[namespace][name] = globaldict
- if not self.files.has_key(cid):
- self.files[cid] = filename
-
- elif filename[-3:] == 'dll':
- if filename in self.loadeddlls:
- return []
- class BlueCreateWrapper:
- def __init__(self,cid):
- self.cid = cid
-
- def __call__(self,*args):
- import blue
- #print self.cid,'called!'
- return blue.os.CreateInstance(self.cid,args)
-
- #import blue
- modulename = filename[:-4]
- m = blue.os.LoadModule(modulename)
- myList = blue.os.GetClassTypes()
- for each in myList:
- moduleInfo = each[0]
- moduleName = moduleInfo["module"]
- className = moduleInfo["classname"]
-
- #if moduleName[0].upper() == 'P':
- # if moduleName == 'PyAIO':
-
- # print 'registering',moduleName,'.',className
- if not self.namespaces.has_key(moduleName):
- self.namespaces[moduleName] = {}
- else:
- if self.namespaces[moduleName].has_key(className):
- continue
- bc = BlueCreateWrapper(moduleName+'.'+className)
- self.namespaces[moduleName][className] = bc
- self.files[moduleName+"."+className] = filename
- if self.mods.has_key(moduleName):
- setattr(self.mods[moduleName],className,bc)
- if self.mods.has_key(modulename):
- for attr in dir(m):
- var = getattr(m,attr)
- setattr(self.mods[modulename],attr,var)
- for attr in dir(m):
- if not self.namespaces.has_key(modulename):
- self.namespaces[modulename] = {}
- var = getattr(m,attr)
- self.namespaces[modulename][attr] = var
- self.files[modulename+"."+attr] = filename
- self.loadeddlls.append(filename)
- return ret
-
- def RecurseBases(self,kl,excepts):
- #print 'RecurseBases 1'
- if type(kl) == type(self.__class__):
- #print 'RecurseBases 2'
- filesToLoad = []
- for ns,space in self.namespaces.iteritems():
- for attribute,kl2 in space.iteritems():
- guid = ns+'.'+attribute
- if type(kl2) == type(self.__class__):
- #print 'checking guid',guid,type(kl2)
- if issubclass(kl2,kl) and kl2 != kl:
- # print 'Want to reload',guid
- if guid not in excepts:
- # print 'Reloading',guid
- fn = self.files.get(guid,None)
- if (fn is not None) and (fn not in filesToLoad):
- filesToLoad.append(fn)
- for f in filesToLoad:
- self.BrowseClassFile(f, fromReload = 0)
-
- # -----------------------------------------------------------------------------------
- # Using
- # -----------------------------------------------------------------------------------
- def CreateInstance(self,cid,arguments = ()):
- """For blue to python marriage"""
- try:
- namespace,name = cid.split('.')
- except:
- raise "InvalidClassID",cid
- #print namespace,name
- #print arguments
- # if name != 'dvec':
- try:
- ns = self.namespaces[namespace]
- except:
- raise NamespaceFailedException,namespace
- try:
- constructor = ns[name]
- except:
- raise AttributeError,name
-
- ret = apply(constructor,arguments)
-
- if hasattr(ret,"__persistvars__"):
- for each in ret.__persistvars__:
- if not hasattr(ret,each):
- setattr(ret,each,None)
-
- if hasattr(ret,"__nonpersistvars__"):
- for each in ret.__nonpersistvars__:
- if not hasattr(ret,each):
- setattr(ret,each,None)
-
- return ret
-
-
- # -----------------------------------------------------------------------------------
- # Using
- # -----------------------------------------------------------------------------------
- def Using(self,namespace):
- import blue, types
-
- f = sysold._getframe().f_back
- loc = f.f_globals
-
- if type(namespace) == types.InstanceType:
- # print namespace.__class__.__name__
- if namespace.__class__.__name__ == 'Namespace':
- # print 'is namespace'
- # print 'caller',f.f_code
- # print loc
- ns = namespace.space
- for k,v in ns.iteritems():
- loc[k] = v
- #f.f_nlocals = f.f_nlocals + 1
- else:
- #print 'caller',f.f_code
- ns = namespace.__dict__
- for k,v in ns.iteritems():
- loc[k] = v
- #f.f_nlocals = f.f_nlocals + 1
-
- elif type(namespace) == type(blue.os):
- meths = namespace.TypeInfo()[3].iterkeys()
- for each in meths:
- loc[each] = getattr(namespace,each)
- attrs = namespace.TypeInfo()[2].iterkeys()
- for each in attrs:
- loc[each] = getattr(namespace,each)
- else:
- raise TypeError,namespace
-
-
- # -----------------------------------------------------------------------------------
- # SetGlobal
- # -----------------------------------------------------------------------------------
- def SetGlobal(self,classId,attr,var):
- namespace,name = classId.split('.')
- if not self.globs.has_key(namespace):
- raise ImportError,namespace
- if not self.globs[namespace].has_key(name):
- raise AttributeError,var
- # if self.globs[namespace][name].has_key(attr):
- #if self.globs[namespace][name][attr] != var:
- #raise "GlobalSharingError",(classId,attr)
- self.globs[namespace][name][attr] = var
-
-
- # -----------------------------------------------------------------------------------
- # RegisterConstant
- # -----------------------------------------------------------------------------------
- def RegisterConstant(self,name,var):
- #namespace,name = classId.split('.')
- namespace = "const"
- if not self.namespaces.has_key(namespace):
- self.namespaces[namespace] = {}
- self.namespaces[namespace][name] = var
-
- # -----------------------------------------------------------------------------------
- # GatherFileGuids
- # -----------------------------------------------------------------------------------
- def GatherFileGuids(self):
- exports = {}
- for guid,filename in self.files.iteritems():
- if not exports.has_key(filename):
- exports[filename] = []
- exports[filename].append(guid)
- return exports
-
- Nasty().Initialize()
-