home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2106 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  19.4 KB  |  586 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Use OpenDocument to generate your documents.'''
  5. import zipfile
  6. import time
  7. import sys
  8. import mimetypes
  9. import copy
  10. from cStringIO import StringIO
  11. from namespaces import *
  12. import manifest
  13. import meta
  14. from office import *
  15. import element
  16. from attrconverters import make_NCName
  17. from xml.sax.xmlreader import InputSource
  18. from odfmanifest import manifestlist
  19. __version__ = TOOLSVERSION
  20. _XMLPROLOGUE = u"<?xml version='1.0' encoding='UTF-8'?>\n"
  21. UNIXPERMS = 33188 << 0x10L
  22. IS_FILENAME = 0
  23. IS_IMAGE = 1
  24. sys.setrecursionlimit = 50
  25. odmimetypes = {
  26.     'application/vnd.oasis.opendocument.text': '.odt',
  27.     'application/vnd.oasis.opendocument.text-template': '.ott',
  28.     'application/vnd.oasis.opendocument.graphics': '.odg',
  29.     'application/vnd.oasis.opendocument.graphics-template': '.otg',
  30.     'application/vnd.oasis.opendocument.presentation': '.odp',
  31.     'application/vnd.oasis.opendocument.presentation-template': '.otp',
  32.     'application/vnd.oasis.opendocument.spreadsheet': '.ods',
  33.     'application/vnd.oasis.opendocument.spreadsheet-template': '.ots',
  34.     'application/vnd.oasis.opendocument.chart': '.odc',
  35.     'application/vnd.oasis.opendocument.chart-template': '.otc',
  36.     'application/vnd.oasis.opendocument.image': '.odi',
  37.     'application/vnd.oasis.opendocument.image-template': '.oti',
  38.     'application/vnd.oasis.opendocument.formula': '.odf',
  39.     'application/vnd.oasis.opendocument.formula-template': '.otf',
  40.     'application/vnd.oasis.opendocument.text-master': '.odm',
  41.     'application/vnd.oasis.opendocument.text-web': '.oth' }
  42.  
  43. class OpaqueObject:
  44.     
  45.     def __init__(self, filename, mediatype, content = None):
  46.         self.mediatype = mediatype
  47.         self.filename = filename
  48.         self.content = content
  49.  
  50.  
  51.  
  52. class OpenDocument:
  53.     thumbnail = None
  54.     
  55.     def __init__(self, mimetype, add_generator = True):
  56.         self.mimetype = mimetype
  57.         self.childobjects = []
  58.         self._extra = []
  59.         self.folder = ''
  60.         self.topnode = Document(mimetype = self.mimetype)
  61.         self.topnode.ownerDocument = self
  62.         self.clear_caches()
  63.         self.Pictures = { }
  64.         self.meta = Meta()
  65.         self.topnode.addElement(self.meta)
  66.         if add_generator:
  67.             self.meta.addElement(meta.Generator(text = TOOLSVERSION))
  68.         
  69.         self.scripts = Scripts()
  70.         self.topnode.addElement(self.scripts)
  71.         self.fontfacedecls = FontFaceDecls()
  72.         self.topnode.addElement(self.fontfacedecls)
  73.         self.settings = Settings()
  74.         self.topnode.addElement(self.settings)
  75.         self.styles = Styles()
  76.         self.topnode.addElement(self.styles)
  77.         self.automaticstyles = AutomaticStyles()
  78.         self.topnode.addElement(self.automaticstyles)
  79.         self.masterstyles = MasterStyles()
  80.         self.topnode.addElement(self.masterstyles)
  81.         self.body = Body()
  82.         self.topnode.addElement(self.body)
  83.  
  84.     
  85.     def rebuild_caches(self, node = None):
  86.         if node is None:
  87.             node = self.topnode
  88.         
  89.         self.build_caches(node)
  90.         for e in node.childNodes:
  91.             if e.nodeType == element.Node.ELEMENT_NODE:
  92.                 self.rebuild_caches(e)
  93.                 continue
  94.         
  95.  
  96.     
  97.     def clear_caches(self):
  98.         self.element_dict = { }
  99.         self._styles_dict = { }
  100.         self._styles_ooo_fix = { }
  101.  
  102.     
  103.     def build_caches(self, element):
  104.         if not self.element_dict.has_key(element.qname):
  105.             self.element_dict[element.qname] = []
  106.         
  107.         self.element_dict[element.qname].append(element)
  108.         if element.qname == (STYLENS, u'style'):
  109.             self._register_stylename(element)
  110.         
  111.         styleref = element.getAttrNS(TEXTNS, u'style-name')
  112.         if styleref is not None and self._styles_ooo_fix.has_key(styleref):
  113.             element.setAttrNS(TEXTNS, u'style-name', self._styles_ooo_fix[styleref])
  114.         
  115.  
  116.     
  117.     def _register_stylename(self, element):
  118.         name = element.getAttrNS(STYLENS, u'name')
  119.         if name is None:
  120.             return None
  121.  
  122.     
  123.     def toXml(self, filename = ''):
  124.         xml = StringIO()
  125.         xml.write(_XMLPROLOGUE)
  126.         self.body.toXml(0, xml)
  127.         if not filename:
  128.             return xml.getvalue()
  129.         f = file(filename, 'w')
  130.         f.write(xml.getvalue())
  131.         f.close()
  132.  
  133.     
  134.     def xml(self):
  135.         self._replaceGenerator()
  136.         xml = StringIO()
  137.         xml.write(_XMLPROLOGUE)
  138.         self.topnode.toXml(0, xml)
  139.         return xml.getvalue()
  140.  
  141.     
  142.     def contentxml(self):
  143.         xml = StringIO()
  144.         xml.write(_XMLPROLOGUE)
  145.         x = DocumentContent()
  146.         x.write_open_tag(0, xml)
  147.         if self.scripts.hasChildNodes():
  148.             self.scripts.toXml(1, xml)
  149.         
  150.         if self.fontfacedecls.hasChildNodes():
  151.             self.fontfacedecls.toXml(1, xml)
  152.         
  153.         a = AutomaticStyles()
  154.         stylelist = self._used_auto_styles([
  155.             self.styles,
  156.             self.automaticstyles,
  157.             self.body])
  158.         if len(stylelist) > 0:
  159.             a.write_open_tag(1, xml)
  160.             for s in stylelist:
  161.                 s.toXml(2, xml)
  162.             
  163.             a.write_close_tag(1, xml)
  164.         else:
  165.             a.toXml(1, xml)
  166.         self.body.toXml(1, xml)
  167.         x.write_close_tag(0, xml)
  168.         return xml.getvalue()
  169.  
  170.     
  171.     def manifestxml(self):
  172.         xml = StringIO()
  173.         xml.write(_XMLPROLOGUE)
  174.         self.manifest.toXml(0, xml)
  175.         return xml.getvalue()
  176.  
  177.     
  178.     def metaxml(self):
  179.         self._replaceGenerator()
  180.         x = DocumentMeta()
  181.         x.addElement(self.meta)
  182.         xml = StringIO()
  183.         xml.write(_XMLPROLOGUE)
  184.         x.toXml(0, xml)
  185.         return xml.getvalue()
  186.  
  187.     
  188.     def settingsxml(self):
  189.         x = DocumentSettings()
  190.         x.addElement(self.settings)
  191.         xml = StringIO()
  192.         xml.write(_XMLPROLOGUE)
  193.         x.toXml(0, xml)
  194.         return xml.getvalue()
  195.  
  196.     
  197.     def _parseoneelement(self, top, stylenamelist):
  198.         for e in top.childNodes:
  199.             if e.nodeType == element.Node.ELEMENT_NODE:
  200.                 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')):
  201.                     if e.getAttrNS(styleref[0], styleref[1]):
  202.                         stylename = e.getAttrNS(styleref[0], styleref[1])
  203.                         if stylename not in stylenamelist:
  204.                             stylenamelist.append(stylename)
  205.                         
  206.                     stylename not in stylenamelist
  207.                 
  208.                 stylenamelist = self._parseoneelement(e, stylenamelist)
  209.                 continue
  210.         
  211.         return stylenamelist
  212.  
  213.     
  214.     def _used_auto_styles(self, segments):
  215.         stylenamelist = []
  216.         for top in segments:
  217.             stylenamelist = self._parseoneelement(top, stylenamelist)
  218.         
  219.         stylelist = []
  220.         for e in self.automaticstyles.childNodes:
  221.             if e.getAttrNS(STYLENS, u'name') in stylenamelist:
  222.                 stylelist.append(e)
  223.                 continue
  224.         
  225.         return stylelist
  226.  
  227.     
  228.     def stylesxml(self):
  229.         xml = StringIO()
  230.         xml.write(_XMLPROLOGUE)
  231.         x = DocumentStyles()
  232.         x.write_open_tag(0, xml)
  233.         if self.fontfacedecls.hasChildNodes():
  234.             self.fontfacedecls.toXml(1, xml)
  235.         
  236.         self.styles.toXml(1, xml)
  237.         a = AutomaticStyles()
  238.         a.write_open_tag(1, xml)
  239.         for s in self._used_auto_styles([
  240.             self.masterstyles]):
  241.             s.toXml(2, xml)
  242.         
  243.         a.write_close_tag(1, xml)
  244.         if self.masterstyles.hasChildNodes():
  245.             self.masterstyles.toXml(1, xml)
  246.         
  247.         x.write_close_tag(0, xml)
  248.         return xml.getvalue()
  249.  
  250.     
  251.     def addPicture(self, filename, mediatype = None, content = None):
  252.         if content is None:
  253.             if mediatype is None:
  254.                 (mediatype, encoding) = mimetypes.guess_type(filename)
  255.             
  256.             if mediatype is None:
  257.                 mediatype = ''
  258.                 
  259.                 try:
  260.                     ext = filename[filename.rindex('.'):]
  261.                 ext = ''
  262.  
  263.             else:
  264.                 ext = mimetypes.guess_extension(mediatype)
  265.             manifestfn = 'Pictures/%0.0f%s' % (time.time() * 0x2540BE400L, ext)
  266.             self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype)
  267.         else:
  268.             manifestfn = filename
  269.             self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype)
  270.         return manifestfn
  271.  
  272.     
  273.     def addPictureFromFile(self, filename, mediatype = None):
  274.         if mediatype is None:
  275.             (mediatype, encoding) = mimetypes.guess_type(filename)
  276.         
  277.         if mediatype is None:
  278.             mediatype = ''
  279.             
  280.             try:
  281.                 ext = filename[filename.rindex('.'):]
  282.             except ValueError:
  283.                 ext = ''
  284.             except:
  285.                 None<EXCEPTION MATCH>ValueError
  286.             
  287.  
  288.         None<EXCEPTION MATCH>ValueError
  289.         ext = mimetypes.guess_extension(mediatype)
  290.         manifestfn = 'Pictures/%0.0f%s' % (time.time() * 0x2540BE400L, ext)
  291.         self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype)
  292.         return manifestfn
  293.  
  294.     
  295.     def addPictureFromString(self, content, mediatype):
  296.         ext = mimetypes.guess_extension(mediatype)
  297.         manifestfn = 'Pictures/%0.0f%s' % (time.time() * 0x2540BE400L, ext)
  298.         self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype)
  299.         return manifestfn
  300.  
  301.     
  302.     def addThumbnail(self, filecontent = None):
  303.         if filecontent is None:
  304.             import thumbnail
  305.             self.thumbnail = thumbnail.thumbnail()
  306.         else:
  307.             self.thumbnail = filecontent
  308.  
  309.     
  310.     def addObject(self, document, objectname = None):
  311.         self.childobjects.append(document)
  312.         if objectname is None:
  313.             document.folder = '%s/Object %d' % (self.folder, len(self.childobjects))
  314.         else:
  315.             document.folder = objectname
  316.         return '.%s' % document.folder
  317.  
  318.     
  319.     def _savePictures(self, object, folder):
  320.         hasPictures = False
  321.         for arcname, picturerec in object.Pictures.items():
  322.             (what_it_is, fileobj, mediatype) = picturerec
  323.             self.manifest.addElement(manifest.FileEntry(fullpath = '%s%s' % (folder, arcname), mediatype = mediatype))
  324.             hasPictures = True
  325.             if what_it_is == IS_FILENAME:
  326.                 self._z.write(fileobj, arcname, zipfile.ZIP_STORED)
  327.                 continue
  328.             zi = zipfile.ZipInfo(str(arcname), self._now)
  329.             zi.compress_type = zipfile.ZIP_STORED
  330.             zi.external_attr = UNIXPERMS
  331.             self._z.writestr(zi, fileobj)
  332.         
  333.         if hasPictures:
  334.             self.manifest.addElement(manifest.FileEntry(fullpath = '%sPictures/' % folder, mediatype = ''))
  335.         
  336.         subobjectnum = 1
  337.         for subobject in object.childobjects:
  338.             self._savePictures(subobject, '%sObject %d/' % (folder, subobjectnum))
  339.             subobjectnum += 1
  340.         
  341.  
  342.     
  343.     def _replaceGenerator(self):
  344.         for m in self.meta.childNodes[:]:
  345.             if m.qname == (METANS, u'generator'):
  346.                 self.meta.removeChild(m)
  347.                 continue
  348.         
  349.         self.meta.addElement(meta.Generator(text = TOOLSVERSION))
  350.  
  351.     
  352.     def save(self, outputfile, addsuffix = False):
  353.         if outputfile == '-':
  354.             outputfp = zipfile.ZipFile(sys.stdout, 'w')
  355.         elif addsuffix:
  356.             outputfile = outputfile + odmimetypes.get(self.mimetype, '.xxx')
  357.         
  358.         outputfp = zipfile.ZipFile(outputfile, 'w')
  359.         self._zipwrite(outputfp)
  360.         outputfp.close()
  361.  
  362.     
  363.     def write(self, outputfp):
  364.         zipoutputfp = zipfile.ZipFile(outputfp, 'w')
  365.         self._zipwrite(zipoutputfp)
  366.  
  367.     
  368.     def _zipwrite(self, outputfp):
  369.         self._z = outputfp
  370.         self._now = time.localtime()[:6]
  371.         self.manifest = manifest.Manifest()
  372.         zi = zipfile.ZipInfo('mimetype', self._now)
  373.         zi.compress_type = zipfile.ZIP_STORED
  374.         zi.external_attr = UNIXPERMS
  375.         self._z.writestr(zi, self.mimetype)
  376.         self._saveXmlObjects(self, '')
  377.         self._savePictures(self, '')
  378.         if self.thumbnail is not None:
  379.             self.manifest.addElement(manifest.FileEntry(fullpath = 'Thumbnails/', mediatype = ''))
  380.             self.manifest.addElement(manifest.FileEntry(fullpath = 'Thumbnails/thumbnail.png', mediatype = ''))
  381.             zi = zipfile.ZipInfo('Thumbnails/thumbnail.png', self._now)
  382.             zi.compress_type = zipfile.ZIP_DEFLATED
  383.             zi.external_attr = UNIXPERMS
  384.             self._z.writestr(zi, self.thumbnail)
  385.         
  386.         for op in self._extra:
  387.             if op.filename == 'META-INF/documentsignatures.xml':
  388.                 continue
  389.             
  390.             self.manifest.addElement(manifest.FileEntry(fullpath = op.filename, mediatype = op.mediatype))
  391.             zi = zipfile.ZipInfo(op.filename.encode('utf-8'), self._now)
  392.             zi.compress_type = zipfile.ZIP_DEFLATED
  393.             zi.external_attr = UNIXPERMS
  394.             if op.content is not None:
  395.                 self._z.writestr(zi, op.content)
  396.                 continue
  397.         
  398.         zi = zipfile.ZipInfo('META-INF/manifest.xml', self._now)
  399.         zi.compress_type = zipfile.ZIP_DEFLATED
  400.         zi.external_attr = UNIXPERMS
  401.         self._z.writestr(zi, self.manifestxml())
  402.         del self._z
  403.         del self._now
  404.         del self.manifest
  405.  
  406.     
  407.     def _saveXmlObjects(self, object, folder):
  408.         if self == object:
  409.             self.manifest.addElement(manifest.FileEntry(fullpath = '/', mediatype = object.mimetype))
  410.         else:
  411.             self.manifest.addElement(manifest.FileEntry(fullpath = folder, mediatype = object.mimetype))
  412.         self.manifest.addElement(manifest.FileEntry(fullpath = '%sstyles.xml' % folder, mediatype = 'text/xml'))
  413.         zi = zipfile.ZipInfo('%sstyles.xml' % folder, self._now)
  414.         zi.compress_type = zipfile.ZIP_DEFLATED
  415.         zi.external_attr = UNIXPERMS
  416.         self._z.writestr(zi, object.stylesxml())
  417.         self.manifest.addElement(manifest.FileEntry(fullpath = '%scontent.xml' % folder, mediatype = 'text/xml'))
  418.         zi = zipfile.ZipInfo('%scontent.xml' % folder, self._now)
  419.         zi.compress_type = zipfile.ZIP_DEFLATED
  420.         zi.external_attr = UNIXPERMS
  421.         self._z.writestr(zi, object.contentxml())
  422.         if self == object and self.settings.hasChildNodes():
  423.             self.manifest.addElement(manifest.FileEntry(fullpath = 'settings.xml', mediatype = 'text/xml'))
  424.             zi = zipfile.ZipInfo('%ssettings.xml' % folder, self._now)
  425.             zi.compress_type = zipfile.ZIP_DEFLATED
  426.             zi.external_attr = UNIXPERMS
  427.             self._z.writestr(zi, object.settingsxml())
  428.         
  429.         if self == object:
  430.             self.manifest.addElement(manifest.FileEntry(fullpath = 'meta.xml', mediatype = 'text/xml'))
  431.             zi = zipfile.ZipInfo('meta.xml', self._now)
  432.             zi.compress_type = zipfile.ZIP_DEFLATED
  433.             zi.external_attr = UNIXPERMS
  434.             self._z.writestr(zi, object.metaxml())
  435.         
  436.         subobjectnum = 1
  437.         for subobject in object.childobjects:
  438.             self._saveXmlObjects(subobject, '%sObject %d/' % (folder, subobjectnum))
  439.             subobjectnum += 1
  440.         
  441.  
  442.     
  443.     def createElement(self, element):
  444.         return element(check_grammar = False)
  445.  
  446.     
  447.     def createTextNode(self, data):
  448.         return element.Text(data)
  449.  
  450.     
  451.     def createCDATASection(self, data):
  452.         return element.CDATASection(cdata)
  453.  
  454.     
  455.     def getMediaType(self):
  456.         return self.mimetype
  457.  
  458.     
  459.     def getStyleByName(self, name):
  460.         ncname = make_NCName(name)
  461.         if self._styles_dict == { }:
  462.             self.rebuild_caches()
  463.         
  464.         return self._styles_dict.get(ncname, None)
  465.  
  466.     
  467.     def getElementsByType(self, element):
  468.         obj = element(check_grammar = False)
  469.         if self.element_dict == { }:
  470.             self.rebuild_caches()
  471.         
  472.         return self.element_dict.get(obj.qname, [])
  473.  
  474.  
  475.  
  476. def OpenDocumentChart():
  477.     doc = OpenDocument('application/vnd.oasis.opendocument.chart')
  478.     doc.chart = Chart()
  479.     doc.body.addElement(doc.chart)
  480.     return doc
  481.  
  482.  
  483. def OpenDocumentDrawing():
  484.     doc = OpenDocument('application/vnd.oasis.opendocument.graphics')
  485.     doc.drawing = Drawing()
  486.     doc.body.addElement(doc.drawing)
  487.     return doc
  488.  
  489.  
  490. def OpenDocumentImage():
  491.     doc = OpenDocument('application/vnd.oasis.opendocument.image')
  492.     doc.image = Image()
  493.     doc.body.addElement(doc.image)
  494.     return doc
  495.  
  496.  
  497. def OpenDocumentPresentation():
  498.     doc = OpenDocument('application/vnd.oasis.opendocument.presentation')
  499.     doc.presentation = Presentation()
  500.     doc.body.addElement(doc.presentation)
  501.     return doc
  502.  
  503.  
  504. def OpenDocumentSpreadsheet():
  505.     doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet')
  506.     doc.spreadsheet = Spreadsheet()
  507.     doc.body.addElement(doc.spreadsheet)
  508.     return doc
  509.  
  510.  
  511. def OpenDocumentText():
  512.     doc = OpenDocument('application/vnd.oasis.opendocument.text')
  513.     doc.text = Text()
  514.     doc.body.addElement(doc.text)
  515.     return doc
  516.  
  517.  
  518. def load(odffile):
  519.     LoadParser = LoadParser
  520.     import load
  521.     make_parser = make_parser
  522.     handler = handler
  523.     import xml.sax
  524.     z = zipfile.ZipFile(odffile)
  525.     mimetype = z.read('mimetype')
  526.     doc = OpenDocument(mimetype, add_generator = False)
  527.     manifestpart = z.read('META-INF/manifest.xml')
  528.     manifest = manifestlist(manifestpart)
  529.     for xmlfile in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'):
  530.         if not manifest.has_key(xmlfile):
  531.             continue
  532.         
  533.         
  534.         try:
  535.             xmlpart = z.read(xmlfile)
  536.             doc._parsing = xmlfile
  537.             parser = make_parser()
  538.             parser.setFeature(handler.feature_namespaces, 1)
  539.             parser.setContentHandler(LoadParser(doc))
  540.             parser.setErrorHandler(handler.ErrorHandler())
  541.             inpsrc = InputSource()
  542.             inpsrc.setByteStream(StringIO(xmlpart))
  543.             parser.parse(inpsrc)
  544.             del doc._parsing
  545.         continue
  546.         except KeyError:
  547.             v = None
  548.             continue
  549.         
  550.  
  551.     
  552.     for mentry, mvalue in manifest.items():
  553.         if mentry[:9] == 'Pictures/' and len(mentry) > 9:
  554.             doc.addPicture(mvalue['full-path'], mvalue['media-type'], z.read(mentry))
  555.             continue
  556.         None<EXCEPTION MATCH>KeyError
  557.         if mentry == 'Thumbnails/thumbnail.png':
  558.             doc.addThumbnail(z.read(mentry))
  559.             continue
  560.         if mentry in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'):
  561.             continue
  562.         if mvalue['full-path'][-1] == '/':
  563.             doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], None))
  564.             continue
  565.         doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], z.read(mentry)))
  566.     
  567.     z.close()
  568.     b = doc.getElementsByType(Body)
  569.     if mimetype[:39] == 'application/vnd.oasis.opendocument.text':
  570.         doc.text = b[0].firstChild
  571.     elif mimetype[:43] == 'application/vnd.oasis.opendocument.graphics':
  572.         doc.graphics = b[0].firstChild
  573.     elif mimetype[:47] == 'application/vnd.oasis.opendocument.presentation':
  574.         doc.presentation = b[0].firstChild
  575.     elif mimetype[:46] == 'application/vnd.oasis.opendocument.spreadsheet':
  576.         doc.spreadsheet = b[0].firstChild
  577.     elif mimetype[:40] == 'application/vnd.oasis.opendocument.chart':
  578.         doc.chart = b[0].firstChild
  579.     elif mimetype[:40] == 'application/vnd.oasis.opendocument.image':
  580.         doc.image = b[0].firstChild
  581.     elif mimetype[:42] == 'application/vnd.oasis.opendocument.formula':
  582.         doc.formula = b[0].firstChild
  583.     
  584.     return doc
  585.  
  586.