From 51328138af9b949cc67806dd2131d94f715ccfd5 Mon Sep 17 00:00:00 2001 From: Tj Holowaychuk Date: Mon, 8 Nov 2010 16:32:16 -0800 Subject: [PATCH] Implemented sync toBuffer() --- src/Canvas.cc | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/src/Canvas.cc b/src/Canvas.cc index 88249ac..e9580af 100644 --- a/src/Canvas.cc +++ b/src/Canvas.cc @@ -19,6 +19,8 @@ using namespace node; typedef struct { Handle fn; + unsigned len; + uint8_t *data; } closure_t; /* @@ -103,9 +105,51 @@ Canvas::SetHeight(Local prop, Local val, const AccessorInfo &info } } +/* + * Canvas::ToBuffer callback. + */ + +static cairo_status_t +toBuffer(void *c, const uint8_t *data, unsigned len) { + closure_t *closure = (closure_t *) c; + // TODO: mem handling + if (closure->len) { + closure->data = (uint8_t *) realloc(closure->data, closure->len + len); + memcpy(closure->data + closure->len, data, len); + closure->len += len; + } else { + closure->data = (uint8_t *) malloc(len); + memcpy(closure->data, data, len); + closure->len += len; + } + return CAIRO_STATUS_SUCCESS; +} + Handle Canvas::ToBuffer(const Arguments &args) { HandleScope scope; + + // Async + if (args[0]->IsFunction()) { + + } else { + Canvas *canvas = ObjectWrap::Unwrap(args.This()); + closure_t closure; + closure.len = 0; + + TryCatch try_catch; + cairo_status_t status = cairo_surface_write_to_png_stream(canvas->getSurface(), toBuffer, &closure); + + if (try_catch.HasCaught()) { + return try_catch.ReThrow(); + } else if (status) { + return ThrowException(Canvas::Error(status)); + } else { + Buffer *buf = Buffer::New(closure.len); + memcpy(buf->data(), closure.data, closure.len); + return buf->handle_; + } + } return Undefined(); } @@ -115,7 +159,7 @@ Canvas::ToBuffer(const Arguments &args) { */ static cairo_status_t -writeToBuffer(void *c, const uint8_t *data, unsigned len) { +streamPNG(void *c, const uint8_t *data, unsigned len) { closure_t *closure = (closure_t *) c; Buffer *buf = Buffer::New(len); #if NODE_VERSION_AT_LEAST(0,3,0) @@ -144,7 +188,7 @@ Canvas::StreamPNGSync(const Arguments &args) { closure.fn = Handle::Cast(args[0]); TryCatch try_catch; - cairo_status_t status = cairo_surface_write_to_png_stream(canvas->getSurface(), writeToBuffer, &closure); + cairo_status_t status = cairo_surface_write_to_png_stream(canvas->getSurface(), streamPNG, &closure); if (try_catch.HasCaught()) { return try_catch.ReThrow();