1#!/usr/local/bin/python3.8
2# coding=utf-8
3#
4# Copyright (C) 2009 Aurelio A. Heckert, aurium (a) gmail dot com
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19#
20
21import os
22import re
23import sys
24
25import inkex
26from inkex import Script
27
28class InkWebEffect(inkex.EffectExtension):
29    reUpdateJS = '/\\*\\s* inkweb.js [^*]* InkWebEffect:AutoUpdate \\s*\\*/'
30    def effect(self):
31        pass
32
33    def mustAddInkWebJSCode(self, script):
34        if not script.text:
35            return True
36        if re.search(self.reUpdateJS, script.text):
37            return True
38        return False
39
40    def addInkWebJSCode(self, script):
41        with open(os.path.join(sys.path[0], "inkweb.js")) as js:
42            script.set_text("\n/* inkweb.js - InkWebEffect:AutoUpdate */\n" + js.read())
43
44    def ensureInkWebSupport(self):
45        # Search for the script tag with the inkweb.js code:
46        script = None
47        for child in self.svg.xpath('//svg:script'):
48            if re.search(self.reUpdateJS, child.text):
49                script = child
50
51        if script is None:
52            script = Script(id="inkwebjs", type="text/javascript")
53            self.svg.insert(0, script)
54
55        if self.mustAddInkWebJSCode(script):
56            self.addInkWebJSCode(script)
57