// // Image.cc // // Copyright (c) 2010 LearnBoost // #include "Canvas.h" #include "Image.h" #include #include #include #ifdef HAVE_JPEG #include #endif Persistent Image::constructor; /* * Initialize Image. */ void Image::Initialize(Handle target) { HandleScope scope; // Constructor constructor = Persistent::New(FunctionTemplate::New(Image::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Image")); // Prototype Local proto = constructor->PrototypeTemplate(); proto->SetAccessor(String::NewSymbol("src"), GetSrc, SetSrc); proto->SetAccessor(String::NewSymbol("complete"), GetComplete); proto->SetAccessor(String::NewSymbol("width"), GetWidth); proto->SetAccessor(String::NewSymbol("height"), GetHeight); proto->SetAccessor(String::NewSymbol("onload"), GetOnload, SetOnload); proto->SetAccessor(String::NewSymbol("onerror"), GetOnerror, SetOnerror); target->Set(String::NewSymbol("Image"), constructor->GetFunction()); } /* * Initialize a new Image. */ Handle Image::New(const Arguments &args) { HandleScope scope; Image *img = new Image; img->Wrap(args.This()); return args.This(); } /* * Get complete boolean. */ Handle Image::GetComplete(Local, const AccessorInfo &info) { HandleScope scope; Image *img = ObjectWrap::Unwrap(info.This()); return scope.Close(Boolean::New(Image::COMPLETE == img->state)); } /* * Get width. */ Handle Image::GetWidth(Local, const AccessorInfo &info) { HandleScope scope; Image *img = ObjectWrap::Unwrap(info.This()); return scope.Close(Number::New(img->width)); } /* * Get height. */ Handle Image::GetHeight(Local, const AccessorInfo &info) { HandleScope scope; Image *img = ObjectWrap::Unwrap(info.This()); return scope.Close(Number::New(img->height)); } /* * Get src path. */ Handle Image::GetSrc(Local, const AccessorInfo &info) { HandleScope scope; Image *img = ObjectWrap::Unwrap(info.This()); return scope.Close(String::New(img->filename)); } /* * Set src path. */ void Image::SetSrc(Local, Local val, const AccessorInfo &info) { HandleScope scope; if (val->IsString()) { String::AsciiValue src(val); Image *img = ObjectWrap::Unwrap(info.This()); if (img->filename) free(img->filename); img->filename = strdup(*src); TryCatch try_catch; img->load(); if (try_catch.HasCaught()) { img->error(try_catch); } else { V8::AdjustAmountOfExternalAllocatedMemory(4 * img->width * img->height); img->loaded(); } } } /* * Get onload callback. */ Handle Image::GetOnload(Local, const AccessorInfo &info) { Image *img = ObjectWrap::Unwrap(info.This()); return img->onload; } /* * Set onload callback. */ void Image::SetOnload(Local, Local val, const AccessorInfo &info) { if (val->IsFunction()) { Image *img = ObjectWrap::Unwrap(info.This()); img->onload = Persistent::New(Handle::Cast(val)); } } /* * Get onerror callback. */ Handle Image::GetOnerror(Local, const AccessorInfo &info) { Image *img = ObjectWrap::Unwrap(info.This()); return img->onerror; } /* * Set onerror callback. */ void Image::SetOnerror(Local, Local val, const AccessorInfo &info) { if (val->IsFunction()) { Image *img = ObjectWrap::Unwrap(info.This()); img->onerror = Persistent::New(Handle::Cast(val)); } } /* * Initialize a new Image. */ Image::Image() { filename = NULL; _surface = NULL; width = height = 0; state = DEFAULT; } /* * Destroy image and associated surface. */ Image::~Image() { if (_surface) { V8::AdjustAmountOfExternalAllocatedMemory(-4 * width * height); cairo_surface_destroy(_surface); } if (filename) free(filename); } /* * Initiate image loading. */ void Image::load() { if (LOADING != state) { state = LOADING; loadSurface(); } } /* * Invoke onload (when assigned) and assign dimensions. */ void Image::loaded() { HandleScope scope; state = COMPLETE; if (!onload.IsEmpty()) { TryCatch try_catch; onload->Call(Context::GetCurrent()->Global(), 0, NULL); onload.Dispose(); if (try_catch.HasCaught()) { error(try_catch); } } } /* * Invoke onerror (when assigned) with the given err. */ void Image::error(TryCatch &try_catch) { HandleScope scope; if (onerror.IsEmpty()) { FatalException(try_catch); } else { Local argv[1] = { try_catch.Exception() }; TryCatch try_catch2; onerror->Call(Context::GetCurrent()->Global(), 1, argv); onerror.Dispose(); if (try_catch2.HasCaught()) { FatalException(try_catch2); } } } /* * Load cairo surface from the image src. * * TODO: better format detection * TODO: support more formats * TODO: use node IO or at least thread pool */ void Image::loadSurface() { switch (extension(filename)) { case Image::PNG: loadPNG(); break; #ifdef HAVE_JPEG case Image::JPEG: loadJPEG(); break; #endif default: ThrowException(Exception::Error(String::New("failed to detect image format"))); } } /* * Load PNG. */ void Image::loadPNG() { _surface = cairo_image_surface_create_from_png(filename); cairo_status_t status = cairo_surface_status(_surface); if (status) { ThrowException(Canvas::Error(status)); } else { width = cairo_image_surface_get_width(_surface); height = cairo_image_surface_get_height(_surface); } } #ifdef HAVE_JPEG /* * Load JPEG, convert RGB to ARGB. */ void Image::loadJPEG() { FILE *stream = fopen(filename, "r"); // Generalized errors if (!stream) { ThrowException(ErrnoException(errno, "fopen")); } // JPEG setup struct jpeg_decompress_struct info; struct jpeg_error_mgr err; info.err = jpeg_std_error(&err); jpeg_create_decompress(&info); jpeg_stdio_src(&info, stream); jpeg_read_header(&info, 1); jpeg_start_decompress(&info); width = info.output_width; height = info.output_height; // Data alloc int stride = width * 4; uint8_t *data = (uint8_t *) malloc(width * height * 4); if (!data) { ThrowException(Canvas::Error(CAIRO_STATUS_NO_MEMORY)); return; } uint8_t *src = (uint8_t *) malloc(width * 3); if (!src) { free(data); ThrowException(Canvas::Error(CAIRO_STATUS_NO_MEMORY)); return; } // Copy RGB -> ARGB for (int y = 0; y < height; ++y) { jpeg_read_scanlines(&info, &src, 1); uint32_t *row = (uint32_t *)(data + stride * y); for (int x = 0; x < width; ++x) { int bx = 3 * x; uint32_t *pixel = row + x; *pixel = 255 << 24 | src[bx + 0] << 16 | src[bx + 1] << 8 | src[bx + 2]; } } // New image surface _surface = cairo_image_surface_create_for_data( data , CAIRO_FORMAT_ARGB32 , width , height , cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width)); // Cleanup free(src); fclose(stream); jpeg_finish_decompress(&info); jpeg_destroy_decompress(&info); cairo_status_t status = cairo_surface_status(_surface); if (status) { free(data); ThrowException(Canvas::Error(status)); } } #endif /* * Return UNKNOWN, JPEG, or PNG based on the filename. */ Image::type Image::extension(const char *filename) { size_t len = strlen(filename); filename += len; if (len >= 5 && 0 == strcmp(".jpeg", filename - 5)) return Image::JPEG; if (len >= 4 && 0 == strcmp(".jpg", filename - 4)) return Image::JPEG; if (len >= 4 && 0 == strcmp(".png", filename - 4)) return Image::PNG; return Image::UNKNOWN; }