Add metadata as a xml comment

Resolves #66
This commit is contained in:
Florian Festi 2019-07-06 11:47:41 +02:00
parent a19debf1bd
commit fff74cf382
4 changed files with 60 additions and 11 deletions

View File

@ -31,6 +31,11 @@ from xml.sax.saxutils import quoteattr
from contextlib import contextmanager from contextlib import contextmanager
import copy import copy
try: # py3
from shlex import quote
except ImportError: # py2
from pipes import quote
from boxes import edges from boxes import edges
from boxes import formats from boxes import formats
from boxes import svgutil from boxes import svgutil
@ -239,8 +244,16 @@ class Boxes:
self.argparser = ArgumentParser(description=description) self.argparser = ArgumentParser(description=description)
self.edgesettings = {} self.edgesettings = {}
self.inkscapefile = None self.inkscapefile = None
self.argparser._action_groups[1].title = self.__class__.__name__ + " Settings"
self.metadata = {
"name" : self.__class__.__name__,
"description" : self.description,
"group" : self.ui_group,
"url" : "",
"command_line" : ""
}
self.argparser._action_groups[1].title = self.__class__.__name__ + " Settings"
defaultgroup = self.argparser.add_argument_group( defaultgroup = self.argparser.add_argument_group(
"Default Settings") "Default Settings")
defaultgroup.add_argument( defaultgroup.add_argument(
@ -423,6 +436,7 @@ class Boxes:
self.inkscapefile = args[-1] self.inkscapefile = args[-1]
del args[-1] del args[-1]
args = [a for a in args if not a.startswith('--tab=')] args = [a for a in args if not a.startswith('--tab=')]
self.metadata["cli"] = "boxes " + self.__class__.__name__ + " " + " ".join((quote(arg) for arg in args))
for key, value in vars(self.argparser.parse_args(args=args)).items(): for key, value in vars(self.argparser.parse_args(args=args)).items():
# treat edge settings separately # treat edge settings separately
for setting in self.edgesettings: for setting in self.edgesettings:
@ -600,7 +614,7 @@ class Boxes:
self.surface.flush() self.surface.flush()
self.surface.finish() self.surface.finish()
self.formats.convert(self.output, self.format) self.formats.convert(self.output, self.format, self.metadata)
if self.inkscapefile: if self.inkscapefile:
try: try:
out = sys.stdout.buffer out = sys.stdout.buffer

View File

@ -97,11 +97,11 @@ class Formats:
return surface, ctx return surface, ctx
def convert(self, filename, fmt): def convert(self, filename, fmt, metadata=None):
if fmt in ['svg', 'svg_Ponoko']: if fmt in ['svg', 'svg_Ponoko']:
svg = svgutil.SVGFile(filename) svg = svgutil.SVGFile(filename)
svg.fix() svg.fix(metadata)
else: else:
ps = PSFile(filename) ps = PSFile(filename)
ps.adjustDocumentMedia() ps.adjustDocumentMedia()

View File

@ -14,7 +14,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import re import re, datetime
from xml.etree import cElementTree as ElementTree from xml.etree import cElementTree as ElementTree
@ -60,9 +60,10 @@ class SVGFile(object):
self.tree = ElementTree.parse(filename) self.tree = ElementTree.parse(filename)
self.symbol_extends = {} self.symbol_extends = {}
def fix(self): def fix(self, metadata=None):
self.getEnvelope() self.getEnvelope()
self.moveOrigin() self.moveOrigin()
self.addMetadata(metadata)
self.rewriteViewPort() self.rewriteViewPort()
def getExtend(self, element, extend): def getExtend(self, element, extend):
@ -86,13 +87,11 @@ class SVGFile(object):
extend.addPoint(tx, ty) extend.addPoint(tx, ty)
elif element.tag.endswith("}use"): elif element.tag.endswith("}use"):
x, y = float(element.attrib["x"]), float(element.attrib["y"]) x, y = float(element.attrib["x"]), float(element.attrib["y"])
print(element.attrib)
s = self.symbol_extends[element.attrib["{http://www.w3.org/1999/xlink}href"][1:]] s = self.symbol_extends[element.attrib["{http://www.w3.org/1999/xlink}href"][1:]]
extend.addExtend(s, x, y) extend.addExtend(s, x, y)
for e in element: for e in element:
if e.tag.endswith("}symbol"): if e.tag.endswith("}symbol"):
print(e.attrib)
self.symbol_extends[e.attrib["id"]] = self.getExtend(e, Extend()) self.symbol_extends[e.attrib["id"]] = self.getExtend(e, Extend())
else: else:
self.getExtend(e, extend) self.getExtend(e, extend)
@ -160,6 +159,21 @@ class SVGFile(object):
self.tree.write(self.filename) self.tree.write(self.filename)
def addMetadata(self, md):
txt = """
{name} - {description}
Created with Boxes.py (http://festi.info/boxes.py)
Creation date: {date}
""".format(date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") , **md)
txt += "Command line (remove spaces beteen dashes): %s\n" % md["cli"].replace("--", "- -")
if md["url"]:
txt+= "Url: %s\n" % md["url"]
txt+= "SettingsUrl: %s\n" % re.sub(r"&render=[01]", "", md["url"])
m = ElementTree.Comment(txt)
self.tree.getroot().insert(0, m)
unit2mm = {"mm" : 1.0, unit2mm = {"mm" : 1.0,
"cm" : 10.0, "cm" : 10.0,
"in" : 25.4, "in" : 25.4,

View File

@ -28,9 +28,9 @@ import markdown
# Python 2 vs Python 3 compat # Python 2 vs Python 3 compat
try: try:
from urllib.parse import unquote_plus from urllib.parse import unquote_plus, quote
except ImportError: except ImportError:
from urllib import unquote_plus from urllib import unquote_plus, quote
from wsgiref.util import setup_testing_defaults from wsgiref.util import setup_testing_defaults
@ -342,8 +342,28 @@ b"""
f = open(path, 'rb') f = open(path, 'rb')
return environ['wsgi.file_wrapper'](f, 512*1024) return environ['wsgi.file_wrapper'](f, 512*1024)
def serve(self, environ, start_response): def getURL(self, environ):
url = environ['wsgi.url_scheme']+'://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
if environ['wsgi.url_scheme'] == 'https':
if environ['SERVER_PORT'] != '443':
url += ':' + environ['SERVER_PORT']
else:
if environ['SERVER_PORT'] != '80':
url += ':' + environ['SERVER_PORT']
url += quote(environ.get('SCRIPT_NAME', ''))
url += quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
return url
def serve(self, environ, start_response):
if environ["PATH_INFO"].startswith("/static/"): if environ["PATH_INFO"].startswith("/static/"):
return self.serveStatic(environ, start_response) return self.serveStatic(environ, start_response)
@ -396,6 +416,7 @@ b"""
box.format, box.format,
[('Content-type', 'application/unknown; charset=utf-8')])) [('Content-type', 'application/unknown; charset=utf-8')]))
fd, box.output = tempfile.mkstemp() fd, box.output = tempfile.mkstemp()
box.metadata["url"] = self.getURL(environ)
box.open() box.open()
box.render() box.render()
box.close() box.close()