################################################## # SPYCE - Python-based HTML Scripting # Copyright (c) 2002 Rimon Barr. # # Refer to spyce.py # CVS: $Id: taglib.py 1178 2006-09-12 13:14:19Z ellisj $ ################################################## from spyceModule import spyceModule import os.path __doc__ = '''Spyce tags functionality.''' class taglib(spyceModule): def start(self): self.stack = [] self.taglibs = {} self._api.registerModuleCallback(self.__syncModules) self.__syncModules() def __syncModules(self): modules = self._api.getModules() self.mod_response = modules['response'] self.mod_stdout = modules['stdout'] def finish(self, theError): self._api.unregisterModuleCallback(self.__syncModules) for taglib in self.taglibs.keys(): self.unload(taglib) # load and unload tag libraries def load(self, libname, libfrom=None, libas=None): thename = libname if libas: thename = libas if self.taglibs.has_key(thename): return lib = self._api.spyceTaglib( libname, libfrom, self._api.getFilename())(libname) lib.start() self.taglibs[thename] = lib def unload(self, libname): lib = None try: lib = self.taglibs[libname] del self.taglibs[libname] except KeyError: pass if lib: lib.finish() # tag processing def tagPush(self, libname, tagname, tagid, context, attr, pair): try: parent = self.stack[-1] except: parent = None lib = self.taglibs[libname] sys.path.append(os.path.dirname(lib.__file__)) tag = lib.getTag(self._api, tagname, tagid, context, attr, pair, parent) self.stack.append(tag) def tagPop(self): sys.path.reverse() sys.path.remove(os.path.dirname(self.stack[-1]._lib.__file__)) sys.path.reverse() self.outPopCond() if self.stack: self.stack.pop() def getTag(self): return self.stack[-1] def outPush(self): tag = self.stack[-1] if tag.buffer: tag.setBuffered(1) return self.mod_stdout.push() def outPopCond(self): tag = self.stack[-1] if tag.getBuffered(): tag.setBuffered(0) return self.mod_stdout.pop() def tagBegin(self): tag = self.getTag() tag.setOut(self.mod_response) result = tag.begin(**tag._attrs) self.outPush() return result def tagExport(self): tag = self.getTag() return tag.export() def tagBody(self): contents = self.outPopCond() tag = self.getTag() tag.setOut(self.mod_response) result = tag.body(contents) if result: self.outPush() return result def tagEnd(self): self.outPopCond() tag = self.getTag() tag.setOut(self.mod_response) return tag.end() def tagCatch(self): self.outPopCond() tag = self.getTag() tag.setOut(self.mod_response) # class-based exception instances are in [1], but for string # exceptions [1] is None, so pass [0] (the string raised) tag.catch(sys.exc_info()[1] or sys.exc_info()[0]) def __repr__(self): return 'prefixes: %s; stack: %s' % ( ', '.join(self.taglibs.keys()), ', '.join([x.name for x in self.stack]))