home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- '''Use OpenDocument to generate your documents.'''
- import zipfile
- import time
- import sys
- import mimetypes
- import copy
- from cStringIO import StringIO
- from namespaces import *
- import manifest
- import meta
- from office import *
- import element
- from attrconverters import make_NCName
- from xml.sax.xmlreader import InputSource
- from odfmanifest import manifestlist
- __version__ = TOOLSVERSION
- _XMLPROLOGUE = u"<?xml version='1.0' encoding='UTF-8'?>\n"
- UNIXPERMS = 33188 << 0x10L
- IS_FILENAME = 0
- IS_IMAGE = 1
- sys.setrecursionlimit = 50
- odmimetypes = {
- 'application/vnd.oasis.opendocument.text': '.odt',
- 'application/vnd.oasis.opendocument.text-template': '.ott',
- 'application/vnd.oasis.opendocument.graphics': '.odg',
- 'application/vnd.oasis.opendocument.graphics-template': '.otg',
- 'application/vnd.oasis.opendocument.presentation': '.odp',
- 'application/vnd.oasis.opendocument.presentation-template': '.otp',
- 'application/vnd.oasis.opendocument.spreadsheet': '.ods',
- 'application/vnd.oasis.opendocument.spreadsheet-template': '.ots',
- 'application/vnd.oasis.opendocument.chart': '.odc',
- 'application/vnd.oasis.opendocument.chart-template': '.otc',
- 'application/vnd.oasis.opendocument.image': '.odi',
- 'application/vnd.oasis.opendocument.image-template': '.oti',
- 'application/vnd.oasis.opendocument.formula': '.odf',
- 'application/vnd.oasis.opendocument.formula-template': '.otf',
- 'application/vnd.oasis.opendocument.text-master': '.odm',
- 'application/vnd.oasis.opendocument.text-web': '.oth' }
-
- class OpaqueObject:
-
- def __init__(self, filename, mediatype, content = None):
- self.mediatype = mediatype
- self.filename = filename
- self.content = content
-
-
-
- class OpenDocument:
- thumbnail = None
-
- def __init__(self, mimetype, add_generator = True):
- self.mimetype = mimetype
- self.childobjects = []
- self._extra = []
- self.folder = ''
- self.topnode = Document(mimetype = self.mimetype)
- self.topnode.ownerDocument = self
- self.clear_caches()
- self.Pictures = { }
- self.meta = Meta()
- self.topnode.addElement(self.meta)
- if add_generator:
- self.meta.addElement(meta.Generator(text = TOOLSVERSION))
-
- self.scripts = Scripts()
- self.topnode.addElement(self.scripts)
- self.fontfacedecls = FontFaceDecls()
- self.topnode.addElement(self.fontfacedecls)
- self.settings = Settings()
- self.topnode.addElement(self.settings)
- self.styles = Styles()
- self.topnode.addElement(self.styles)
- self.automaticstyles = AutomaticStyles()
- self.topnode.addElement(self.automaticstyles)
- self.masterstyles = MasterStyles()
- self.topnode.addElement(self.masterstyles)
- self.body = Body()
- self.topnode.addElement(self.body)
-
-
- def rebuild_caches(self, node = None):
- if node is None:
- node = self.topnode
-
- self.build_caches(node)
- for e in node.childNodes:
- if e.nodeType == element.Node.ELEMENT_NODE:
- self.rebuild_caches(e)
- continue
-
-
-
- def clear_caches(self):
- self.element_dict = { }
- self._styles_dict = { }
- self._styles_ooo_fix = { }
-
-
- def build_caches(self, element):
- if not self.element_dict.has_key(element.qname):
- self.element_dict[element.qname] = []
-
- self.element_dict[element.qname].append(element)
- if element.qname == (STYLENS, u'style'):
- self._register_stylename(element)
-
- styleref = element.getAttrNS(TEXTNS, u'style-name')
- if styleref is not None and self._styles_ooo_fix.has_key(styleref):
- element.setAttrNS(TEXTNS, u'style-name', self._styles_ooo_fix[styleref])
-
-
-
- def _register_stylename(self, element):
- name = element.getAttrNS(STYLENS, u'name')
- if name is None:
- return None
-
-
- def toXml(self, filename = ''):
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- self.body.toXml(0, xml)
- if not filename:
- return xml.getvalue()
- f = file(filename, 'w')
- f.write(xml.getvalue())
- f.close()
-
-
- def xml(self):
- self._replaceGenerator()
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- self.topnode.toXml(0, xml)
- return xml.getvalue()
-
-
- def contentxml(self):
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- x = DocumentContent()
- x.write_open_tag(0, xml)
- if self.scripts.hasChildNodes():
- self.scripts.toXml(1, xml)
-
- if self.fontfacedecls.hasChildNodes():
- self.fontfacedecls.toXml(1, xml)
-
- a = AutomaticStyles()
- stylelist = self._used_auto_styles([
- self.styles,
- self.automaticstyles,
- self.body])
- if len(stylelist) > 0:
- a.write_open_tag(1, xml)
- for s in stylelist:
- s.toXml(2, xml)
-
- a.write_close_tag(1, xml)
- else:
- a.toXml(1, xml)
- self.body.toXml(1, xml)
- x.write_close_tag(0, xml)
- return xml.getvalue()
-
-
- def manifestxml(self):
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- self.manifest.toXml(0, xml)
- return xml.getvalue()
-
-
- def metaxml(self):
- self._replaceGenerator()
- x = DocumentMeta()
- x.addElement(self.meta)
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- x.toXml(0, xml)
- return xml.getvalue()
-
-
- def settingsxml(self):
- x = DocumentSettings()
- x.addElement(self.settings)
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- x.toXml(0, xml)
- return xml.getvalue()
-
-
- def _parseoneelement(self, top, stylenamelist):
- for e in top.childNodes:
- if e.nodeType == element.Node.ELEMENT_NODE:
- for styleref in ((DRAWNS, u'style-name'), (DRAWNS, u'text-style-name'), (PRESENTATIONNS, u'style-name'), (STYLENS, u'data-style-name'), (STYLENS, u'list-style-name'), (STYLENS, u'page-layout-name'), (STYLENS, u'style-name'), (TABLENS, u'default-cell-style-name'), (TABLENS, u'style-name'), (TEXTNS, u'style-name')):
- if e.getAttrNS(styleref[0], styleref[1]):
- stylename = e.getAttrNS(styleref[0], styleref[1])
- if stylename not in stylenamelist:
- stylenamelist.append(stylename)
-
- stylename not in stylenamelist
-
- stylenamelist = self._parseoneelement(e, stylenamelist)
- continue
-
- return stylenamelist
-
-
- def _used_auto_styles(self, segments):
- stylenamelist = []
- for top in segments:
- stylenamelist = self._parseoneelement(top, stylenamelist)
-
- stylelist = []
- for e in self.automaticstyles.childNodes:
- if e.getAttrNS(STYLENS, u'name') in stylenamelist:
- stylelist.append(e)
- continue
-
- return stylelist
-
-
- def stylesxml(self):
- xml = StringIO()
- xml.write(_XMLPROLOGUE)
- x = DocumentStyles()
- x.write_open_tag(0, xml)
- if self.fontfacedecls.hasChildNodes():
- self.fontfacedecls.toXml(1, xml)
-
- self.styles.toXml(1, xml)
- a = AutomaticStyles()
- a.write_open_tag(1, xml)
- for s in self._used_auto_styles([
- self.masterstyles]):
- s.toXml(2, xml)
-
- a.write_close_tag(1, xml)
- if self.masterstyles.hasChildNodes():
- self.masterstyles.toXml(1, xml)
-
- x.write_close_tag(0, xml)
- return xml.getvalue()
-
-
- def addPicture(self, filename, mediatype = None, content = None):
- if content is None:
- if mediatype is None:
- (mediatype, encoding) = mimetypes.guess_type(filename)
-
- if mediatype is None:
- mediatype = ''
-
- try:
- ext = filename[filename.rindex('.'):]
- ext = ''
-
- else:
- ext = mimetypes.guess_extension(mediatype)
- manifestfn = 'Pictures/%0.0f%s' % (time.time() * 0x2540BE400L, ext)
- self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype)
- else:
- manifestfn = filename
- self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype)
- return manifestfn
-
-
- def addPictureFromFile(self, filename, mediatype = None):
- if mediatype is None:
- (mediatype, encoding) = mimetypes.guess_type(filename)
-
- if mediatype is None:
- mediatype = ''
-
- try:
- ext = filename[filename.rindex('.'):]
- except ValueError:
- ext = ''
- except:
- None<EXCEPTION MATCH>ValueError
-
-
- None<EXCEPTION MATCH>ValueError
- ext = mimetypes.guess_extension(mediatype)
- manifestfn = 'Pictures/%0.0f%s' % (time.time() * 0x2540BE400L, ext)
- self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype)
- return manifestfn
-
-
- def addPictureFromString(self, content, mediatype):
- ext = mimetypes.guess_extension(mediatype)
- manifestfn = 'Pictures/%0.0f%s' % (time.time() * 0x2540BE400L, ext)
- self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype)
- return manifestfn
-
-
- def addThumbnail(self, filecontent = None):
- if filecontent is None:
- import thumbnail
- self.thumbnail = thumbnail.thumbnail()
- else:
- self.thumbnail = filecontent
-
-
- def addObject(self, document, objectname = None):
- self.childobjects.append(document)
- if objectname is None:
- document.folder = '%s/Object %d' % (self.folder, len(self.childobjects))
- else:
- document.folder = objectname
- return '.%s' % document.folder
-
-
- def _savePictures(self, object, folder):
- hasPictures = False
- for arcname, picturerec in object.Pictures.items():
- (what_it_is, fileobj, mediatype) = picturerec
- self.manifest.addElement(manifest.FileEntry(fullpath = '%s%s' % (folder, arcname), mediatype = mediatype))
- hasPictures = True
- if what_it_is == IS_FILENAME:
- self._z.write(fileobj, arcname, zipfile.ZIP_STORED)
- continue
- zi = zipfile.ZipInfo(str(arcname), self._now)
- zi.compress_type = zipfile.ZIP_STORED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, fileobj)
-
- if hasPictures:
- self.manifest.addElement(manifest.FileEntry(fullpath = '%sPictures/' % folder, mediatype = ''))
-
- subobjectnum = 1
- for subobject in object.childobjects:
- self._savePictures(subobject, '%sObject %d/' % (folder, subobjectnum))
- subobjectnum += 1
-
-
-
- def _replaceGenerator(self):
- for m in self.meta.childNodes[:]:
- if m.qname == (METANS, u'generator'):
- self.meta.removeChild(m)
- continue
-
- self.meta.addElement(meta.Generator(text = TOOLSVERSION))
-
-
- def save(self, outputfile, addsuffix = False):
- if outputfile == '-':
- outputfp = zipfile.ZipFile(sys.stdout, 'w')
- elif addsuffix:
- outputfile = outputfile + odmimetypes.get(self.mimetype, '.xxx')
-
- outputfp = zipfile.ZipFile(outputfile, 'w')
- self._zipwrite(outputfp)
- outputfp.close()
-
-
- def write(self, outputfp):
- zipoutputfp = zipfile.ZipFile(outputfp, 'w')
- self._zipwrite(zipoutputfp)
-
-
- def _zipwrite(self, outputfp):
- self._z = outputfp
- self._now = time.localtime()[:6]
- self.manifest = manifest.Manifest()
- zi = zipfile.ZipInfo('mimetype', self._now)
- zi.compress_type = zipfile.ZIP_STORED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, self.mimetype)
- self._saveXmlObjects(self, '')
- self._savePictures(self, '')
- if self.thumbnail is not None:
- self.manifest.addElement(manifest.FileEntry(fullpath = 'Thumbnails/', mediatype = ''))
- self.manifest.addElement(manifest.FileEntry(fullpath = 'Thumbnails/thumbnail.png', mediatype = ''))
- zi = zipfile.ZipInfo('Thumbnails/thumbnail.png', self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, self.thumbnail)
-
- for op in self._extra:
- if op.filename == 'META-INF/documentsignatures.xml':
- continue
-
- self.manifest.addElement(manifest.FileEntry(fullpath = op.filename, mediatype = op.mediatype))
- zi = zipfile.ZipInfo(op.filename.encode('utf-8'), self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- if op.content is not None:
- self._z.writestr(zi, op.content)
- continue
-
- zi = zipfile.ZipInfo('META-INF/manifest.xml', self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, self.manifestxml())
- del self._z
- del self._now
- del self.manifest
-
-
- def _saveXmlObjects(self, object, folder):
- if self == object:
- self.manifest.addElement(manifest.FileEntry(fullpath = '/', mediatype = object.mimetype))
- else:
- self.manifest.addElement(manifest.FileEntry(fullpath = folder, mediatype = object.mimetype))
- self.manifest.addElement(manifest.FileEntry(fullpath = '%sstyles.xml' % folder, mediatype = 'text/xml'))
- zi = zipfile.ZipInfo('%sstyles.xml' % folder, self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, object.stylesxml())
- self.manifest.addElement(manifest.FileEntry(fullpath = '%scontent.xml' % folder, mediatype = 'text/xml'))
- zi = zipfile.ZipInfo('%scontent.xml' % folder, self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, object.contentxml())
- if self == object and self.settings.hasChildNodes():
- self.manifest.addElement(manifest.FileEntry(fullpath = 'settings.xml', mediatype = 'text/xml'))
- zi = zipfile.ZipInfo('%ssettings.xml' % folder, self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, object.settingsxml())
-
- if self == object:
- self.manifest.addElement(manifest.FileEntry(fullpath = 'meta.xml', mediatype = 'text/xml'))
- zi = zipfile.ZipInfo('meta.xml', self._now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- self._z.writestr(zi, object.metaxml())
-
- subobjectnum = 1
- for subobject in object.childobjects:
- self._saveXmlObjects(subobject, '%sObject %d/' % (folder, subobjectnum))
- subobjectnum += 1
-
-
-
- def createElement(self, element):
- return element(check_grammar = False)
-
-
- def createTextNode(self, data):
- return element.Text(data)
-
-
- def createCDATASection(self, data):
- return element.CDATASection(cdata)
-
-
- def getMediaType(self):
- return self.mimetype
-
-
- def getStyleByName(self, name):
- ncname = make_NCName(name)
- if self._styles_dict == { }:
- self.rebuild_caches()
-
- return self._styles_dict.get(ncname, None)
-
-
- def getElementsByType(self, element):
- obj = element(check_grammar = False)
- if self.element_dict == { }:
- self.rebuild_caches()
-
- return self.element_dict.get(obj.qname, [])
-
-
-
- def OpenDocumentChart():
- doc = OpenDocument('application/vnd.oasis.opendocument.chart')
- doc.chart = Chart()
- doc.body.addElement(doc.chart)
- return doc
-
-
- def OpenDocumentDrawing():
- doc = OpenDocument('application/vnd.oasis.opendocument.graphics')
- doc.drawing = Drawing()
- doc.body.addElement(doc.drawing)
- return doc
-
-
- def OpenDocumentImage():
- doc = OpenDocument('application/vnd.oasis.opendocument.image')
- doc.image = Image()
- doc.body.addElement(doc.image)
- return doc
-
-
- def OpenDocumentPresentation():
- doc = OpenDocument('application/vnd.oasis.opendocument.presentation')
- doc.presentation = Presentation()
- doc.body.addElement(doc.presentation)
- return doc
-
-
- def OpenDocumentSpreadsheet():
- doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet')
- doc.spreadsheet = Spreadsheet()
- doc.body.addElement(doc.spreadsheet)
- return doc
-
-
- def OpenDocumentText():
- doc = OpenDocument('application/vnd.oasis.opendocument.text')
- doc.text = Text()
- doc.body.addElement(doc.text)
- return doc
-
-
- def load(odffile):
- LoadParser = LoadParser
- import load
- make_parser = make_parser
- handler = handler
- import xml.sax
- z = zipfile.ZipFile(odffile)
- mimetype = z.read('mimetype')
- doc = OpenDocument(mimetype, add_generator = False)
- manifestpart = z.read('META-INF/manifest.xml')
- manifest = manifestlist(manifestpart)
- for xmlfile in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'):
- if not manifest.has_key(xmlfile):
- continue
-
-
- try:
- xmlpart = z.read(xmlfile)
- doc._parsing = xmlfile
- parser = make_parser()
- parser.setFeature(handler.feature_namespaces, 1)
- parser.setContentHandler(LoadParser(doc))
- parser.setErrorHandler(handler.ErrorHandler())
- inpsrc = InputSource()
- inpsrc.setByteStream(StringIO(xmlpart))
- parser.parse(inpsrc)
- del doc._parsing
- continue
- except KeyError:
- v = None
- continue
-
-
-
- for mentry, mvalue in manifest.items():
- if mentry[:9] == 'Pictures/' and len(mentry) > 9:
- doc.addPicture(mvalue['full-path'], mvalue['media-type'], z.read(mentry))
- continue
- None<EXCEPTION MATCH>KeyError
- if mentry == 'Thumbnails/thumbnail.png':
- doc.addThumbnail(z.read(mentry))
- continue
- if mentry in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'):
- continue
- if mvalue['full-path'][-1] == '/':
- doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], None))
- continue
- doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], z.read(mentry)))
-
- z.close()
- b = doc.getElementsByType(Body)
- if mimetype[:39] == 'application/vnd.oasis.opendocument.text':
- doc.text = b[0].firstChild
- elif mimetype[:43] == 'application/vnd.oasis.opendocument.graphics':
- doc.graphics = b[0].firstChild
- elif mimetype[:47] == 'application/vnd.oasis.opendocument.presentation':
- doc.presentation = b[0].firstChild
- elif mimetype[:46] == 'application/vnd.oasis.opendocument.spreadsheet':
- doc.spreadsheet = b[0].firstChild
- elif mimetype[:40] == 'application/vnd.oasis.opendocument.chart':
- doc.chart = b[0].firstChild
- elif mimetype[:40] == 'application/vnd.oasis.opendocument.image':
- doc.image = b[0].firstChild
- elif mimetype[:42] == 'application/vnd.oasis.opendocument.formula':
- doc.formula = b[0].firstChild
-
- return doc
-
-