Ejemplo n.º 1
0
    def filter_layers(self, root, name_dict):
        """Return the xml root with filtered layers"""
        for g in root.xpath("//svg:g", namespaces=inkex.NSS):
            attr = inkex.addNS("label", ns="inkscape")
            if attr not in g.attrib:
                # Not a layer, skip.
                continue
            label = g.attrib[attr]
            if "%" not in label:
                # Nothing to be done, skip.
                continue

            # Treat %IF_???% layers
            match = re.match(".*%IF_([^%]*)%", label)
            if match is not None:
                lookup = match.groups()[0]
                try:
                    var = name_dict[lookup]
                except KeyError:
                    errormsg(_('Column "' + lookup + '" not in the csv file'))
                    continue
                if var and (var.lower() not in ("0", "false", "no")):
                    # Set group visibility to true.
                    if "style" in g.attrib:
                        del g.attrib["style"]
                    # Include the group.
                    continue
                else:
                    # Remove the group's content.
                    g.clear()

            # Treat %UNLESS_???% layers
            match = re.match(".*%UNLESS_([^%]*)%", label)
            if match is not None:
                lookup = match.groups()[0]
                try:
                    var = name_dict[lookup]
                except KeyError:
                    errormsg(_('Column "' + lookup + '" not in the csv file'))
                    continue
                if not (var) or (var.lower() in ("0", "false", "no")):
                    # Set group visibility to true.
                    if "style" in g.attrib:
                        del g.attrib["style"]
                    # Include the group.
                    continue
                else:
                    # Remove the group's content.
                    g.clear()
Ejemplo n.º 2
0
 def handle_csv(self):
     """Read data from the csv file and store the rows into self.data"""
     try:
         reader = csv.reader(open(self.options.datafile, "r"))
     except IOError:
         errormsg(_('Cannot read "{}"'.format(self.options.datafile)))
         raise Exception(_('Cannot read "{}"'.format(self.options.datafile)))
     if self.options.var_type == "name":
         try:
             self.header = reader.next()
         except StopIteration:
             errormsg(_('Data file "{}" contains no data'.format(self.options.datafile)))
             raise Exception(_('Data file "{}" contains no data'.format(self.options.datafile)))
     self.data = []
     for row in reader:
         self.data.append(row)
Ejemplo n.º 3
0
 def expand_extra_vars(self, line, name_dict):
     """Replace extra replacement values with the content from a csv entry"""
     if not self.options.extra_vars:
         return line
     replacement_strings = self.options.extra_vars.split("|")
     for t in replacement_strings:
         try:
             old_txt, column = t.split("=>")
         except ValueError:
             errormsg(_("Unrecognized replacement string {}".format(t)))
             raise Exception(_("Unrecognized replacement string {}".format(t)))
         if line.find(old_txt) < 0:
             # Nothing to be replaced.
             continue
         try:
             new_txt = escape(name_dict[column])
         except KeyError:
             if self.options.var_type == "name":
                 errormsg(_('Wrong column name "{}"'.format(column)))
                 raise Exception(_('Wrong column name "{}"'.format(column)))
             else:
                 errormsg(_("Wrong column number ({})".format(column)))
                 raise Exception(_("Wrong column number ({})".format(column)))
         line = line.replace(old_txt, new_txt)
     return line
Ejemplo n.º 4
0
 def show_preview(self):
     systems = {
         "nt": os.startfile if "startfile" in dir(os) else None,
         "posix": lambda fname: os.system('xdg-open "{0}"'.format(fname)),
         "os2": lambda fname: os.system('open "{0}"'.format(fname)),
     }
     try:
         line = self.svgouts.keys()[0]
         d = self.get_line_desc(line)
         outfile = self.get_output(d)
         systems[os.name](outfile)
     except:
         errormsg(_("Error open preview file"))
Ejemplo n.º 5
0
    def export(self):
        """Writes out all output files"""

        def get_export_cmd(svgfile, fmt, dpi, outfile):
            if False and os.name == "posix":
                # Deactivated for now because rsvg-convert (v 2.36.4) changes
                # the size in output pdf files for some svg files. It's a pity,
                # rsvg-convert is much faster.
                ret = os.system("rsvg-convert --version 1>/dev/null")
                if ret == 0:
                    return (
                        "rsvg-convert"
                        + " --dpi-x="
                        + dpi
                        + " --dpi-y="
                        + dpi
                        + " --format="
                        + fmt
                        + ' --output="'
                        + outfile
                        + '"'
                        + ' "'
                        + svgfile
                        + '"'
                    )
            else:
                return (
                    "inkscape --without-gui " + "--export-dpi=" + dpi + " " + "--export-" + fmt + '="' + outfile + '" '
                    '"' + svgfile + '"'
                )

        for line, svgfile in self.svgouts.iteritems():
            d = self.get_line_desc(line)
            outfile = self.get_output(d)
            if self.options.format == "jpg":
                # TODO: output a jpg file
                self.options.format = "png"
                outfile = outfile.replace("jpg", "png")
            if self.options.format == "svg":
                try:
                    os.rename(svgfile, outfile)
                except OSError:
                    errormsg(_('Cannot create "' + outfile + '"'))
            else:
                cmd = get_export_cmd(svgfile, self.options.format, self.options.dpi, outfile)
                os.system(cmd)
Ejemplo n.º 6
0
 def create_svg(self, name_dict):
     """Writes out a modified svg"""
     s = StringIO.StringIO()
     for svg_line in open(self.svg_file, "r").readlines():
         # Modify the line to handle replacements from extension GUI
         svg_line = self.expand_extra_vars(svg_line, name_dict)
         # Modify the line to handle variables in svg file
         svg_line = self.expand_vars(svg_line, name_dict)
         s.write(svg_line)
     # Modify the svg to include or exclude groups
     root = etree.fromstring(s.getvalue())
     self.filter_layers(root, name_dict)
     svgout = self.get_svgout()
     try:
         f = open(svgout, "w")
         f.write(etree.tostring(root, encoding="utf-8", xml_declaration=True))
     except IOError:
         errormsg(_('Cannot open "' + svgout + '" for writing'))
     finally:
         f.close()
     s.close()
     return svgout