Exemplo n.º 1
0
    def _size_allocate_cb(self, widget, allocation):
        """We know the size of the widget on the screen, so we keep
        the parameters which are important for our rendering (center
        of the clock, radius).
        """
        # This callback can be called when the gdk window is not yet
        # set
        if self.window is None:
            return

        # Store the measures of the clock face widget
        self._center_x = int(allocation.width / 2.0)
        self._center_y = int(allocation.height / 2.0)
        self._radius = max(min(int(allocation.width / 2.0),
                           int(allocation.height / 2.0)) - 20, 0)
        self._line_width = int(self._radius / 150)

        cr = self.window.cairo_create()

        # Draw simple clock background
        self._simple_background_cache = cr.get_target().create_similar(
            cairo.CONTENT_COLOR_ALPHA, self._radius * 2,
            self._radius * 2)
        cache_ctx = cairo.Context(self._simple_background_cache)
        self._draw_simple_background(cache_ctx)
        self._draw_numbers(cache_ctx)

        # Reload the svg handle
        self._svg_handle = Rsvg.Handle(file="clock.svg")

        # Draw nice clock background
        self._nice_background_cache = cr.get_target().create_similar(
            cairo.CONTENT_COLOR_ALPHA, self._radius * 2,
            self._radius * 2)
        cache_ctx = cairo.Context(self._nice_background_cache)
        scale_x = self._radius * 2.0 / self._svg_handle.props.width
        scale_y = self._radius * 2.0 / self._svg_handle.props.height
        matrix = cairo.Matrix(xx=scale_x, yy=scale_y)
        cache_ctx.transform(matrix)
        self._svg_handle.render_cairo(cache_ctx)

        # The hands sizes are proportional to the radius
        self._hand_sizes['hour'] = self._radius * 0.5
        self._hand_sizes['minutes'] = self._radius * 0.8
        self._hand_sizes['seconds'] = self._radius * 0.7

        self.initialized = True
Exemplo n.º 2
0
    def _marker(self, color, txt, lat, lon, ctx, dpi):

        marker_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '..', '..', 'images',
                         'marker.svg'))

        fp = open(marker_path, 'r')
        data = fp.read()
        fp.close()

        if color[0] != '#':
            c = Color(color)
            color = c.hex_l

        data = data.replace('#000000', color)

        rsvg = Rsvg.Handle()
        svg = rsvg.new_from_data(data.encode())

        x, y = self._latlon2xy(lat, lon, dpi)

        scale = (50.0 / svg.props.height) * (dpi / 72.0)

        x -= svg.props.width * scale / 2
        y -= svg.props.height * scale

        ctx.save()
        ctx.translate(x, y)

        ctx.scale(scale, scale)
        svg.render_cairo(ctx)

        pc = PangoCairo.create_context(ctx)
        layout = PangoCairo.create_layout(ctx)
        fd = Pango.FontDescription('Droid Sans')
        fd.set_size(Pango.SCALE)
        layout.set_font_description(fd)
        layout.set_text(txt, -1)
        draw_utils.adjust_font_size(layout, fd, svg.props.width / 3,
                                    svg.props.width / 3)
        ink, logical = layout.get_extents()
        ctx.translate(svg.props.width / 2 - logical.width / svg.props.height,
                      svg.props.height / 5)
        PangoCairo.update_layout(ctx, layout)
        PangoCairo.show_layout(ctx, layout)

        ctx.restore()
Exemplo n.º 3
0
def render(renderer, ctx):
    if renderer.rc.qrcode_text:
        qrcode_text = renderer.rc.qrcode_text
    else:
        qrcode_text = renderer.rc.origin_url

    if not qrcode_text:
        return

    x = convert_pt_to_dots(renderer._map_coords[0], renderer.dpi)
    y = convert_pt_to_dots(renderer._map_coords[1], renderer.dpi)
    w = convert_pt_to_dots(renderer._map_coords[2], renderer.dpi)
    h = convert_pt_to_dots(renderer._map_coords[3], renderer.dpi)
    W = convert_pt_to_dots(renderer.paper_width_pt)

    size = convert_pt_to_dots(
        max(renderer.paper_width_pt, renderer.paper_height_pt),
        renderer.dpi) / 12

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )

    qr.add_data(qrcode_text)
    qr.make(fit=True)

    img = qr.make_image(image_factory=qrcode.image.svg.SvgPathFillImage,
                        fill_color='lightblue')
    svgstr = BytesIO()
    img.save(svgstr)

    svg_val = svgstr.getvalue()

    rsvg = Rsvg.Handle()
    svg = rsvg.new_from_data(svg_val)
    svgstr.close()

    ctx.save()
    ctx.translate(x + w - size, y + h - size)
    ctx.move_to(0, 0)
    factor = size / svg.props.height
    ctx.scale(factor, factor)
    svg.render_cairo(ctx)
    ctx.restore()
Exemplo n.º 4
0
    def _update(self, tempo):
        def map_range(value, ilower, iupper, olower, oupper):
            if value == iupper:
                return oupper
            return olower + int((oupper-olower+1) * (value-ilower) /
                    float(iupper-ilower))

        img = map_range(tempo, self.adjustment.get_lower(),
                            self.adjustment.get_upper(), 0, 7)

        if not self._pixbuf[img]:
            svg = Rsvg.Handle().new_from_data(IMAGE[img])
            self._pixbuf[img] = _from_svg_at_size(handle=svg,
                    width=style.STANDARD_ICON_SIZE,
                    height=style.STANDARD_ICON_SIZE)

        self._image.set_from_pixbuf(self._pixbuf[img])
Exemplo n.º 5
0
def convert_svg2png(infile, outfile, icon_size=None):
    """
        Converts svg files to png using Cairosvg or Inkscape
        @file_path : String; the svg file absolute path
        @dest_path : String; the png file absolute path
    """
    if not disable_svg2png:
        if use_inkscape:
            if icon_size:
                p = Popen([
                    "inkscape", "-z", "-f", infile, "-e", outfile, "-w",
                    str(icon_size), "-h",
                    str(icon_size)
                ],
                          stdout=PIPE,
                          stderr=PIPE)
            else:
                p = Popen(["inkscape", "-z", "-f", infile, "-e", outfile],
                          stdout=PIPE,
                          stderr=PIPE)
            p.communicate()
        else:
            if icon_size:
                handle = Rsvg.Handle()
                svg = handle.new_from_file(infile)
                dim = svg.get_dimensions()

                img = cairo.ImageSurface(cairo.FORMAT_ARGB32, icon_size,
                                         icon_size)
                ctx = cairo.Context(img)
                ctx.scale(icon_size / dim.width, icon_size / dim.height)
                svg.render_cairo(ctx)

                png_io = BytesIO()
                img.write_to_png(png_io)
                with open(outfile, 'wb') as fout:
                    fout.write(png_io.getvalue())
                svg.close()
                png_io.close()
                img.finish()
            else:
                with open(infile, "r") as content_file:
                    svg = content_file.read()
                fout = open(outfile, "wb")
                svg2png(bytestring=bytes(svg, "UTF-8"), write_to=fout)
                fout.close()
    def render(s, ctx, t):
        ctx.save()
        ctx.identity_matrix()

        # first, collect the information on the height and width
        # not sure what the 1.25 means but it's good
        svg_height = s.my_params['fontsize'] * s.svg_out['height'] * 1.25
        svg_width = s.my_params['fontsize'] * s.svg_out['width'] * 1.25

        # then, determine the scaling factor
        clip_x, clip_y, clip_w, clip_h = ctx.clip_extents()
        scaling_factor = s.height(t) * clip_h / float(svg_height)

        # render the svg
        ltx_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                         ceil(svg_width * scaling_factor),
                                         ceil(svg_height * scaling_factor))

        ltx_context = cairo.Context(ltx_surface)
        ltx_context.scale(scaling_factor, scaling_factor)

        handle = Rsvg.Handle()
        svg = handle.new_from_file("./tmp/" + s.hexdigest + ".svg")
        svg.render_cairo(ltx_context)
        svg.close()

        # render bounding box too.
        #ltx_context.rectangle(0, 0, svg_width, svg_height)
        #ltx_context.set_source_rgb(0.3, 0.2, 0.5)  # Solid color
        #ltx_context.set_line_width(1)
        #ltx_context.stroke()

        # calculate the source offset, in pixels
        # the target cposx times pixesl minus width in ctx pixels divided by two
        x_offset = clip_w * s.cpos(t)[0] - (svg_width * scaling_factor) / 2.
        y_offset = clip_h * s.cpos(t)[1] - (svg_height * scaling_factor) / 2.

        r, g, b = s.color(t)
        ctx.set_source_rgba(r, g, b, s.alpha(t))
        ctx.mask_surface(ltx_surface, x_offset, y_offset)

        #ctx.set_source_surface(ltx_surface, x_offset, y_offset)
        #ctx.paint_with_alpha(s.alpha(t))

        ctx.restore()
Exemplo n.º 7
0
    def __init__(self, input_file):

        Gtk.Window.__init__(self, title='Edycja SVG poprzez CSS')
        self.set_border_width(0)
        self.input_file = input_file

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        self.handle = Rsvg.Handle()
        self.image = Gtk.Image()
        svg = self.handle.new_from_file(self.input_file)
        self.image.set_from_pixbuf(svg.get_pixbuf())
        vbox.pack_start(self.image, True, True, 0)

        button = Gtk.Button('Update')
        button.connect('clicked', self.on_click)
        vbox.pack_start(button, True, True, 0)
Exemplo n.º 8
0
    def _load_surface_list(self, names):
        lst = []
        for i in names:
            path = self.clock_theme_dir + "/" + i + ".svg"
            if os.path.exists(path):
                svg = rsvg.Handle(path)
                try:
                    if self.svg_size is None:
                        self.svg_size = svg.get_dimension_data()[2:4]

                    svg_size = self.svg_size

                    sx = self.width / svg_size[0]
                    sy = self.height / svg_size[1]
                    scale = min(sx, sy)
                    surface = cairo.SVGSurface(None, svg_size[0] * scale * 2,
                                               svg_size[1] * scale * 2)
                    context = cairo.Context(surface)
                    self.screen.configure_canvas(context)
                    context.scale(scale, scale)
                    context.translate(svg_size[0], svg_size[1])
                    svg.render_cairo(context)
                    context.translate(-svg_size[0], -svg_size[1])
                    lst.append(
                        ((svg_size[0] * scale, svg_size[1] * scale), surface))
                finally:
                    svg.close()

            path = self.clock_theme_dir + "/" + i + ".gif"
            if os.path.exists(path):
                img_surface = g15cairo.load_surface_from_file(
                    path, self.height)
                surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                             img_surface.get_width() * 2,
                                             img_surface.get_height() * 2)
                context = cairo.Context(surface)
                self.screen.configure_canvas(context)
                context.translate(img_surface.get_width(),
                                  img_surface.get_height())
                context.set_source_surface(img_surface)
                context.paint()
                lst.append(((img_surface.get_width(),
                             img_surface.get_height()), surface))
        return lst
Exemplo n.º 9
0
    def _render_header(self, ctx, area, dpi, color, label, logo = None):
        f = dpi / UTILS.PT_PER_INCH;

        ctx.save()
        ctx.translate(10*f, 10*f)

        c = Color(color);
        ctx.set_source_rgb(c.red, c.green, c.blue)
        ctx.rectangle( 0, 0, (area.w - 20)*f, dpi * 0.8)
        ctx.fill()

        x = 5*f

        if logo != None:
            logo_path = os.path.abspath(os.path.join(
                os.path.dirname(__file__), '..', '..', 'templates', 'poi_markers', 'Font-Awesome-SVG-PNG', 'white', 'svg', logo + '.svg'))

            if os.path.isfile(logo_path):
                rsvg = Rsvg.Handle()
                svg = rsvg.new_from_file(logo_path)

                scale = dpi * 0.6 / svg.props.height;
                x += svg.props.width * scale + 10*f

                ctx.save()
                ctx.translate(5*f, 5*f)
                ctx.scale(scale, scale)
                svg.render_cairo(ctx)
                ctx.restore()
            else:
                LOG.warning("icon not found %s" % logo_path)

        ctx.set_source_rgb(1, 1, 1)
        ctx.select_font_face("Droid Sans Bold",
                             cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)

        ctx.set_font_size(dpi*0.6)
        x_bearing, y_bearing, width, height = ctx.text_extents(label)[:4]
        ctx.move_to(x, 10*f - y_bearing)
        ctx.show_text(label)
        ctx.restore()

        return dpi * 0.8
Exemplo n.º 10
0
def _from_svg_at_size(filename=None,
                      width=None,
                      height=None,
                      handle=None,
                      keep_ratio=True):
    """ import from pixbuf.py """

    if not handle:
        handle = Rsvg.Handle()
        handle.new_from_file(filename)
    dimensions = handle.get_dimensions()
    icon_width = dimensions.width
    icon_height = dimensions.height

    if (icon_width != width or icon_height != height) and \
        icon_width != 0 and icon_height != 0:

        ratio_width = float(width) / icon_width
        ratio_height = float(height) / icon_height

        if keep_ratio:
            ratio = min(ratio_width, ratio_height)
            if ratio_width != ratio:
                ratio_width = ratio
                width = int(icon_width * ratio)
            elif ratio_height != ratio:
                ratio_height = ratio
                height = int(icon_height * ratio)
    else:
        ratio_width = 1
        ratio_height = 1

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    context = cairo.Context(surface)
    context.scale(ratio_width, ratio_height)
    handle.render_cairo(context)

    loader = GdkPixbuf.PixbufLoader.new_with_mime_type('image/png')
    surface.write_to_png(loader)
    loader.close()

    return loader.get_pixbuf()
Exemplo n.º 11
0
def collateA4():
    width, height = 595.27559, 841.88976
    surfaces = [
        cairo.PDFSurface('./out/4x4_collate' + str(x + 1) + '.pdf', width,
                         height) for x in range(29)
    ]
    contexts = [cairo.Context(surface) for surface in surfaces]
    handle = Rsvg.Handle()
    svgs = [
        handle.new_from_file(inp) for inp in
        ['./out/4x4_card' + str(x + 1) + '.svg' for x in range(256)]
    ]
    for i in range(256):
        dim = svgs[i].get_dimensions()
        contexts[i // 9].save()
        contexts[i // 9].translate(A4Positions[i % 9][0],
                                   A4Positions[i % 9][1])
        contexts[i // 9].scale(185 / dim.width, 266 / dim.height)
        svgs[i].render_cairo(contexts[i // 9])
        contexts[i // 9].restore()
Exemplo n.º 12
0
    def init(self):
        if not os.path.isfile(self.filename):
            self.filename = self.default_filename

        if self.filename.split('.')[-1] == 'svg':
            # use rsvg to render the cairo context
            handle = Rsvg.Handle()
            svg = handle.new_from_file(self.filename)
            self.pb = svg.get_pixbuf()

        else:
            self.pb = GdkPixbuf.Pixbuf.new_from_file(self.filename)

        # 1052
        # 744

        # self.pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(self.filename, 100, 100, True)

        self.img_w = self.pb.get_width()
        self.img_h = self.pb.get_height()
Exemplo n.º 13
0
def svgToSurface(filename, width, height):
    file = open(filename, 'r')
    fileStr = file.read()

    fileStr = re.sub('width\s*=\s*\"([0-9]+)\"', 'width=\"{}\"'.format(width), fileStr, 1)
    fileStr = re.sub('height\s*=\s*\"([0-9]+)\"', 'height=\"{}\"'.format(height), fileStr, 1)

    handle = Rsvg.Handle()
    svg = handle.new_from_data(fileStr.encode())

    width, height = map(svg.get_property, ("width", "height"))

    data = array('b')
    data.frombytes((chr(0) * width * height * 4).encode())

    surface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, width, height, width * 4)
    ctx = cairo.Context(surface)
    svg.render_cairo(ctx)

    image = pygame.image.frombuffer(data.tostring(), (width, height), "RGBA")

    return image
Exemplo n.º 14
0
    def _onExpose(self, widget, event):
        svgh = rsvg.Handle()
        try:
            svgh.write(bytes(self.svg, "utf-8"))
        except (GObject.GError, KeyError, ValueError) as ex:
            print('Error reading SVG for display: %s\r\n%s', ex, self.svg)
            svgh.close()
            return
        svgh.close()

        if not self._composited:
            cairo_operator = cairo.OPERATOR_OVER
        else:
            cairo_operator = cairo.OPERATOR_SOURCE
        window = self.get_window()
        cr = window.cairo_create()
        cr.set_source_rgba(1.0, 1.0, 1.0, 0.0)
        cr.set_operator(cairo_operator)
        cr.paint()

        svgh.render_cairo(cr)
        del svgh
Exemplo n.º 15
0
def convert_svg_image(p, o):
    handle = Rsvg.Handle()

    try:
        svg = handle.new_from_file(p)
    except Error as e:
        logger.error(e)
        return None

    width = svg.props.width
    height = svg.props.height

    svg_surface = cairo.SVGSurface(None, width * 2, height * 2)
    svg_context = cairo.Context(svg_surface)
    svg_context.scale(2, 2)
    svg.render_cairo(svg_context)
    svg_surface.write_to_png(o)

    dimensions = image_dimensions(o)
    dimensions = [dimensions[0] / 2, dimensions[1] / 2]

    return dimensions
Exemplo n.º 16
0
 def __init__(self, title=None, height=500, width=500, framerate=20):
     Gtk.Window.__init__(self, title=title)
     self.height = height
     self.width = width
     self.dwg = svgwrite.container.SVG(size=(width, height), debug=False)
     self.canvas = Gtk.Image().new_from_pixbuf(Rsvg.Handle().new_from_data(
         bytes(self.dwg.tostring(), 'ascii')).get_pixbuf())
     self.add(self.canvas)
     self.framerate = framerate
     #self.timeout=GLib.timeout_add(1000//framerate,self._draw)
     self.idle = None
     self.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
     self.connect("delete-event", self.cleanup)
     self.connect("motion-notify-event", self.motion)
     self.mouseX = 0
     self.mouseY = 0
     self.add_events(Gdk.EventMask.KEY_PRESS_MASK)
     self.connect("key-press-event", self._keypress)
     self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
     self.connect("button_press_event", self._mousedown)
     self.keydown = None
     self.mouseclicked = None
     self.mousedown = False
Exemplo n.º 17
0
    def __init__(self,
                 bot,
                 path=None,
                 x=0,
                 y=0,
                 width=None,
                 height=None,
                 alpha=1.0,
                 data=None,
                 pathmode=CORNER,
                 **kwargs):
        Grob.__init__(self, bot)
        ColorMixin.__init__(self, **kwargs)

        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.alpha = alpha
        self.path = path
        self.data = data
        self._pathmode = pathmode
        sh = sw = None  # Surface Height and Width

        if isinstance(self.data, cairo.ImageSurface):
            sw = self.data.get_width()
            sh = self.data.get_height()
            self._surface = self.data
        else:
            # checks if image data is passed in command call, in this case it wraps
            # the data in a StringIO oject in order to use it as a file
            # the data itself must contain an entire image, not just pixel data
            # it can be useful for example to retrieve images from the web without
            # writing temp files (e.g. using nodebox's web library, see example 1 of the library)
            # if no data is passed the path is used to open a local file
            if self.data is None:
                surfaceref = self._surface_cache.get(path)
                if surfaceref:
                    surface = surfaceref.surface
                    if isinstance(surface, cairo.RecordingSurface):
                        extents = surface.get_extents()
                        # extents has x, y which we dont use right now
                        sw = extents.width
                        sh = extents.height
                    else:
                        sw = surface.get_width()
                        sh = surface.get_height()
                elif os.path.splitext(
                        path)[1].lower() == ".svg" and Rsvg is not None:
                    handle = Rsvg.Handle()
                    svg = handle.new_from_file(path)
                    dimensions = svg.get_dimensions()
                    sw = dimensions.width
                    sh = dimensions.height
                    surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA,
                                                     (0, 0, sw, sh))
                    ctx = cairo.Context(surface)
                    pycairo_ctx = driver.ensure_pycairo_context(ctx)
                    svg.render_cairo(pycairo_ctx)
                elif os.path.splitext(path)[1].lower() == ".png":
                    surface = cairo.ImageSurface.create_from_png(path)
                    sw = surface.get_width()
                    sh = surface.get_height()
                else:
                    img = PILImage.open(path)

                    if img.mode != "RGBA":
                        img = img.convert("RGBA")

                    sw, sh = img.size
                    # Would be nice to not have to do some of these conversions :-\
                    bgra_data = img.tobytes("raw", "BGRA", 0, 1)
                    bgra_array = array.array("B", bgra_data)
                    surface = cairo.ImageSurface.create_for_data(
                        bgra_array, cairo.FORMAT_ARGB32, sw, sh, sw * 4)

                self._surface_cache[path] = SurfaceRef(surface)
            else:
                img = PILImage.open(StringIO(self.data))

                if img.mode != "RGBA":
                    img = img.convert("RGBA")

                sw, sh = img.size
                # Would be nice to not have to do some of these conversions :-\
                bgra_data = img.tobytes("raw", "BGRA", 0, 1)
                bgra_array = array.array("B", bgra_data)
                surface = cairo.ImageSurface.create_for_data(
                    bgra_array, cairo.FORMAT_ARGB32, sw, sh, sw * 4)

            if width is not None or height is not None:
                if width:
                    wscale = float(width) / sw
                else:
                    wscale = 1.0
                if height:
                    hscale = float(height) / sh
                else:
                    if width:
                        hscale = wscale
                    else:
                        hscale = 1.0
                self._transform.scale(wscale, hscale)

            self.width = width or sw
            self.height = height or sh
            self._surface = surface

        self._deferred_render()
Exemplo n.º 18
0
def render_banner(data, res_mgr, card_cache=None, emblem_cache=None, base=""):
    tree = ET.parse(base + 'banner.svg')
    root = tree.getroot()
    width, height = int(root.attrib["width"]), int(root.attrib["height"])

    if data.leader_card["id"] == -2:
        card_icon = open(base + "chihiro2x.png", "rb").read()
    else:
        if card_cache is None:
            output = io.BytesIO()
            get_card(data.leader_card["id"], res_mgr, output)
            card_icon = output.getvalue()
        else:
            card_file = card_cache(
                data.leader_card["id"],
                lambda f: get_card(data.leader_card["id"], res_mgr, f))
            card_icon = open(card_file, "rb").read()

    if emblem_cache is None:
        output = io.BytesIO()
        get_emblem(data.emblem_id, res_mgr, output)
        emblem_icon = output.getvalue()
    else:
        emblem_file = emblem_cache(
            data.emblem_id, lambda f: get_emblem(data.emblem_id, res_mgr, f))
        emblem_icon = open(emblem_file, "rb").read()

    icon_uri = "data:image/png;base64," + base64.b64encode(card_icon).decode(
        "ascii")
    emblem_uri = "data:image/png;base64," + base64.b64encode(
        emblem_icon).decode("ascii")

    def set_text(id, val, grp=False):
        if grp:
            e = root.findall('.//svg:g[@id="%s"]/svg:text/svg:tspan' % id, ns)
        else:
            e = root.findall('.//svg:text[@id="%s"]/svg:tspan' % id, ns)
        #assert len(e) != 0
        for i in e:
            while len(i):
                del i[0]
            i.text = val

    e_icon = root.find('.//svg:image[@id="icon"]', ns)
    e_icon.set(xlink + "href", icon_uri)
    e_emblem = root.find('.//svg:image[@id="emblem"]', ns)
    e_emblem.set(xlink + "href", emblem_uri)

    set_text("level", str(data.level))
    set_text("prp", str(data.prp))
    if data.fan >= 10000:
        set_text("fan", "%d万人" % (data.fan // 10000))
    else:
        set_text("fan", "%d人" % data.fan)
    if data.id is None:
        root.find('.//svg:g[@id="gameid_grp"]', ns).clear()
    elif data.id == -2:
        set_text("gameid", "エラー")
    else:
        set_text("gameid", str(data.id))
    set_text("name", data.name)
    set_text("comment", data.comment)
    for k, v in list(data.cleared.items()):
        set_text("cl_" + k, str(v), grp=True)
    for k, v in list(data.full_combo.items()):
        set_text("fc_" + k, str(v), grp=True)
    set_text("cardlevel", str(data.leader_card["level"]), grp=True)

    if data.emblem_ex_value:
        set_text("emblem-rank", str(data.emblem_ex_value))
    else:
        set_text("emblem-rank", "")

    for i, rank in enumerate(["f", "e", "d", "c", "b", "a", "s", "ss", "sss"]):
        if (i + 1) != data.rank and not (rank == "sss" and data.rank == 100):
            root.find('.//svg:g[@id="rk_%s"]' % rank, ns).clear()

    img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 2 * width, 2 * height)
    ctx = cairo.Context(img)
    handle = Rsvg.Handle().new_from_data(ET.tostring(root))
    ctx.scale(2, 2)
    handle.render_cairo(ctx)
    im = Image.frombuffer("RGBA", (2 * width, 2 * height),
                          bytes(img.get_data()), "raw", "BGRA", 0, 1)
    return im
Exemplo n.º 19
0
#!/usr/bin/python
import gi
gi.require_version('Rsvg', '2.0')
from gi.repository import Rsvg
import cairo

INPUTFILE = 'data/sources/Box.svg'

if __name__ == '__main__':
    # create the cairo context
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 128, 128)
    context = cairo.Context(surface)

    # use rsvg to render the cairo context
    handle = Rsvg.Handle()
    svg = handle.new_from_file(INPUTFILE)
    svg.render_cairo(context)
    surface.write_to_png('svg.png')
Exemplo n.º 20
0
    def _render_front_page_footer(self, ctx, w, h, osm_date):
        ctx.save()

        # Draw the footer
        ctx.translate(0, 0.8 * h + 2 * Renderer.PRINT_SAFE_MARGIN_PT)

        # Display a nice grey rectangle as the background of the
        # footer
        footer_w = w
        footer_h = 0.2 * h - 2 * Renderer.PRINT_SAFE_MARGIN_PT
        ctx.set_source_rgb(.80,.80,.80)
        ctx.rectangle(0, 0, footer_w, footer_h)
        ctx.fill()

        # Draw the OpenStreetMap logo to the right of the footer
        logo_height = footer_h / 2
        grp, logo_width = self._get_osm_logo(ctx, logo_height)
        if grp:
            ctx.save()
            ctx.translate(w - logo_width - Renderer.PRINT_SAFE_MARGIN_PT,
                          logo_height / 2)
            ctx.set_source(grp)
            ctx.paint_with_alpha(0.8)
            ctx.restore()

        # add QRcode if qrcode text is provided
        if self.rc.qrcode_text:
                qr = qrcode.QRCode(
                    version=1,
                    error_correction=qrcode.constants.ERROR_CORRECT_L,
                    box_size=10,
                    border=4,
                )

                qr.add_data(self.rc.qrcode_text);
                qr.make(fit=True)

                img = qr.make_image(image_factory=qrcode.image.svg.SvgPathFillImage,
                                    fill_color='lightblue')
                svgstr = BytesIO()
                img.save(svgstr);

                svg_val = svgstr.getvalue()

                rsvg = Rsvg.Handle()
                svg = rsvg.new_from_data(svg_val)
                svgstr.close()

                ctx.save()
                ctx.translate(w - 2*logo_width - 2*Renderer.PRINT_SAFE_MARGIN_PT,
                              logo_height/2)
                ctx.move_to(0, 0)
                factor = logo_height / svg.props.height
                ctx.scale(factor, factor)
                svg.render_cairo(ctx)
                ctx.restore()

        # Prepare the text for the left of the footer
        today = datetime.date.today()
        notice = _(u'Copyright © %(year)d MapOSMatic/OCitySMap developers.')
        notice+= '\n\n'
        notice+= _(u'Map data © %(year)d OpenStreetMap contributors (see http://osm.org/copyright)')
        notice+= '\n'
        annotations = []

        if self.rc.stylesheet.annotation != '':
            annotations.append(self.rc.stylesheet.annotation)
            for overlay in self._overlays:
                if overlay.annotation != '':
                    annotations.append(overlay.annotation)
        if len(annotations) > 0:
            notice+= _(u'Map styles:')
            notice+= ' ' + '; '.join(annotations) + '\n'

        notice+= _(u'Map rendered on: %(date)s. OSM data updated on: %(osmdate)s.')
        notice+= '\n'
        notice+= _(u'The map may be incomplete or inaccurate.')

        # We need the correct locale to be set for strftime().
        prev_locale = locale.getlocale(locale.LC_TIME)
        locale.setlocale(locale.LC_TIME, self.rc.i18n.language_code())
        try:
            if osm_date is None:
                osm_date_str = _(u'unknown')
            else:
                osm_date_str = osm_date.strftime("%d %B %Y %H:%M")

            notice = notice % {'year': today.year,
                               'date': today.strftime("%d %B %Y"),
                               'osmdate': osm_date_str}
        finally:
            locale.setlocale(locale.LC_TIME, prev_locale)

        draw_utils.draw_text_adjusted(ctx, notice,
                Renderer.PRINT_SAFE_MARGIN_PT, footer_h/2, footer_w,
                footer_h, align=Pango.Alignment.LEFT)
        ctx.restore()
Exemplo n.º 21
0
    def _render_item(self, ctx, area, dpi, color, number, label, gridlabel, logo = None):
        f = dpi / UTILS.PT_PER_INCH;

        x = 5*f

        marker_path = os.path.abspath(os.path.join(
            os.path.dirname(__file__), '..', '..', 'images', 'marker.svg'))

        fp = open(marker_path,'r')
        data = fp.read()
        fp.close()

        if color[0] != '#':
            c = Color(color);
            color = c.hex_l

        data = data.replace('#000000', color)

        rsvg = Rsvg.Handle()
        svg = rsvg.new_from_data(data.encode())

        scale = 50.0 * f/ svg.props.height;
        x += 35*f

        ctx.save()

        ctx.scale(scale, scale)
        svg.render_cairo(ctx)

        ctx.restore()

        ctx.save()
        ctx.set_source_rgb(0, 0, 0)
        ctx.select_font_face("Droid Sans Mono",
                             cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)

        x_bearing, y_bearing, width, height = ctx.text_extents(number)[:4]
        ctx.set_font_size((dpi*0.6)/(len(number)+1))
        ctx.move_to(20*f - f*width/2, 25*f)
        ctx.show_text(number)
        ctx.restore()

        if logo != None:
            logo_path = os.path.abspath(os.path.join(
                os.path.dirname(__file__), '..', '..', 'templates', 'poi_markers', 'Font-Awesome-SVG-PNG', 'black', 'svg', logo + '.svg'))

            if os.path.isfile(logo_path):
                rsvg = Rsvg.Handle()
                svg = rsvg.new_from_file(logo_path)

                scale = min(dpi * 0.6 / svg.props.height, dpi * 0.6 / svg.props.width);

                ctx.save()
                ctx.translate(x + 5, 5*f)
                ctx.scale(scale, scale)
                svg.render_cairo(ctx)
                ctx.restore()
                
                x += svg.props.width * scale + 10*f
            else:
                LOG.warning("icon not found %s" % logo_path)

        ctx.save()
        ctx.set_source_rgb(0, 0, 0)
        ctx.select_font_face("Droid Sans",
                             cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)

        ctx.set_font_size(dpi*0.6)
        x_bearing, y_bearing, width, height = ctx.text_extents(label)[:4]
        ctx.move_to(x, 10*f - y_bearing)
        ctx.show_text(label)

        ctx.select_font_face("Droid Sans Mono",
                             cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)

        gridParts = re.match('^([A-Z]+)([0-9]+)$', gridlabel)
        gridlabel = gridParts.group(1) + '-' + gridParts.group(2)

        x_bearing, y_bearing, width, height = ctx.text_extents(gridlabel)[:4]
        ctx.move_to((area.w - 15)*f - width, 10*f + height)
        ctx.show_text(gridlabel)

        ctx.restore()

        return dpi * 0.7
Exemplo n.º 22
0
    def update_frame(self):
        if not self.frame_updated:
            return
        self.frame_updated = False

        if not self.active_slide:
            return

        slide = self.slides[self.active_slide]
        svg = slide['raw'].replace('</svg>', '')

        for annotation_id, annotation in sorted(self.annotations.items(),
                                                key=lambda v: v[1]['counter']):
            if annotation['whiteboardId'] != slide['whiteboardId']:
                continue

            # only draw finished shapes
            if 'status' not in annotation or annotation['status'] != 'DRAW_END':
                continue

            if annotation['svg'] is None:
                annotation['svg'] = shapes.generate_svg(annotation, slide)
            svg += annotation['svg']

        svg += '</svg>'

        if svg != self.framesvg:
            self.framesvg = svg

            handle = Rsvg.Handle()
            svghandle = handle.new_from_data(self.framesvg.encode())

            scale_w = 1920 / svghandle.get_dimensions().width
            scale_h = 1080 / svghandle.get_dimensions().height

            if scale_w > scale_h:
                scale = scale_h
                width = int(svghandle.get_dimensions().width * scale_h)
                height = int(svghandle.get_dimensions().height * scale_h)
            else:
                scale = scale_w
                width = int(svghandle.get_dimensions().width * scale_w)
                height = int(svghandle.get_dimensions().height * scale_w)

            surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
            context = cairo.Context(surface)
            context.scale(scale, scale)

            if self.frameres != (width, height):
                self.frameres = (width, height)

                curcaps = self.appsrc.get_property("caps")
                curwidth, curheight = curcaps.get_structure(0).get_value(
                    "width"), curcaps.get_structure(0).get_value("height")
                if curwidth != width or curheight != height:
                    caps = curcaps.copy()
                    caps.set_value("width", width)
                    caps.set_value("height", height)
                    self.appsrc.set_property("caps", caps)
                    log.info("Resized presentation canvas")

            svghandle.render_cairo(context)

            self.frame = bytes(surface.get_data())
            ctypes.memmove(self.mapped_framebuf, self.frame, len(self.frame))

        log.debug("Presentation frame updated")
Exemplo n.º 23
0
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os

import cairo
# import rsvg
from gi.repository import Rsvg as rsvg

# import gnome15.util.g15convert as g15convert
import gnome15.util.g15cairo as g15cairo

needles = {
    "cpu_pc": (170, 90,
               rsvg.Handle(
                   os.path.join(os.path.dirname(__file__),
                                "g19-large-needle.svg"))),
    "net_send_pc":
    (82, 198,
     rsvg.Handle(os.path.join(os.path.dirname(__file__),
                              "g19-tiny-needle.svg"))),
    "net_recv_pc": (82, 198,
                    rsvg.Handle(
                        os.path.join(os.path.dirname(__file__),
                                     "g19-small-needle.svg"))),
    "mem_used_pc": (254, 198,
                    rsvg.Handle(
                        os.path.join(os.path.dirname(__file__),
                                     "g19-small-needle.svg"))),
    "mem_cached_pc":
    (254, 198,
Exemplo n.º 24
0
    def saveAx(self, fn=None, ax='a4', svg_list=None):
        """Store history of previously files in a DIN-format file.

        Note
        ----
        In the optional parameter svg_list, a custom list of file paths may be used instead of the 
        history of previously stored files.

        Parameters
        ----------
        fn
            Filename of the saved file. If left blank, the filename defaults to the existing filename 
            saved in the class members. If there is no filename, it defaults to default_Ax.svg. 
            The filename will be stored in the _fnAx class member.
        ax
            String to define the size of the DIN format document. Allowed is 'a0', 'a1', ..., 'a10'.
        svg_list
            Custom list of paths to files, which should be aranged to the DIN format svg file. By default 
            the history of paths to all files stored by the save() function, stored in the class member 
            _fn_list is stored.
        
        """
        widthAx = {
            'a10': 92,
            'a9': 131,
            'a8': 184,
            'a7': 262,
            'a6': 372,
            'a5': 524,
            'a4': 744,
            'a3': 1052,
            'a2': 1488,
            'a1': 2104,
            'a0': 2979
        }
        heightAx = {
            'a10': 131,
            'a9': 184,
            'a8': 262,
            'a7': 372,
            'a6': 524,
            'a5': 524,
            'a4': 1052,
            'a3': 1488,
            'a2': 2104,
            'a1': 2979,
            'a0': 4212
        }
        if svg_list == None:
            if self._fn_list == []:
                warnings.warn(
                    'svg_list is empty. No files available to store to Ax file.'
                )
                svg_list = []
            else:
                svg_list = self._fn_list

        if fn == None:
            fn = "default_Ax.svg"

        if not self.overwrite:
            fn = self._check_fn_exists(fn)

        self._fnAx = fn

        if self.landscapeAx:
            width = heightAx[ax]
            height = widthAx[ax]
        else:
            width = widthAx[ax]
            height = heightAx[ax]

        pg_nmb = 0
        self._fnAx = self._fn_sub_str(fn, ('_pg' + str(pg_nmb)))
        self.__create(self._fnAx, width, height)

        x_pos = 0
        y_pos = 0

        svg_label = sg.fromfile(self._fnAx)

        # derzeit noch suboptimal, da nur gut fuer gleich Hoehen (todo: besseren Algorithmus entwickeln)
        for svg_file in svg_list:
            handle = Rsvg.Handle()
            svg = handle.new_from_file(svg_file)
            h = svg.get_dimensions().height
            w = svg.get_dimensions().width
            #rsvg_anker = Rsvg.Handle(file=svg_file)
            #(w, h, w2, h2) = rsvg_anker.get_dimension_data()
            anker = sg.fromfile(svg_file).getroot()
            anker.moveto(x_pos, y_pos, scale=1.0)
            svg_label.append(anker)

            if (width - (x_pos + w)) > w:
                x_pos += w
            else:
                if (height - (y_pos + h)) > h:
                    y_pos += h
                    x_pos = 0
                else:  # new page
                    # store current page -> todo: check if file exists
                    svg_label.save(self._fnAx)
                    # reset positions
                    x_pos = 0
                    y_pos = 0
                    # increase page number
                    pg_nmb += 1
                    # create new page
                    self._fnAx = self._fn_sub_str(fn, ('_pg' + str(pg_nmb)))
                    self.__create(self._fnAx, width, height)
                    svg_label = sg.fromfile(self._fnAx)

            #if h>max_height:
            #	max_height=h

        self._fnAx = self._fn_sub_str(fn, ('_pg' + str(pg_nmb + 0)))
        svg_label.save(self._fnAx)
Exemplo n.º 25
0
def load_surface_from_file(filename, size=None):
    type = None
    if filename == None:
        logger.warning("Empty filename requested")
        return None

    if filename.startswith("http:") or filename.startswith("https:"):
        full_cache_path = get_image_cache_file(filename, size)
        if full_cache_path:
            meta_fileobj = open(full_cache_path + "m", "r")
            type = meta_fileobj.readline()
            meta_fileobj.close()
            if type == "image/svg+xml" or filename.lower().endswith(".svg"):
                return load_svg_as_surface(filename, size)
            else:
                return pixbuf_to_surface(
                    GdkPixbuf.Pixbuf.new_from_file(full_cache_path), size)

    if is_url(filename):
        type = None
        try:
            file = urllib.request.urlopen(filename)
            data = file.read()
            type = file.info().gettype()

            if filename.startswith("file://"):
                type = str(mime.get_type(filename))

            if filename.startswith("http:") or filename.startswith("https:"):
                full_cache_path = get_cache_filename(filename, size)
                cache_fileobj = open(full_cache_path, "w")
                cache_fileobj.write(data)
                cache_fileobj.close()
                meta_fileobj = open(full_cache_path + "m", "w")
                meta_fileobj.write(type + "\n")
                meta_fileobj.close()

            if type == "image/svg+xml" or filename.lower().endswith(".svg"):
                svg = rsvg.Handle()
                try:
                    if not svg.write(data):
                        raise Exception("Failed to load SVG")
                    svg_size = svg.get_dimension_data()[2:4]
                    if size == None:
                        size = svg_size
                    surface = cairo.ImageSurface(
                        cairo.FORMAT_ARGB32,
                        int(size[0]) if not isinstance(size, int) else size,
                        int(size[1]) if not isinstance(size, int) else size)
                    context = cairo.Context(surface)
                    if size != svg_size:
                        scale = get_scale(size, svg_size)
                        context.scale(scale, scale)
                    svg.render_cairo(context)
                    surface.flush()
                    return surface
                finally:
                    svg.close()
            else:
                if type == "text/plain":
                    if filename.startswith("file://"):
                        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename[7:])
                        return pixbuf_to_surface(pixbuf, size)
                    raise Exception("Could not determine type")
                else:
                    pbl = GdkPixbuf.Pixbuf.loader_new_with_mime_type(type)
                    pbl.write(data)
                    pixbuf = pbl.get_pixbuf()
                    pbl.close()
                    return pixbuf_to_surface(pixbuf, size)
            return None
        except Exception as e:
            logger.warning("Failed to get image %s (%s).",
                           filename,
                           type,
                           exc_info=e)
            return None
    else:
        if os.path.exists(filename):
            try:
                if filename.lower().endswith(".svg"):
                    if os.path.islink(filename):
                        filename = os.path.realpath(filename)
                    return load_svg_as_surface(filename, size)
                else:
                    return pixbuf_to_surface(
                        GdkPixbuf.Pixbuf.new_from_file(filename), size)

            except Exception as e:
                logger.warning("Failed to get image %s (%s).",
                               filename,
                               type,
                               exc_info=e)
                return None
Exemplo n.º 26
0
 def __init__(self):
     super().__init__()
     self.handle = Rsvg.Handle()