Version 6.4.0.3, tag libreoffice-6.4.0.3
[LibreOffice.git] / writerfilter / source / ooxml / modelpreprocess.py
blobf81496094d473e2663305b97df2d1dd9787d1e38
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 __future__ import print_function
11 from xml.dom import minidom
12 import sys
15 def prefixForGrammar(namespace):
16 ns = namespace.getElementsByTagName("grammar")[0].getAttribute("ns")
17 return ooxUrlAliases[ns]
20 def parseNamespaceAliases(node):
21 ret = {}
22 for k, v in list(node.attributes.items()):
23 if k.startswith("xmlns:"):
24 ret[k.replace('xmlns:', '')] = v
25 return ret
28 def parseNamespaces(fro):
29 sock = open(fro)
30 for i in sock.readlines():
31 line = i.strip()
32 alias, url = line.split(' ')[1:]
33 ooxUrlAliases[url] = alias
34 sock.close()
37 def check(model):
38 defines = [i.getAttribute("name") for i in model.getElementsByTagName("define")]
39 for reference in [i.getAttribute("name") for i in model.getElementsByTagName("ref")]:
40 if reference not in defines:
41 raise Exception("Unknown define element with name '%s'" % reference)
42 for start in [i.getAttribute("name") for i in model.getElementsByTagName("start")]:
43 if start not in defines:
44 raise Exception("Unknown start element with name '%s'" % start)
47 def preprocess(model):
48 modelNode = [i for i in model.childNodes if i.localName == "model"][0]
49 # Alias -> URL, based on "xmlns:" attributes.
50 modelNamespaceAliases = parseNamespaceAliases(modelNode)
51 for i in modelNode.getElementsByTagName("namespace"):
52 grammarprefix = prefixForGrammar(i)
54 grammar = i.getElementsByTagName("grammar")[0]
56 for j in i.getElementsByTagName("element") + i.getElementsByTagName("attribute"):
57 # prefix
58 prefix = ""
59 if ":" in j.getAttribute("name"):
60 nameprefix = j.getAttribute("name").split(':')[0]
61 prefix = ooxUrlAliases[modelNamespaceAliases[nameprefix]]
62 elif j.localName == "attribute":
63 if grammar.getAttribute("attributeFormDefault") == "qualified":
64 prefix = grammarprefix
65 else:
66 prefix = grammarprefix
68 # localname
69 if ":" in j.getAttribute("name"):
70 localname = j.getAttribute("name").split(':')[1]
71 else:
72 localname = j.getAttribute("name")
74 # set the attributes
75 j.setAttribute("prefix", prefix)
76 j.setAttribute("localname", localname)
79 namespacesPath = sys.argv[1]
80 modelPath = sys.argv[2]
82 # URL -> alias, from oox
83 ooxUrlAliases = {}
84 parseNamespaces(namespacesPath)
86 model = minidom.parse(modelPath)
87 check(model)
88 preprocess(model)
89 model.writexml(sys.stdout)
91 # vim:set shiftwidth=4 softtabstop=4 expandtab: