Copy the background image from the UFO Glyph to the GSLayer.
172654
def to_glyphs_background_image(self, ufo_glyph, layer):
    """"""
    ufo_image = ufo_glyph.image
    if ufo_image.fileName is None:
        return
    image = self.glyphs_module.GSBackgroundImage()
    image.path = ufo_image.fileName
    image.transform = Transform(*ufo_image.transformation)
    if CROP_KEY in ufo_glyph.lib:
        x, y, w, h = ufo_glyph.lib[CROP_KEY]
        image.crop = Rect(Point(x, y), Size(w, h))
    if LOCKED_KEY in ufo_glyph.lib:
        image.locked = ufo_glyph.lib[LOCKED_KEY]
    if ALPHA_KEY in ufo_glyph.lib:
        image.alpha = ufo_glyph.lib[ALPHA_KEY]
    layer.backgroundImage = image
1131111
def frompil(self, pillow_image):
        """"""
        bio = BytesIO()
        pillow_image.save(bio, format='png', compress_level=1)
        py_buffer = bio.getbuffer()
        c_buffer = ffi.from_buffer(py_buffer)
        with _LeptonicaErrorTrap():
            pix = Pix(lept.pixReadMem(c_buffer, len(c_buffer)))
            return pix
641205
def _tile_image(self, data):
        
        image = Image.open(BytesIO(data))
        return image.convert('RGBA')
1295226
def apply_texture(self, image):
        """"""
        self.image = image.convert_alpha()
        self.untransformed_image = self.image.copy()
##        self.rect.x = 0
##        self.rect.y = 0
##        self.rect.width = self.image.get_width()
##        self.rect.height = self.image.get_height()
        self.source.x = 0
        self.source.y = 0
        self.source.width = self.image.get_width()
        self.source.height = self.image.get_height()
        center = Vector2(self.source.width / 2.0,
                         self.source.height / 2.0)
        self.set_origin(center)
967510
def to_glyphs_glyph_anchors(self, ufo_glyph, layer):
    """"""
    for ufo_anchor in ufo_glyph.anchors:
        anchor = self.glyphs_module.GSAnchor()
        anchor.name = ufo_anchor.name
        anchor.position = Point(ufo_anchor.x, ufo_anchor.y)
        layer.anchors.append(anchor)
447737
function(sliceCode,data){
    	console.log(_outSpritePath);
        var _slice;
        for(var key in sliceCode){
            _slice = sliceCode[key];
            var _code = "background-image: url(.";
                _code += _outSpritePath.slice(_outSpritePath.lastIndexOf("/"),_outSpritePath.length);
                _code += "/";
                _code += _outSpriteName;
                _code += ");";
                _code += "background-position: -";
                _code += _slice.x;
                _code += "px -";
                _code += _slice.y;
                _code += "px;";
            data = data.replace(_slice.code,_code);
        }
        return data;
    }
1032856
def background_fill=(color)
      warn 'background_fill= has no effect in nested RVG objects' if @nested
      if !color.is_a?(Magick::Pixel)
        begin
          @background_fill = Magick::Pixel.from_color(color)
        rescue Magick::ImageMagickError
          raise ArgumentError, "unknown color `#{color}'"
        rescue TypeError
          raise TypeError, "cannot convert #{color.class} into Pixel"
        rescue StandardError
          raise ArgumentError, "argument must be a color name or a Pixel (got #{color.class})"
        end
      else
        @background_fill = color
      end
    end
582407
def to_ufo_components(self, ufo_glyph, layer):
    """"""
    pen = ufo_glyph.getPointPen()

    for index, component in enumerate(layer.components):
        pen.addComponent(component.name, component.transform)

        if component.anchor:
            if COMPONENT_INFO_KEY not in ufo_glyph.lib:
                ufo_glyph.lib[COMPONENT_INFO_KEY] = []
            ufo_glyph.lib[COMPONENT_INFO_KEY].append(
                {"name": component.name, "index": index, "anchor": component.anchor}
            )

    # data related to components stored in lists of booleans
    # each list's elements correspond to the components in order
    for key in ["alignment", "locked", "smartComponentValues"]:
        values = [getattr(c, key) for c in layer.components]
        if any(values):
            ufo_glyph.lib[_lib_key(key)] = values
