Skip to content

Commit

Permalink
Add cairo.Surface.WriteToPNGWriter
Browse files Browse the repository at this point in the history
  • Loading branch information
diamondburned committed Oct 19, 2021
1 parent 9653677 commit d2e12b4
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions pkg/cairo/surface.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ package cairo
// #include <cairo.h>
// #include <cairo-gobject.h>
// #include <cairo-pdf.h>
// cairo_status_t _gotk4_cairo_write_func(void*, unsigned char*, unsigned int);
import "C"

import (
"io"
"runtime"
"unsafe"

"github.com/diamondburned/gotk4/pkg/core/gbox"
)

/*
Expand Down Expand Up @@ -275,6 +279,46 @@ func (v *Surface) WriteToPNG(fileName string) error {
return nil
}

type writerBox struct {
w io.Writer
}

//export _gotk4_cairo_write_func
func _gotk4_cairo_write_func(userdata unsafe.Pointer, data *C.uchar, len C.uint) C.cairo_status_t {
wb, ok := gbox.Get(uintptr(unsafe.Pointer(userdata))).(writerBox)
if !ok {
return C.CAIRO_STATUS_WRITE_ERROR
}

bytes := unsafe.Slice((*byte)(unsafe.Pointer(data)), uint(len))

_, err := wb.w.Write(bytes)
if err != nil {
return C.CAIRO_STATUS_WRITE_ERROR
}

return C.CAIRO_STATUS_SUCCESS
}

// WriteToPNGWriter is a wrapper around cairo_surface_write_png_stream(). It
// writes the Cairo surface to the given io.Writer in PNG format.
func (v *Surface) WriteToPNGWriter(w io.Writer) error {
dataptr := gbox.Assign(writerBox{w})
defer gbox.Delete(dataptr)

status := Status(C.cairo_surface_write_to_png_stream(
v.surface,
(*[0]byte)(C._gotk4_cairo_write_func),
unsafe.Pointer(dataptr),
))

if status != STATUS_SUCCESS {
return ErrorStatus(status)
}

return nil
}

// TODO(jrick) SupportsMimeType (since 1.12)
// cairo_surface_supports_mime_type

Expand Down

0 comments on commit d2e12b4

Please sign in to comment.