nss: upgrade to release 3.73
[LibreOffice.git] / writerfilter / source / ooxml / modelpreprocess.py
blobd6ef4c175430c57dd720ae5f702d234882ab9423
1 #!/usr/bin/env python
3 # This file is part of the LibreOffice project.
5 # This Source Code Form is subject to the terms of the Mozilla Public
6 # License, v. 2.0. If a copy of the MPL was not distributed with this
7 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 from xml.dom import minidom
11 import sys
14 def prefixForGrammar(namespace):
15 ns = namespace.getElementsByTagName("grammar")[0].getAttribute("ns")
16 return ooxUrlAliases[ns]
19 def parseNamespaceAliases(node):
20 ret = {}
21 for k, v in list(node.attributes.items()):
22 if k.startswith("xmlns:"):
23 ret[k.replace('xmlns:', '')] = v
24 return ret
27 def parseNamespaces(fro):
28 sock = open(fro)
29 for i in sock.readlines():
30 line = i.strip()
31 alias, url = line.split(' ')[1:]
32 ooxUrlAliases[url] = alias
33 sock.close()
36 def check(model):
37 defines = [i.getAttribute("name") for i in model.getElementsByTagName("define")]
38 for reference in [i.getAttribute("name") for i in model.getElementsByTagName("ref")]:
39 if reference not in defines:
40 raise Exception("Unknown define element with name '%s'" % reference)
41 for start in [i.getAttribute("name") for i in model.getElementsByTagName("start")]:
42 if start not in defines:
43 raise Exception("Unknown start element with name '%s'" % start)
46 def preprocess(model):
47 modelNode = [i for i in model.childNodes if i.localName == "model"][0]
48 # Alias -> URL, based on "xmlns:" attributes.
49 modelNamespaceAliases = parseNamespaceAliases(modelNode)
50 for i in modelNode.getElementsByTagName("namespace"):
51 grammarprefix = prefixForGrammar(i)
53 grammar = i.getElementsByTagName("grammar")[0]
55 for j in i.getElementsByTagName("element") + i.getElementsByTagName("attribute"):
56 # prefix
57 prefix = ""
58 if ":" in j.getAttribute("name"):
59 nameprefix = j.getAttribute("name").split(':')[0]
60 prefix = ooxUrlAliases[modelNamespaceAliases[nameprefix]]
61 elif j.localName == "attribute":
62 if grammar.getAttribute("attributeFormDefault") == "qualified":
63 prefix = grammarprefix
64 else:
65 prefix = grammarprefix
67 # localname
68 if ":" in j.getAttribute("name"):
69 localname = j.getAttribute("name").split(':')[1]
70 else:
71 localname = j.getAttribute("name")
73 # set the attributes
74 j.setAttribute("prefix", prefix)
75 j.setAttribute("localname", localname)
78 namespacesPath = sys.argv[1]
79 modelPath = sys.argv[2]
81 # URL -> alias, from oox
82 ooxUrlAliases = {}
83 parseNamespaces(namespacesPath)
85 model = minidom.parse(modelPath)
86 check(model)
87 preprocess(model)
88 model.writexml(sys.stdout)
90 # vim:set shiftwidth=4 softtabstop=4 expandtab: