[Python-modules-commits] [python-odf] 60/118: Rewritten odfimgimport
Wolfgang Borgert
debacle at moszumanska.debian.org
Fri Oct 3 21:27:22 UTC 2014
This is an automated email from the git hooks/post-receive script.
debacle pushed a commit to reference refs/remotes/upstream/master
in repository python-odf.
commit d3dfc04ab7fc24d9f05365dbd23150037c857667
Author: Søren Roug <soren.roug at eea.europa.eu>
Date: Tue Aug 4 20:24:29 2009 +0000
Rewritten odfimgimport
---
odfimgimport/odfimgimport | 154 +++++++---------------------------------------
1 file changed, 22 insertions(+), 132 deletions(-)
diff --git a/odfimgimport/odfimgimport b/odfimgimport/odfimgimport
index edc9b12..98caafa 100755
--- a/odfimgimport/odfimgimport
+++ b/odfimgimport/odfimgimport
@@ -1,6 +1,6 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
-# Copyright (C) 2007 Søren Roug, European Environment Agency
+# Copyright (C) 2007-2009 Søren Roug, European Environment Agency
#
# This is free software. You may redistribute it under the terms
# of the Apache license and the GNU General Public License Version
@@ -17,27 +17,15 @@
#
# Contributor(s):
#
-import zipfile, time, sys, getopt, mimetypes, tempfile
+import zipfile, sys, getopt, mimetypes
from urllib2 import urlopen, quote, unquote
from urlparse import urlunsplit, urlsplit
-import xml.sax, xml.sax.saxutils
-from odf.namespaces import XLINKNS, DRAWNS
-from odf.odfmanifest import manifestlist
-from odf.manifest import Manifest, FileEntry
-try:
- from cStringIO import StringIO
-except ImportError:
- from StringIO import StringIO
+from odf.opendocument import load
+from odf.draw import Image
+import cStringIO
sys.tracebacklimit = 0
-OUTENCODING="utf-8"
-
-UNIXPERMS = 0100644 << 16L # -rw-r--r--
-
-# Manifest list
-mlist = {}
-
# Variable to count the number of retrieval failures
failures = 0
@@ -48,8 +36,9 @@ quiet = 0
verbose = 0
# Dictionary with new pictures. Key is original file path
-# Item is a tuple of ( newfilename, metatype, image )
+# Item is newfilename
newpictures = {}
+doc = None
def importpicture(href):
""" Add the picture to the ZIP file
@@ -57,10 +46,10 @@ def importpicture(href):
If it is unable to import, then it returns the original href
Sideeffect: add line to manifest
"""
- global newpictures, failures, verbose
+ global doc, newpictures, failures, verbose
# Check that it is not already in the manifest
- if mlist.has_key(href): return href
+ if doc.Pictures.has_key(href): return href
image = None
if verbose: print >>sys.stderr, "Importing", href,
@@ -75,7 +64,7 @@ def importpicture(href):
goodhref = urlunsplit(o)
if newpictures.has_key(goodhref):
if verbose: print >>sys.stderr, "already imported"
- return newpictures[goodhref][0] # Already imported
+ return newpictures[goodhref] # Already imported
try:
f = urlopen(goodhref)
image = f.read()
@@ -106,7 +95,7 @@ def importpicture(href):
goodhref = unquote(directory + href[2:])
if newpictures.has_key(goodhref):
if verbose: print >>sys.stderr, "already imported"
- return newpictures[goodhref][0] # Already imported
+ return newpictures[goodhref] # Already imported
mediatype, encoding = mimetypes.guess_type(goodhref)
if mediatype is None:
mediatype = ''
@@ -124,71 +113,19 @@ def importpicture(href):
# If we have a picture to import, the image variable contains it
# and manifestfn, ext and mediatype has a value
if image:
- manifestfn = "Pictures/imported%d%s" % (len(mlist), str(ext))
- mlist[manifestfn] = {'media-type': mediatype, 'full-path': manifestfn }
- newpictures[goodhref] = (manifestfn, mediatype, image)
+ manifestfn = doc.addPictureFromString(image, mediatype)
+ newpictures[goodhref] = manifestfn
return manifestfn
if verbose: print >>sys.stderr, "not imported"
return href
-def makemanifest():
- import cStringIO
- xml=cStringIO.StringIO()
- m = Manifest()
- for key, item in mlist.items():
- f = FileEntry(mediatype=item['media-type'], fullpath=item['full-path'])
- m.addElement(f)
- m.toXml(0,xml)
- return xml.getvalue()
-
def exitwithusage(exitcode=2):
""" Print out usage information and exit """
print >>sys.stderr, "Usage: %s [-q] [-v] [-o output] [inputfile]" % sys.argv[0]
print >>sys.stderr, "\tInputfile must be OpenDocument format"
sys.exit(exitcode)
-base = xml.sax.saxutils.XMLGenerator
-
-class odfcontentparser(base):
-
- def __init__(self):
- self._mimetype = ''
- self.output = StringIO()
- self.seenfields = {}
- base.__init__(self, self.output, OUTENCODING)
-
- def _qname(self, name):
- """Builds a qualified name from a (ns_url, localname) pair"""
- if name[0]:
- if name[0] == u'http://www.w3.org/XML/1998/namespace':
- return u'xml' + ":" + name[1]
- # The name is in a non-empty namespace
- prefix = self._current_context[name[0]]
- if prefix:
- # If it is not the default namespace, prepend the prefix
- return prefix + ":" + name[1]
- # Return the unqualified name
- return name[1]
-
- def startElementNS(self, name, qname, attrs):
- if name == (DRAWNS,u'image'):
- href = attrs.get((XLINKNS,u'href'))
- newhref = importpicture(href)
- attrs = dict(attrs.items())
- # Take advantage that startElementNS can take a normal
- # dict as attrs
- attrs[(XLINKNS,u'href')] = newhref
-
- base.startElementNS(self, name, qname, attrs)
-
- def characters(self, content):
- base.characters(self, content)
-
- def content(self):
- return self.output.getvalue()
-
-now = time.localtime()[:6]
outputfile = None
writefile = True
@@ -206,14 +143,9 @@ for o, a in opts:
if o == "-v":
verbose = 1
-odfs = odfcontentparser()
-parser = xml.sax.make_parser()
-parser.setFeature(xml.sax.handler.feature_namespaces, 1)
-parser.setContentHandler(odfs)
-
if len(args) == 0:
try:
- zin = zipfile.ZipFile(sys.stdin,'r')
+ doc = load(sys.stdin)
directory = None
except:
print >>sys.stderr, "Couldn't open OpenDocument file"
@@ -225,61 +157,19 @@ else:
dirinx = max(fn.rfind('\\'), fn.rfind('/'))
if dirinx >= 0: directory = fn[:dirinx]
else: directory = "."
+ doc = load(fn)
- zin = zipfile.ZipFile(fn, 'r')
-
-manifest = zin.read('META-INF/manifest.xml')
-mlist = manifestlist(manifest)
-content = zin.read('content.xml')
-parser.parse(StringIO(content))
+for image in doc.getElementsByType(Image):
+ href = image.getAttribute('href')
+ newhref = importpicture(href)
+ image.setAttribute('href',newhref)
-if writefile: # Better to check that there are new pictures
+if writefile:
if outputfile is None:
- tempfp = tempfile.TemporaryFile()
- zout = zipfile.ZipFile(tempfp,"w")
- elif outputfile == '-':
- zout = zipfile.ZipFile(sys.stdout,"w")
+ doc.save(fn)
else:
- zout = zipfile.ZipFile(outputfile,"w")
-
-
- # Loop through the input zipfile and copy the content to the output until we
- # get to the content.xml. Then substitute.
- for zinfo in zin.infolist():
- if zinfo.filename == "content.xml":
- # Write content
- zi = zipfile.ZipInfo("content.xml", now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- zout.writestr(zi,odfs.content() )
- elif zinfo.filename == "META-INF/manifest.xml":
- zi = zipfile.ZipInfo("META-INF/manifest.xml", now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- zout.writestr(zi,makemanifest() )
- else:
- payload = zin.read(zinfo.filename)
- zout.writestr(zinfo, payload)
- # Add the new pictures
- for oldpath,picturetpl in newpictures.items():
- zi = zipfile.ZipInfo(picturetpl[0], now)
- zi.compress_type = zipfile.ZIP_DEFLATED
- zi.external_attr = UNIXPERMS
- zout.writestr(zi, picturetpl[2])
-
- zout.close()
-zin.close()
+ doc.save(outputfile)
-# Write the result back into the source file
-if outputfile is None:
- tempfp.seek(0) # Rewind
- savefp = file(fn,'w')
- data = tempfp.read()
- while data:
- savefp.write(data)
- data = tempfp.read()
- tempfp.close()
- savefp.close()
if quiet == 0 and failures > 0:
print >>sys.stderr, "Couldn't import %d image(s)" % failures
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-odf.git
More information about the Python-modules-commits
mailing list