858434
def generate_background
      background = MiniMagick::Image.open(fetch_config['background'])

      if background.height != screenshot.size[1]
        background.resize("#{screenshot.size[0]}x#{screenshot.size[1]}^") # `^` says it should fill area
        background.merge!(["-gravity", "center", "-crop", "#{screenshot.size[0]}x#{screenshot.size[1]}+0+0"]) # crop from center
      end
      background
    end
1282885
def to_ufo_glyph(self, ufo_glyph, layer, glyph):
    """"""
    ufo_glyph.unicodes = [int(uval, 16) for uval in glyph.unicodes]

    note = glyph.note
    if note is not None:
        ufo_glyph.note = note

    last_change = glyph.lastChange
    if last_change is not None:
        ufo_glyph.lib[GLYPHLIB_PREFIX + "lastChange"] = to_ufo_time(last_change)

    color_index = glyph.color
    if color_index is not None:
        # .3f is enough precision to round-trip uint8 to float losslessly.
        # https://github.com/unified-font-object/ufo-spec/issues/61
        # #issuecomment-389759127
        if (
            isinstance(color_index, list)
            and len(color_index) == 4
            and all(0 <= v < 256 for v in color_index)
        ):
            ufo_glyph.markColor = ",".join(
                "{:.3f}".format(v / 255) for v in color_index
            )
        elif isinstance(color_index, int) and color_index in range(len(GLYPHS_COLORS)):
            ufo_glyph.markColor = GLYPHS_COLORS[color_index]
        else:
            logger.warning(
                "Glyph {}, layer {}: Invalid color index/tuple {}".format(
                    glyph.name, layer.name, color_index
                )
            )

    export = glyph.export
    if not export:
        if "public.skipExportGlyphs" not in self._designspace.lib:
            self._designspace.lib["public.skipExportGlyphs"] = []
        self._designspace.lib["public.skipExportGlyphs"].append(glyph.name)

    # FIXME: (jany) next line should be an API of GSGlyph?
    glyphinfo = glyphsLib.glyphdata.get_glyph(ufo_glyph.name)
    production_name = glyph.production or glyphinfo.production_name
    if production_name != ufo_glyph.name:
        postscriptNamesKey = PUBLIC_PREFIX + "postscriptNames"
        if postscriptNamesKey not in ufo_glyph.font.lib:
            ufo_glyph.font.lib[postscriptNamesKey] = dict()
        ufo_glyph.font.lib[postscriptNamesKey][ufo_glyph.name] = production_name

    for key in ["leftMetricsKey", "rightMetricsKey", "widthMetricsKey"]:
        value = getattr(layer, key, None)
        if value:
            ufo_glyph.lib[GLYPHLIB_PREFIX + "layer." + key] = value
        value = getattr(glyph, key, None)
        if value:
            ufo_glyph.lib[GLYPHLIB_PREFIX + "glyph." + key] = value

    if glyph.script is not None:
        ufo_glyph.lib[SCRIPT_LIB_KEY] = glyph.script

    # if glyph contains custom 'category' and 'subCategory' overrides, store
    # them in the UFO glyph's lib
    category = glyph.category
    if category is None:
        category = glyphinfo.category
    else:
        ufo_glyph.lib[GLYPHLIB_PREFIX + "category"] = category
    subCategory = glyph.subCategory
    if subCategory is None:
        subCategory = glyphinfo.subCategory
    else:
        ufo_glyph.lib[GLYPHLIB_PREFIX + "subCategory"] = subCategory

    # load width before background, which is loaded with lib data
    width = layer.width
    if width is None:
        pass
    elif category == "Mark" and subCategory == "Nonspacing" and width > 0:
        # zero the width of Nonspacing Marks like Glyphs.app does on export
        # TODO: (jany) check for customParameter DisableAllAutomaticBehaviour
        # FIXME: (jany) also don't do that when rt UFO -> glyphs -> UFO
        ufo_glyph.lib[ORIGINAL_WIDTH_KEY] = width
        ufo_glyph.width = 0
    else:
        ufo_glyph.width = width

    self.to_ufo_background_image(ufo_glyph, layer)
    self.to_ufo_guidelines(ufo_glyph, layer)
    self.to_ufo_glyph_background(ufo_glyph, layer)
    self.to_ufo_annotations(ufo_glyph, layer)
    self.to_ufo_hints(ufo_glyph, layer)
    self.to_ufo_glyph_user_data(ufo_glyph.font, glyph)
    self.to_ufo_layer_user_data(ufo_glyph, layer)
    self.to_ufo_smart_component_axes(ufo_glyph, glyph)

    self.to_ufo_paths(ufo_glyph, layer)
    self.to_ufo_components(ufo_glyph, layer)
    self.to_ufo_glyph_anchors(ufo_glyph, layer.anchors)
1238510
def to_image(options = {})
      options = {
          tileable: false,
      }.merge! options

      # Create a new Image from the flipped pixel data.
      stub = ImageStub.new to_blob, width, height
      if defined? TexPlay
        Gosu::Image.new $window, stub, options[:tileable], options
      else
        Gosu::Image.new $window, stub, options[:tileable]
      end
    end
1097565
def apply(self, resource):
        
        if not isinstance(resource, Image.Image):
            raise ValueError('Unknown resource format')

        resource_format = resource.format
        if resource.mode != 'RGBA':  # pragma: no cover
            resource = resource.convert('RGBA')

        layer = Image.new('RGBA', resource.size, (0, 0, 0, 0))
        image, left, upper = getattr(self, '_' + self.position + '_position')(resource)
        layer.paste(image, (left, upper))

        image = Image.composite(layer, resource, layer)
        image.format = resource_format

        return image
519991
def ufo2glyphs(options):
    """"""
    import fontTools.designspaceLib
    import defcon

    sources = options.designspace_file_or_UFOs
    designspace_file = None
    if (
        len(sources) == 1
        and sources[0].endswith(".designspace")
        and os.path.isfile(sources[0])
    ):
        designspace_file = sources[0]
        designspace = fontTools.designspaceLib.DesignSpaceDocument()
        designspace.read(designspace_file)
        object_to_read = designspace
    elif all(source.endswith(".ufo") and os.path.isdir(source) for source in sources):
        ufos = [defcon.Font(source) for source in sources]
        ufos.sort(
            key=lambda ufo: [  # Order the masters by weight and width
                ufo.info.openTypeOS2WeightClass or 400,
                ufo.info.openTypeOS2WidthClass or 5,
            ]
        )
        object_to_read = ufos
    else:
        print(
            "Please specify just one designspace file *or* one or more "
            "UFOs. They must end in '.designspace' or '.ufo', respectively.",
            file=sys.stderr,
        )
        return 1

    font = glyphsLib.to_glyphs(
        object_to_read, minimize_ufo_diffs=options.no_preserve_glyphsapp_metadata
    )

    # Make the Glyphs file more suitable for roundtrip:
    font.customParameters["Disable Last Change"] = options.enable_last_change
    font.disablesAutomaticAlignment = options.enable_automatic_alignment

    if options.output_path:
        font.save(options.output_path)
    else:
        if designspace_file:
            filename_to_write = os.path.splitext(designspace_file)[0] + ".glyphs"
        else:
            filename_to_write = os.path.join(
                os.path.dirname(sources[0]),
                font.familyName.replace(" ", "") + ".glyphs",
            )
        font.save(filename_to_write)
321866
function(g, options) {
        var compositeOperation = options.compositeOperation
                || options.composition || 'source-over';
        g.globalCompositeOperation = compositeOperation;// 
        g.fillStyle = options.fillColor || options.color;
        if (options.fillImage) {
            g.fillStyle = g.createPattern(options.fillImage, "repeat");
        }
        g.globalAlpha = options.fillOpacity || options.opacity || 0;
    }
613981
def _prepare_base_image(self):
        
        if not self.base_image:
            return defer.succeed(True)

        if self.cheap_copy:
            clone_cmd = "qemu-img"
            clone_args = "create -b %(base)s -f qcow2 %(image)s"
        else:
            clone_cmd = "cp"
            clone_args = "%(base)s %(image)s"

        clone_args = clone_args % {
            "base": self.base_image,
            "image": self.image,
        }

        log.msg("Cloning base image: %s %s'" % (clone_cmd, clone_args))

        d = utils.getProcessValue(clone_cmd, clone_args.split())

        def _log_result(res):
            log.msg("Cloning exit code was: %d" % res)
            return res

        def _log_error(err):
            log.err("Cloning failed: %s" % err)
            return err

        d.addCallbacks(_log_result, _log_error)

        return d
