Exemplo n.º 1
0
    def generate(self):
        """Generate the actual svg from the coding"""
        string = self.encode(self.text)

        if string == 'ERROR':
            return

        name = self.get_id('barcode')

        # use an svg group element to contain the barcode
        barcode = Group()
        barcode.set('id', name)
        barcode.set('style', 'fill: black;')

        barcode.transform.add_translate(self.pos_x, self.pos_y)
        if self.scale:
            barcode.transform.add_scale(self.scale)

        bar_id = 1
        bar_offset = 0
        tops = set()

        for datum in self.graphical_array(string):
            # Datum 0 tells us what style of bar is to come next
            style = self.get_style(int(datum[0]))
            # Datum 1 tells us what width in units,
            # style tells us how wide a unit is
            width = int(datum[1]) * int(style['width'])

            if style['write']:
                tops.add(style['top'])
                rect = Rectangle()
                rect.set('x', str(bar_offset))
                rect.set('y', str(style['top']))
                if self.pos_text == TEXT_POS_TOP:
                    rect.set('y', str(style['top'] + self.font_size))
                rect.set('id', "{}_bar{:d}".format(name, bar_id))
                rect.set('width', str(width))
                rect.set('height', str(style['height']))
                barcode.append(rect)
            bar_offset += width
            bar_id += 1

        for extra in self._extra:
            if extra is not None:
                barcode.append(extra)

        bar_width = bar_offset
        # Add text at the bottom of the barcode
        text = TextElement()
        text.set('x', str(int(bar_width / 2)))
        text.set('y', str(min(tops) + self.font_size - 1))
        if self.pos_text == TEXT_POS_BOTTOM:
            text.set('y', str(self.height + max(tops) + self.font_size))
        text.set('style', TEXT_TEMPLATE % self.font_size)
        text.set('xml:space', 'preserve')
        text.set('id', '{}_text'.format(name))
        text.text = str(self.text)
        barcode.append(text)
        return barcode
Exemplo n.º 2
0
    def test_group_with_number_of_rects(self):

        group = Group()

        xmin, ymin = 1000, 1000
        xmax, ymax = -1000, -1000

        rects = []

        for x, y, w, h in [
            (10, 20, 5, 7),
            (30, 40, 5, 7),
        ]:
            rect = Rectangle(width=str(w), height=str(h), x=str(x), y=str(y))
            rects.append(rect)

            xmin = min(xmin, x)
            xmax = max(xmax, x + w)
            ymin = min(ymin, y)
            ymax = max(ymax, y + h)

            group.append(rect)

        self.assert_bounding_box_is_equal(group, (xmin, xmax), (ymin, ymax))
Exemplo n.º 3
0
    def effect(self):
        svg = self.svg

        if svg.get('width') == None:
            viewbox = svg.get_viewbox()
            svg.set('width', str(viewbox[2]))
            svg.set('height', str(viewbox[3]))

        widthInfo = self.parse_length(svg.get('width'))
        origWidth = widthInfo[0]
        heightInfo = self.parse_length(svg.get('height'))
        origHeight = heightInfo[0]

        # unittouu == desired units to document units. This calculates in the DPI for the document
        # uutounit == user units to desired units with regards to DPI. Inkscape and pretty much everything else uses 96 DPI but illustrator does everything in 72 DPI because adobe is dumb.
        originalWidthInPx = svg.unittouu(svg.get('width'))

        widthInInches = svg.uutounit(svg.get('width'), 'in')
        heightInInches = svg.uutounit(svg.get('height'), 'in')

        documentDPI = svg.unittouu("1in")

        if self.options.toggle_unit_to_inches or self.options.size_select == '':
            targetWidthInches = widthInInches
            targetHeightInches = heightInInches
        else:
            if self.options.size_select == "youth":
                targetWidthInches = 10
                targetHeightInches = 12
            elif self.options.size_select == "adult":
                targetWidthInches = 14
                targetHeightInches = 16
            elif self.options.size_select == "infant":
                targetWidthInches = 7
                targetHeightInches = 8
            elif self.options.size_select == "exlarge":
                targetWidthInches = 16
                targetHeightInches = 18

        # viewbox = svg.get_viewbox()
        # thing2 = discover_unit(svg.get('width'), viewbox[2], default='px')

        if svg.get('viewBox') == None:
            svg.set('viewBox', "0 0 " + str(origWidth) + " " + str(origHeight))

        origViewbox = svg.get_viewbox()

        svg.set(
            'viewBox', '{} {} {} {}'.format(
                origViewbox[0], origViewbox[1],
                (targetWidthInches / widthInInches) * float(origViewbox[2]),
                (targetHeightInches / heightInInches) * float(origViewbox[3])))

        svg.namedview.set('units', "in")
        svg.namedview.set('inkscape:document-units', "in")
        svg.set('width', str(targetWidthInches) + "in")
        svg.set('height', str(targetHeightInches) + "in")

        # svg.namedview.set('inkscape:cx', '218.85925')
        # svg.namedview.set('inkscape:cy', '114.95549')
        # svg.namedview.set('inkscape:zoom', '0.5')

        if self.options.toggle_unit_to_inches or self.options.size_select == '':
            return None

        svg.namedview.set('pagecolor', "#abd7de")
        svg.namedview.set('inkscape:pagecheckerboard', "true")
        svg.namedview.set('inkscape:window-maximized', "1")

        # Set the guides at 1, 2, 3 inches and half board horizontally, and half board vertically
        self.remove_all_existing_guides()
        self.set_guide_at_position(1, True)
        self.set_guide_at_position(2, True)
        self.set_guide_at_position(3, True)
        self.set_guide_at_position(targetHeightInches / 2, True)
        self.set_guide_at_position(targetWidthInches / 2, False)

        newWidthInPx = svg.unittouu(str(targetWidthInches) + "in")

        diff = newWidthInPx - originalWidthInPx
        translateCalc = diff / 2

        # sys.stderr.write("Did we ever make it in here?\nDocument DPI is: " + str(documentDPI) + " " + str(widthInInches) + " " + str(origWidth) + " " + str(targetWidthInches) + " " + str(originalWidthInPx) + " New width in px: " + str(newWidthInPx) + " " + str(translateCalc));

        elementsToGroup = []

        for element in svg:
            tag = element.TAG

            if tag in GRAPHICS_ELEMENTS or tag in CONTAINER_ELEMENTS:
                # sys.stderr.write(str(element.get('transform')) + " " + str(translateCalc))
                # existtingTransform = element.get('transform')

                # This is a bit of a workaround because I don't know how to do a translate operation on an element that already.
                # So what I do is I take any element that already has transform matrix, remove it from the svg, push it onto a group, and add all those elements back onto the svg
                # if existtingTransform != None and re.search("matrix", existtingTransform):
                # sys.stderr.write(str(existtingTransform))

                elementsToGroup.append(element)
                svg.remove(element)

        if len(elementsToGroup) > 0:
            group = Group()

            for element in elementsToGroup:
                group.append(element)

            self.svg.append(group)

        for element in svg:
            tag = element.TAG

            if tag in GRAPHICS_ELEMENTS or tag in CONTAINER_ELEMENTS:

                element.transform.add_translate(translateCalc)
Exemplo n.º 4
0
    def effect(self):
        scale = self.svg.unittouu('1px')  # convert to document units
        self.options.xoffset *= scale
        self.options.yoffset *= scale

        if not self.svg.selected:
            raise inkex.AbortExtension("Please select an object")
        if self.options.type == "geometric":
            bbox = self.svg.selection.bounding_box()
        else:
            bbox = self.svg.selection.first().bounding_box()

        layer = self.svg.get_current_layer()

        self.add_marker('Arrow1Lstart', False)
        self.add_marker('Arrow1Lend', True)

        group = Group()
        layer.append(group)
        group.set('fill', 'none')
        group.set('stroke', 'black')

        line = self.horz_line(bbox.top, [0, 1], bbox)
        line.set('marker-start', 'url(#Arrow1Lstart)')
        line.set('marker-end', 'url(#Arrow1Lend)')
        line.set('stroke-width', str(scale))
        group.append(line)

        line = self.vert_line(bbox.left, [0, 2], bbox)
        line.set('stroke-width', str(0.5 * scale))
        group.append(line)

        line = self.vert_line(bbox.right, [0, 2], bbox)
        line.set('stroke-width', str(0.5 * scale))
        group.append(line)

        line = self.vert_line(bbox.left, [1, 0], bbox)
        line.set('marker-start', 'url(#Arrow1Lstart)')
        line.set('marker-end', 'url(#Arrow1Lend)')
        line.set('stroke-width', str(scale))
        group.append(line)

        line = self.horz_line(bbox.top, [2, 0], bbox)
        line.set('stroke-width', str(0.5 * scale))
        group.append(line)

        line = self.horz_line(bbox.bottom, [2, 0], bbox)
        line.set('stroke-width', str(0.5 * scale))
        group.append(line)

        for node in self.svg.selected.values():
            group.append(node)

        layer.append(group)
        return None
Exemplo n.º 5
0
    def effect(self):

        if len(self.svg.selection) != 1:
            raise AbortExtension(_("Debe seleccionar un objeto"))

        scale = self.svg.unittouu('1mm')  # convert to document units

        patternSize = self.options.patternSize
        fromSize = self.options.fromSize
        toSize = self.options.toSize

        if not (fromSize <= patternSize <= toSize):
            raise AbortExtension(
                _("La talla del patrón debe estar dentro de desde y hasta"))

        downerSizesCount = patternSize - fromSize
        upperSizesCount = toSize - patternSize

        pattern = self.svg.selection.first()
        parent = pattern.getparent()

        bbox = pattern.shape_box()
        scaleX = 10 * scale  # scale width 10mm
        scaleY = 23.21 * scale  # scale height 23.21mm
        width = bbox.width * scale
        height = bbox.height * scale

        for i, size in enumerate(
                range(patternSize + upperSizesCount, patternSize, -1)):
            copy = pattern.duplicate()
            size_text = TextElement()

            proportionX = 1 + (1 - ((width - (scaleX *
                                              (upperSizesCount - i))) / width))
            proportionY = 1 + (1 - ((height -
                                     (scaleY *
                                      (upperSizesCount - i))) / height))

            transform = Transform()
            transform.add_scale(proportionX, proportionY)
            copy.transform = transform

            size_text.text = str(size)
            size_text.set(
                'style',
                "font-size:8px;shape-inside:url(#{});".format(copy.get('id')))

            group = Group()
            group.append(copy)
            group.append(size_text)
            parent.append(group)

            group.set(
                'transform',
                "translate(-{},-{})".format(copy.shape_box().left,
                                            copy.shape_box().top))

        for i, size in enumerate(
                range(patternSize - 1, patternSize - downerSizesCount - 1, -1),
                1):
            copy = pattern.duplicate()
            size_text = TextElement()

            proportionX = (width - (scaleX * i)) / width
            proportionY = (height - (scaleY * i)) / height

            transform = Transform()
            transform.add_scale(proportionX, proportionY)
            copy.transform = transform

            size_text.text = str(size)
            size_text.set(
                'style',
                "font-size:8px;shape-inside:url(#{});".format(copy.get('id')))

            group = Group()
            group.append(copy)
            group.append(size_text)
            parent.append(group)

            group.set(
                'transform',
                "translate(-{},-{})".format(copy.shape_box().left,
                                            copy.shape_box().top))

        patternGroup = Group()
        pattern_size_text = TextElement()
        pattern_size_text.text = str(patternSize)
        pattern_size_text.set(
            'style',
            "font-size:8px;shape-inside:url(#{});".format(pattern.get('id')))
        patternGroup.append(pattern)
        patternGroup.append(pattern_size_text)
        parent.append(patternGroup)
Exemplo n.º 6
0
class PathScatter(pathmodifier.Diffeo):
    def __init__(self):
        super(PathScatter, self).__init__()
        self.arg_parser.add_argument("-n",
                                     "--noffset",
                                     type=float,
                                     dest="noffset",
                                     default=0.0,
                                     help="normal offset")
        self.arg_parser.add_argument("-t",
                                     "--toffset",
                                     type=float,
                                     dest="toffset",
                                     default=0.0,
                                     help="tangential offset")
        self.arg_parser.add_argument(
            "-g",
            "--grouppick",
            type=inkex.Boolean,
            dest="grouppick",
            default=False,
            help="if pattern is a group then randomly pick group members")
        self.arg_parser.add_argument(
            "-m",
            "--pickmode",
            type=str,
            dest="pickmode",
            default="rand",
            help="group pick mode (rand=random seq=sequentially)")
        self.arg_parser.add_argument(
            "-f",
            "--follow",
            type=inkex.Boolean,
            dest="follow",
            default=True,
            help="choose between wave or snake effect")
        self.arg_parser.add_argument(
            "-s",
            "--stretch",
            type=inkex.Boolean,
            dest="stretch",
            default=True,
            help="repeat the path to fit deformer's length")
        self.arg_parser.add_argument("-p",
                                     "--space",
                                     type=float,
                                     dest="space",
                                     default=0.0)
        self.arg_parser.add_argument("-v",
                                     "--vertical",
                                     type=inkex.Boolean,
                                     dest="vertical",
                                     default=False,
                                     help="reference path is vertical")
        self.arg_parser.add_argument(
            "-d",
            "--duplicate",
            type=inkex.Boolean,
            dest="duplicate",
            default=False,
            help="duplicate pattern before deformation")
        self.arg_parser.add_argument(
            "-c",
            "--copymode",
            type=str,
            dest="copymode",
            default="clone",
            help="duplicate pattern before deformation")
        self.arg_parser.add_argument(
            "--tab",
            type=str,
            dest="tab",
            help="The selected UI-tab when OK was pressed")

    def prepareSelectionList(self):
        # first selected->pattern, all but first selected-> skeletons
        pattern_node = self.svg.selected.pop()

        self.gNode = Group()
        pattern_node.getparent().append(self.gNode)

        if self.options.copymode == "copy":
            self.patternNode = pattern_node.duplicate()
        elif self.options.copymode == "clone":
            # TODO: allow 4th option: duplicate the first copy and clone the next ones.
            self.patternNode = self.gNode.add(Use())
            self.patternNode.href = pattern_node
        else:
            self.patternNode = pattern_node

        self.skeletons = self.svg.selected
        self.expand_clones(self.skeletons, True, False)
        self.objects_to_paths(self.skeletons, False)

    def lengthtotime(self, l):
        """
        Receives an arc length l, and returns the index of the segment in self.skelcomp
        containing the corresponding point, to gether with the position of the point on this segment.

        If the deformer is closed, do computations modulo the total length.
        """
        if self.skelcompIsClosed:
            l = l % sum(self.lengths)
        if l <= 0:
            return 0, l / self.lengths[0]
        i = 0
        while (i < len(self.lengths)) and (self.lengths[i] <= l):
            l -= self.lengths[i]
            i += 1
        t = l / self.lengths[min(i, len(self.lengths) - 1)]
        return i, t

    def localTransformAt(self, s, follow=True):
        """
        receives a length, and returns the corresponding point and tangent of self.skelcomp
        if follow is set to false, returns only the translation
        """
        i, t = self.lengthtotime(s)
        if i == len(self.skelcomp) - 1:
            x, y = bezier.between_point(self.skelcomp[i - 1], self.skelcomp[i],
                                        1 + t)
            dx = (self.skelcomp[i][0] -
                  self.skelcomp[i - 1][0]) / self.lengths[-1]
            dy = (self.skelcomp[i][1] -
                  self.skelcomp[i - 1][1]) / self.lengths[-1]
        else:
            x, y = bezier.between_point(self.skelcomp[i], self.skelcomp[i + 1],
                                        t)
            dx = (self.skelcomp[i + 1][0] -
                  self.skelcomp[i][0]) / self.lengths[i]
            dy = (self.skelcomp[i + 1][1] -
                  self.skelcomp[i][1]) / self.lengths[i]
        if follow:
            mat = [[dx, -dy, x], [dy, dx, y]]
        else:
            mat = [[1, 0, x], [0, 1, y]]
        return mat

    def effect(self):

        if len(self.options.ids) < 2:
            inkex.errormsg(_("This extension requires two selected paths."))
            return
        self.prepareSelectionList()

        # center at (0,0)
        bbox = self.patternNode.bounding_box()
        mat = [[1, 0, -bbox.center.x], [0, 1, -bbox.center.y]]
        if self.options.vertical:
            bbox = BoundingBox(-bbox.y, bbox.x)
            mat = (Transform([[0, -1, 0], [1, 0, 0]]) * Transform(mat)).matrix
        mat[1][2] += self.options.noffset
        self.patternNode.transform *= mat

        width = bbox.width
        dx = width + self.options.space

        # check if group and expand it
        patternList = []
        if self.options.grouppick and isinstance(self.patternNode, Group):
            mat = self.patternNode.transform
            for child in self.patternNode:
                child.transform *= mat
                patternList.append(child)
        else:
            patternList.append(self.patternNode)
        # inkex.debug(patternList)

        counter = 0
        for skelnode in self.skeletons.values():
            self.curSekeleton = skelnode.path.to_superpath()
            for comp in self.curSekeleton:
                self.skelcomp, self.lengths = linearize(comp)
                # !!!!>----> TODO: really test if path is closed! end point==start point is not enough!
                self.skelcompIsClosed = (self.skelcomp[0] == self.skelcomp[-1])

                length = sum(self.lengths)
                if self.options.stretch:
                    dx = width + self.options.space
                    n = int(
                        (length - self.options.toffset + self.options.space) /
                        dx)
                    if n > 0:
                        dx = (length - self.options.toffset) / n

                xoffset = self.skelcomp[0][
                    0] - bbox.x.minimum + self.options.toffset
                yoffset = self.skelcomp[0][
                    1] - bbox.y.center - self.options.noffset

                s = self.options.toffset
                while s <= length:
                    mat = self.localTransformAt(s, self.options.follow)
                    if self.options.pickmode == "rand":
                        clone = copy.deepcopy(patternList[random.randint(
                            0,
                            len(patternList) - 1)])

                    if self.options.pickmode == "seq":
                        clone = copy.deepcopy(patternList[counter])
                        counter = (counter + 1) % len(patternList)

                    # !!!--> should it be given an id?
                    # seems to work without this!?!
                    myid = patternList[random.randint(0,
                                                      len(patternList) -
                                                      1)].tag.split('}')[-1]
                    clone.set("id", self.svg.get_unique_id(myid))
                    self.gNode.append(clone)

                    clone.transform *= mat
                    s += dx

        self.patternNode.getparent().remove(self.patternNode)