1199146
def font(self):
        """"""
        if self._font is not None:
            return self._font

        # Sort UFOS in the original order from the Glyphs file
        sorted_sources = self.to_glyphs_ordered_masters()

        # Convert all full source UFOs to Glyphs masters. Sources with layer names
        # are assumed to be sparse or "brace" layers and are ignored because Glyphs
        # considers them to be special layers and will handle them itself.
        self._font = self.glyphs_module.GSFont()
        self._sources = OrderedDict()  # Same as in UFOBuilder
        for index, source in enumerate(s for s in sorted_sources if not s.layerName):
            master = self.glyphs_module.GSFontMaster()

            # Filter bracket glyphs out of public.glyphOrder.
            if GLYPH_ORDER_KEY in source.font.lib:
                source.font.lib[GLYPH_ORDER_KEY] = [
                    glyph_name
                    for glyph_name in source.font.lib[GLYPH_ORDER_KEY]
                    if ".BRACKET." not in glyph_name
                ]

            self.to_glyphs_font_attributes(source, master, is_initial=(index == 0))
            self.to_glyphs_master_attributes(source, master)
            self._font.masters.insert(len(self._font.masters), master)
            self._sources[master.id] = source

            # First, move free-standing bracket glyphs back to layers to avoid dealing
            # with GSLayer transplantation.
            for bracket_glyph in [g for g in source.font if ".BRACKET." in g.name]:
                base_glyph, threshold = bracket_glyph.name.split(".BRACKET.")
                try:
                    int(threshold)
                except ValueError:
                    raise ValueError(
                        "Glyph '{}' has malformed bracket layer name. Must be '<glyph "
                        "name>.BRACKET.<crossover value>'.".format(bracket_glyph)
                    )
                layer_name = bracket_glyph.lib.get(
                    GLYPHLIB_PREFIX + "_originalLayerName", "[{}]".format(threshold)
                )
                if layer_name not in source.font.layers:
                    ufo_layer = source.font.newLayer(layer_name)
                else:
                    ufo_layer = source.font.layers[layer_name]
                bracket_glyph_new = ufo_layer.newGlyph(base_glyph)
                bracket_glyph_new.copyDataFromGlyph(bracket_glyph)

                # Remove all freestanding bracket layer glyphs from all layers.
                for layer in source.font.layers:
                    if bracket_glyph.name in layer:
                        del layer[bracket_glyph.name]

            for layer in _sorted_backgrounds_last(source.font.layers):
                self.to_glyphs_layer_lib(layer)
                for glyph in layer:
                    self.to_glyphs_glyph(glyph, layer, master)

        self.to_glyphs_features()
        self.to_glyphs_groups()
        self.to_glyphs_kerning()

        # Now that all GSGlyph are built, restore the glyph order
        if self.designspace.sources:
            first_ufo = self.designspace.sources[0].font
            if GLYPH_ORDER_KEY in first_ufo.lib:
                glyph_order = first_ufo.lib[GLYPH_ORDER_KEY]
                lookup = {name: i for i, name in enumerate(glyph_order)}
                self.font.glyphs = sorted(
                    self.font.glyphs, key=lambda glyph: lookup.get(glyph.name, 1 << 63)
                )
            # FIXME: (jany) We only do that on the first one. Maybe we should
            # merge the various `public.glyphorder` values?

            # Restore the layer ordering in each glyph
            for glyph in self._font.glyphs:
                self.to_glyphs_layer_order(glyph)

        self.to_glyphs_family_user_data_from_designspace()
        self.to_glyphs_axes()
        self.to_glyphs_sources()
        self.to_glyphs_instances()

        return self._font
1322098
def _deep_copy_contours(self, ufo, parent, component, transformation):
        """"""

        for nested in component.components:
            self._deep_copy_contours(
                ufo,
                parent,
                ufo[nested.baseGlyph],
                transformation.transform(nested.transformation),
            )

        if component != parent:
            pen = TransformPen(parent.getPen(), transformation)

            # if the transformation has a negative determinant, it will reverse
            # the contour direction of the component
            xx, xy, yx, yy = transformation[:4]
            if xx * yy - xy * yx < 0:
                pen = ReverseContourPen(pen)

            component.draw(pen)