Пример #1
0
Handle<Value> ImageView::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "image view external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        ImageView* im =  static_cast<ImageView*>(ptr);
        im->Wrap(args.This());
        return args.This();
    } else {
            return ThrowException(String::New("Cannot create this object from Javascript"));
    }
    return Undefined();
}
Пример #2
0
Handle<Value> NodeSandbox::node_new(const Arguments& args)
{
  HandleScope scope;

  if (args.IsConstructCall()) {
    SandboxWrapper* wrap = new SandboxWrapper();
    wrap->Wrap(args.This());
    wrap->nodeThis = wrap->handle_;
    node::MakeCallback (wrap->nodeThis, "_init", 0, nullptr);
    wrap->nodeThis->SetAccessor (String::NewSymbol ("debuggerOnCrash"), NodeSandbox::node_getDebugOnCrash, NodeSandbox::node_setDebugOnCrash);
    wrap->sbox->addIPC (std::unique_ptr<NodeIPC> (new NodeIPC (STDOUT_FILENO, wrap->handle_)));
    wrap->sbox->addIPC (std::unique_ptr<NodeIPC> (new NodeIPC (STDERR_FILENO, wrap->handle_)));

    return args.This();
  } else {
    Local<Value> argv[1] = { args[0] };
    return scope.Close(s_constructor->NewInstance(1, argv));
  }
}
Пример #3
0
	/* ECMAScript constructor */
	Handle<Value> Viewport::New(const Arguments& args)
	{
		HandleScope scope;

		if (!args.IsConstructCall()) {
			return ThrowException(Exception::TypeError(
				String::New("Use the new operator to create instances of this object."))
			);
		}

		// Creates a new instance object of this type and wraps it.
		Viewport* obj = new Viewport();
		obj->Wrap(args.This());

		/* Initializing sub-objects */
		Local<Object> ScrollableObject = Scrollable::New(MX_SCROLLABLE(obj->_actor));
		args.Holder()->Set(String::NewSymbol("scroll"), ScrollableObject);

		return scope.Close(args.This());
	}
Пример #4
0
Handle<Value> ItemObject::constructor(const Arguments &args)
{
	HandleScope handleScope;
	
	// Make sure the constructor is called with the new keyword
	
	if (!args.IsConstructCall())
	{
		Local<String> message = String::New("Cannot call constructor as a function");
		return ThrowException(Exception::SyntaxError(message));
	}
	
	// Instantiate a new ScriptTemplate
	
	ItemObject *itemObject = new ItemObject();
	Local<Object> itemInstance = itemObject->createInstance();
	itemInstance->SetInternalField(0, External::New(itemObject));
	
	return handleScope.Close(itemInstance);
}
Пример #5
0
Handle<Value> Palette::New(const Arguments& args) {
    HandleScope scope;

    if (!args.IsConstructCall()) {
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
    }

    std::string palette;
    rgba_palette::palette_type type = rgba_palette::PALETTE_RGBA;
    if (args.Length() >= 1) {
        if (args[0]->IsString()) {
            String::AsciiValue obj(args[0]->ToString());
            palette = std::string(*obj, obj.length());
        }
        else if (node::Buffer::HasInstance(args[0])) {
            Local<Object> obj = args[0]->ToObject();
            palette = std::string(node::Buffer::Data(obj), node::Buffer::Length(obj));
        }
    }
    if (args.Length() >= 2) {
        if (args[1]->IsString()) {
            std::string obj = *String::Utf8Value(args[1]->ToString());
            if (obj == "rgb") type = rgba_palette::PALETTE_RGB;
            else if (obj == "act") type = rgba_palette::PALETTE_ACT;
        }
    }

    if (!palette.length()) {
        return ThrowException(Exception::TypeError(
            String::New("First parameter must be a palette string")));
    }

    Palette* p = new Palette(palette, type);
    if (!p->palette()->valid()) {
        delete p;
        return ThrowException(Exception::TypeError(String::New("Invalid palette length")));
    } else {
        p->Wrap(args.This());
        return args.This();
    }
}
Пример #6
0
Handle<Value> Image::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Image* im =  static_cast<Image*>(ptr);
        im->Wrap(args.This());
        return args.This();
    }

    try
    {
        if (args.Length() == 2)
        {
            if (!args[0]->IsNumber() || !args[1]->IsNumber())
                return ThrowException(Exception::Error(
                                          String::New("Image 'width' and 'height' must be a integers")));
            Image* im = new Image(args[0]->IntegerValue(),args[1]->IntegerValue());
            im->Wrap(args.This());
            return args.This();
        }
        else
        {
            return ThrowException(Exception::Error(
                                      String::New("please provide Image width and height")));
        }
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
    return Undefined();
}
Handle<Value> MSOutputFormat::New(const Arguments &args) {
  HandleScope scope;
  MSOutputFormat *obj;
  
  if (!args.IsConstructCall()) {
    return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
  }

  if (args[0]->IsExternal()) {
    Local<External> ext = Local<External>::Cast(args[0]);
    void* ptr = ext->Value();
    obj = static_cast<MSOutputFormat*>(ptr);
    obj->Wrap(args.This());
    return args.This();
  }
  
  REQ_STR_ARG(0, driver);
  REQ_STR_ARG(1, name);
  
  outputFormatObj *format = msCreateDefaultOutputFormat(NULL, *driver, *name);

  /* in the case of unsupported formats, msCreateDefaultOutputFormat
     should return NULL */
  if (!format) {
    msSetError(MS_MISCERR, "Unsupported format driver: %s",
               "outputFormatObj()", *driver);
    return args.This();
  }

  msInitializeRendererVTable(format);

  /* Else, continue */
  format->refcount++;
  format->inmapfile = MS_TRUE;
  
  obj = new MSOutputFormat(format);
  obj->Wrap(args.This());
  return args.This();
}
Пример #8
0
Handle<Value> Tail::New(const Arguments& args) {
	HandleScope scope;
	
    assert(args.IsConstructCall());
    
    Tail* tail_instance = new Tail();
	tail_instance->Wrap(args.This());
    
    
	if (!args[0]->IsString())
		return ThrowException(Exception::TypeError(String::New("Argument 1 must be a String")));
	
    if (!args[1]->IsString())
		tail_instance->separator = "\n";
    else {
        String::Utf8Value v8separator(args[1]->ToString());
        tail_instance->separator = std::string(*v8separator, v8separator.length());
    }
    
	String::Utf8Value filename(args[0]);
    
    ifstream fp(*filename, ios::binary);
    fp.seekg(0, ios::end);
    tail_instance->last_position = fp.tellg();
    fp.close();
    
    tail_instance->_event_handle.data = reinterpret_cast<void*>(tail_instance);
    tail_instance->Ref();

    int r = uv_fs_event_init(uv_default_loop(), &tail_instance->_event_handle, *filename, OnEvent, 0);
    
    if (r == 0){
        tail_instance->ontail = false;
    } else
        node::SetErrno(uv_last_error(uv_default_loop()));
    
	return args.This();
}
Пример #9
0
// Create a context (new op)
Handle<Value> GNContext::New(const Arguments& args) {
    HandleScope scope;
    if (args.IsConstructCall()) {
        // new obj
        GNContext* ctx = new GNContext();
        getdns_return_t r = getdns_context_create(&ctx->context_, 1);
        if (r != GETDNS_RETURN_GOOD) {
            // Failed to create an underlying context
            delete ctx;
            ThrowException(Exception::Error(String::New("Unable to create GNContext.")));
        }
        // Apply options if needed
        if (args.Length() > 0) {
            // could throw an
            TryCatch try_catch;
            ctx->applyOptions(args[0]);
            if (try_catch.HasCaught()) {
                // Need to bail
                delete ctx;
                try_catch.ReThrow();
                return scope.Close(Undefined());
            }
        }
        // Attach the context to node
        bool attached = GNUtil::attachContextToNode(ctx->context_);
        if (!attached) {
            // Bail
            delete ctx;
            ThrowException(Exception::Error(String::New("Unable to attach to Node.")));
            return scope.Close(Undefined());
        }
        ctx->Wrap(args.This());
        return args.This();
    } else {
        ThrowException(Exception::Error(String::New("Must use new.")));
    }
    return scope.Close(Undefined());
}
Пример #10
0
Handle<Value> Projection::New(const Arguments& args)
{
  HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

  if (!args.Length() > 0 || !args[0]->IsString()) {
      return ThrowException(Exception::TypeError(
        String::New("please provide a proj4 intialization string")));
  }
  try
  {
      Projection* p = new Projection(TOSTR(args[0]));
      p->Wrap(args.This());
      return args.This();
  }
  catch (const mapnik::proj_init_error & ex )
  {
    return ThrowException(Exception::Error(
      String::New(ex.what())));
  }
}
Пример #11
0
Handle<Value> Point::New(const Arguments& args)
{
	HandleScope scope;
	Point *f;
	OGRPoint *geom;
	double x = 0, y = 0, z = 0;

	if (!args.IsConstructCall()) {
		return NODE_THROW("Cannot call constructor as function, you need to use 'new' keyword");
	}

	if (args[0]->IsExternal()) {
		Local<External> ext = Local<External>::Cast(args[0]);
		void* ptr = ext->Value();
		f = static_cast<Point *>(ptr);

	} else {
		NODE_ARG_DOUBLE_OPT(0, "x", x);
		NODE_ARG_DOUBLE_OPT(1, "y", y);
		NODE_ARG_DOUBLE_OPT(2, "z", z);

		if (args.Length() == 1) {
			return NODE_THROW("Point constructor must be given 0, 2, or 3 arguments");
		}

		if (args.Length() == 3) {
			geom = new OGRPoint(x, y, z);
		} else {
			geom = new OGRPoint(x, y);
		}

		f = new Point(geom);
	}

	f->Wrap(args.This());
	return args.This();
}
Пример #12
0
Handle<Value> ZipFile::New(const Arguments& args) {
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
                                  String::New("first argument must be a path to a zipfile")));

    std::string input_file = TOSTR(args[0]);
    struct zip *za;
    int err;
    char errstr[1024];
    if ((za = zip_open(input_file.c_str(), 0, &err)) == NULL) {
        zip_error_to_str(errstr, sizeof(errstr), err, errno);
        std::stringstream s;
        s << "cannot open file: " << input_file << " error: " << errstr << "\n";
        return ThrowException(Exception::Error(
                                  String::New(s.str().c_str())));
    }

    ZipFile* zf = new ZipFile(input_file);

    int num = zip_get_num_files(za);
    zf->names_.reserve(num);
    int i = 0;
    for (i = 0; i < num; i++) {
        struct zip_stat st;
        zip_stat_index(za, i, 0, &st);
        zf->names_.push_back(st.name);
    }

    zf->archive_ = za;
    zf->Wrap(args.This());
    return args.This();
}
Пример #13
0
Handle<Value> Resolver::New(const Arguments& args) {
	HandleScope scope;

	if (!args.IsConstructCall()) {
		return ThrowException(Exception::TypeError(
				String::New("Use the new operator to create instances of this object."))
		);
	}

	if (args.Length() < 2) {
		return ThrowException(Exception::TypeError(
				String::New("First argument must be a string, second a boolean")));
	}

	Resolver* obj = new Resolver();
	String::Utf8Value name(args[0]->ToString());
	obj->name_ = std::string(*name);
	obj->resolver_ = new O3SResolver(obj->name_, false);

	if (obj->resolver_) {
		while (!obj->resolver_->getDico()) {
			std::cout<<"Waiting for dico..."<<std::endl;
			Poco::Thread::sleep(1000);
		}
		obj->Wrap(args.This());

		Local<Function> cb = Local<Function>::Cast(args[2]);
		const unsigned argc = 1;
		Local<Value> argv[argc] = { args.This() };
		cb->Call(Context::GetCurrent()->Global(), argc, argv);

		return args.This();
	}

	return Undefined();
}
Пример #14
0
  Handle<Value> FingerprintWrap::NewInstance(const Arguments& args) {
    HandleScope scope;

    if (!args.IsConstructCall())
      return ThrowException(Exception::TypeError(
        String::New("Use the new operator to create instances of this object.")));

    FingerprintWrap* fp = new FingerprintWrap(
      std::string(*String::AsciiValue(args[0]->ToString())).c_str(),
      args[1]->Int32Value(),
      args[2]->Int32Value(),
      args[3]->Int32Value(),
      args[4]->Int32Value());
    fp->Wrap(args.This());

    libtorrent::fingerprint* fp_ = FingerprintWrap::Unwrap(args.This());
    args.This()->Set(String::NewSymbol("name"),             String::New( fp_->name));
    args.This()->Set(String::NewSymbol("major_version"),    Integer::New(fp_->major_version));
    args.This()->Set(String::NewSymbol("minor_version"),    Integer::New(fp_->minor_version));
    args.This()->Set(String::NewSymbol("revision_version"), Integer::New(fp_->revision_version));
    args.This()->Set(String::NewSymbol("tag_version"),      Integer::New(fp_->tag_version));

    return scope.Close(args.This());
  };
Пример #15
0
Handle<Value> Nodehun::SpellDictionary::New(const Arguments& args) {
  HandleScope scope;
  int argl = args.Length();
  if (!args.IsConstructCall())
    return ThrowException(Exception::TypeError(String::New("Use the new operator to create instances of this object.")));
  if(argl < 1 || !args[0]->IsString())
    return ThrowException(Exception::TypeError(String::New("First argument must be a string.")));

  String::Utf8Value arg0(args[0]->ToString());
  Nodehun::SpellDictionary * obj;
  if(argl == 1 || argl > 1 && !args[1]->IsString()){    
    obj = new Nodehun::SpellDictionary(*arg0);
    if(!obj->pathsExist)
      return ThrowException(Exception::TypeError(String::New("No such dictionary exists.")));
  }
  else {
    String::Utf8Value arg1(args[1]->ToString());
    obj = new Nodehun::SpellDictionary(*arg0,*arg1);
    if(!obj->pathsExist)
      return ThrowException(Exception::TypeError(String::New("There was an error compiling either the affix or dictionary file you passed. Perhaps one or both of them is invalid.")));
  }
  obj->Wrap(args.This());  
  return args.This();
}
Пример #16
0
Handle<Value> Datasource::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Datasource* d =  static_cast<Datasource*>(ptr);
        if (d->datasource_->type() == mapnik::datasource::Raster)
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("raster"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        else
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("vector"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        d->Wrap(args.This());
        return args.This();
    }
    if (args.Length() != 1){
        return ThrowException(Exception::TypeError(
                                  String::New("accepts only one argument, an object of key:value datasource options")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
                                  String::New("Must provide an object, eg {type: 'shape', file : 'world.shp'}")));

    Local<Object> options = args[0]->ToObject();

    mapnik::parameters params;
    Local<Array> names = options->GetPropertyNames();
    unsigned int i = 0;
    unsigned int a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        // TODO - don't treat everything as strings
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {
#if MAPNIK_VERSION >= 200200
        ds = mapnik::datasource_cache::instance().create(params);
#else
        ds = mapnik::datasource_cache::instance()->create(params);
#endif
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }

    if (ds)
    {
        if (ds->type() == mapnik::datasource::Raster)
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("raster"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        else
        {
            args.This()->Set(String::NewSymbol("type"),
                             String::NewSymbol("vector"),
                             static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete));
        }
        Datasource* d = new Datasource();
        d->Wrap(args.This());
        d->datasource_ = ds;
        return args.This();
    }
    return Undefined();
}
Пример #17
0
Handle<Value> JSDatasource::New(const Arguments& args)
{
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        JSDatasource* d =  static_cast<JSDatasource*>(ptr);
        d->Wrap(args.This());
        return args.This();
    }
    
    if (!args.Length() == 2){
        return ThrowException(Exception::TypeError(
          String::New("two argument required: an object of key:value datasource options and a callback function for features")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
          String::New("Must provide an object, eg {extent: '-180,-90,180,90'}")));

    Local<Object> options = args[0]->ToObject();

    // function callback
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                  String::New("last argument must be a callback function")));

    // TODO - maybe validate in js?

    bool bind=true;
    if (options->Has(String::New("bind")))
    {
        Local<Value> bind_opt = options->Get(String::New("bind"));
        if (!bind_opt->IsBoolean())
          return ThrowException(Exception::TypeError(
            String::New("'bind' must be a Boolean")));

        bind = bind_opt->BooleanValue();
    }

    mapnik::parameters params;
    params["type"] = "js";
    Local<Array> names = options->GetPropertyNames();
    uint32_t i = 0;
    uint32_t a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {

        ds = mapnik::datasource_ptr(new js_datasource(params,bind,args[args.Length()-1]));
        
    }
    catch (const std::exception & ex)
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
          String::New("unknown exception happened, please file bug")));
    }
    if (ds)
    {
        JSDatasource* d = new JSDatasource();
        d->Wrap(args.This());
        d->ds_ptr_ = ds;
        return args.This();
    }

    return Undefined();
}
Пример #18
0
Handle<Value> Query::New(Arguments const& args)
{
    HandleScope scope;
    if (!args.IsConstructCall()) {
        return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword")));
    }
    try {
        if (args.Length() != 1) {
            return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument")));
        }
        if (!args[0]->IsObject()) {
            return ThrowException(Exception::TypeError(String::New("first argument must be an object")));
        }
        Local<Object> obj = args[0]->ToObject();
        if (obj->IsNull() || obj->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("first arg must be an object")));
        }
        if (!obj->Has(String::New("coordinates"))) {
            return ThrowException(Exception::TypeError(String::New("must provide a coordinates property")));
        }
        Local<Value> coordinates = obj->Get(String::New("coordinates"));
        if (!coordinates->IsArray()) {
            return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
        }

        // Handle scenario in which caller explicitly specified service
        std::string service;
        if (obj->Has(String::New("service"))) {
            Local<Value> serviceValue = obj->Get(String::New("service"));
            v8::String::Utf8Value serviceUtf8Value(serviceValue->ToString());
            service = std::string(*serviceUtf8Value);
        }

        // Handle 'nearest', otherwise assume 'viaroute' service.
        if (service == "nearest" || service == "locate") {
            Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
            if (coordinates_array->Length() != 1) {
                return ThrowException(Exception::TypeError(String::New("coordinates array should only have one lat/long pair for 'nearest' or 'locate' queries")));
            }
            Local<Value> coordinate = coordinates_array->Get(0);
            if (!coordinate->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
            if (coordinate_array->Length() != 2) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }

            Query* q = new Query();
            q->this_->service = service;
            q->this_->coordinates.push_back(
                FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
                                     coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));

            q->Wrap(args.This());
            return args.This();
        }


        Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
        if (coordinates_array->Length() < 2) {
            return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided")));
        }

        Query* q = new Query();
        q->this_->zoomLevel = 18; //no generalization
        q->this_->printInstructions = false; //turn by turn instructions
        q->this_->alternateRoute = true; //get an alternate route, too
        q->this_->geometry = true; //retrieve geometry of route
        q->this_->compression = true; //polyline encoding
        q->this_->checkSum = UINT_MAX; //see wiki
        q->this_->service = "viaroute"; //that's routing
        q->this_->outputFormat = "json";
        q->this_->jsonpParameter = ""; //set for jsonp wrapping
        q->this_->language = ""; //unused atm

        if (obj->Has(String::New("alternateRoute"))) {
            q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue();
        }

        if (obj->Has(String::New("checksum"))) {
            q->this_->checkSum = static_cast<unsigned>(obj->Get(String::New("checksum"))->Uint32Value());
        }

        if (obj->Has(String::New("zoomLevel"))) {
            q->this_->zoomLevel = static_cast<short>(obj->Get(String::New("zoomLevel"))->Int32Value());
        }

        if (obj->Has(String::New("printInstructions"))) {
            q->this_->printInstructions = obj->Get(String::New("printInstructions"))->BooleanValue();
        }

        if (obj->Has(String::New("jsonpParameter"))) {
            q->this_->jsonpParameter = *v8::String::Utf8Value(obj->Get(String::New("jsonpParameter")));
        }

        if (obj->Has(String::New("hints"))) {
            Local<Value> hints = obj->Get(String::New("hints"));
            if (!hints->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("hints must be an array of strings/null")));
            }
            Local<Array> hints_array = Local<Array>::Cast(hints);
            for (uint32_t i = 0; i < hints_array->Length(); ++i) {
                Local<Value> hint = hints_array->Get(i);
                if (hint->IsString()) {
                    q->this_->hints.push_back(*v8::String::Utf8Value(hint));
                } else if(hint->IsNull()){
                    q->this_->hints.push_back("");
                }else{
                    return ThrowException(Exception::TypeError(String::New("hint must be null or string")));
                }
            }
        }

        for (uint32_t i = 0; i < coordinates_array->Length(); ++i) {
            Local<Value> coordinate = coordinates_array->Get(i);
            if (!coordinate->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
            if (coordinate_array->Length() != 2) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            q->this_->coordinates.push_back(
                FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
                                     coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));
        }

        q->Wrap(args.This());
        return args.This();
    } catch (std::exception const& ex) {
        return ThrowException(Exception::TypeError(String::New(ex.what())));
    }
    return Undefined();
}
Пример #19
0
Handle<Value> MSRect::New(const Arguments &args) {
  HandleScope scope;
  MSRect *obj;
  double t;

  if (!args.IsConstructCall()) {
    return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
  }

  if (args[0]->IsExternal()) {
    Local<External> ext = Local<External>::Cast(args[0]);
    void* ptr = ext->Value();
    obj = static_cast<MSRect*>(ptr);
    obj->Wrap(args.This());
    return args.This();
  }

  rectObj *rect = (rectObj *)calloc(1, sizeof(rectObj));
  if(!rect) {
    return args.This();
  }

  if (args.Length() == 0) {
    rect->minx = -1;
    rect->miny = -1;
    rect->maxx = -1;
    rect->maxy = -1;
  } else if (args.Length() == 1) {
    Local<Object> argObj;
    if (!args[0]->IsObject()) {
      THROW_ERROR(TypeError, "single argument constructor requires a Rect object");
    }

    argObj = args[0]->ToObject();

    if (argObj->IsNull() || argObj->IsUndefined() || !MSRect::constructor->HasInstance(argObj)) {
      THROW_ERROR(TypeError, "single argument to Rect constructor must be a Rect object");
    }

    MSRect *inRect = ObjectWrap::Unwrap<MSRect>(argObj);

    memcpy(rect, inRect->this_, sizeof(rectObj));

  } else if (args.Length() == 4) {
    REQ_DOUBLE_ARG(0, minx);
    REQ_DOUBLE_ARG(1, miny);
    REQ_DOUBLE_ARG(2, maxx);
    REQ_DOUBLE_ARG(3, maxy);
    /* coerce correct extent */
    if (minx > maxx) {
      t = maxx;
      maxx = minx;
      minx = t;
    }
    if (miny > maxy) {
      t = maxy;
      maxy = miny;
      miny = t;
    }
    rect->minx = minx;
    rect->miny = miny;
    rect->maxx = maxx;
    rect->maxy = maxy;
  } else {
    THROW_ERROR(Error, "Rect objects take 0, 1 or 4 arguments.");
  }

  obj = new MSRect(rect);
  obj->owner = true;
  obj->Wrap(args.This());
  return args.This();
}
Пример #20
0
Handle<Value> Query::New(Arguments const& args)
{
    HandleScope scope;
    if (!args.IsConstructCall()) {
        return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword")));
    }
    try {
        if (args.Length() != 1) {
            return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument")));
        }
        if (!args[0]->IsObject()) {
            return ThrowException(Exception::TypeError(String::New("first argument must be an object")));
        }
        Local<Object> obj = args[0]->ToObject();
        if (obj->IsNull() || obj->IsUndefined()) {
            return ThrowException(Exception::TypeError(String::New("first arg must be an object")));
        }
        if (!obj->Has(String::NewSymbol("coordinates"))) {
            return ThrowException(Exception::TypeError(String::New("must provide a coordinates property")));
        }
        Local<Value> coordinates = obj->Get(String::New("coordinates"));
        if (!coordinates->IsArray()) {
            return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
        }
        Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
        if (coordinates_array->Length() < 2) {
            return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided")));
        }

        Query* q = new Query();
        q->this_->zoomLevel = 18; //no generalization
        q->this_->printInstructions = true; //turn by turn instructions
        q->this_->alternateRoute = true; //get an alternate route, too
        q->this_->geometry = true; //retrieve geometry of route
        q->this_->compression = true; //polyline encoding
        q->this_->checkSum = UINT_MAX; //see wiki
        q->this_->service = "viaroute"; //that's routing
        q->this_->outputFormat = "json";
        q->this_->jsonpParameter = ""; //set for jsonp wrapping
        q->this_->language = ""; //unused atm

        if (obj->Has(String::NewSymbol("alternateRoute"))) {
            q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue();
        }

        for (uint32_t i = 0; i < coordinates_array->Length(); ++i) {
            Local<Value> coordinate = coordinates_array->Get(i);
            if (!coordinate->IsArray()) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
            if (coordinate_array->Length() != 2) {
                return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
            }
            q->this_->coordinates.push_back(
                FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
                                     coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));
        }

        q->Wrap(args.This());
        return args.This();
    } catch (std::exception const& ex) {
        return ThrowException(Exception::TypeError(String::New(ex.what())));
    }
    return Undefined();
}
Handle<Value> Datasource::New(const Arguments& args)
{
    HandleScope scope;

    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Datasource* d =  static_cast<Datasource*>(ptr);
        d->Wrap(args.This());
        return args.This();
    }
    if (!args.Length() == 1){
        return ThrowException(Exception::TypeError(
          String::New("accepts only one argument, an object of key:value datasource options")));
    }

    if (!args[0]->IsObject())
        return ThrowException(Exception::TypeError(
          String::New("must provide an object, eg {type: 'shape', file : 'world.shp'}")));

    Local<Object> options = args[0]->ToObject();

    // TODO - maybe validate in js?

    bool bind=true;
    if (options->Has(String::New("bind")))
    {
        Local<Value> bind_opt = options->Get(String::New("bind"));
        if (!bind_opt->IsBoolean())
          return ThrowException(Exception::TypeError(
            String::New("'bind' must be a Boolean")));

        bind = bind_opt->BooleanValue();
    }

    mapnik::parameters params;
    Local<Array> names = options->GetPropertyNames();
    uint32_t i = 0;
    uint32_t a_length = names->Length();
    while (i < a_length) {
        Local<Value> name = names->Get(i)->ToString();
        Local<Value> value = options->Get(name);
        params[TOSTR(name)] = TOSTR(value);
        i++;
    }

    mapnik::datasource_ptr ds;
    try
    {
        ds = mapnik::datasource_cache::create(params, bind);
    }
    catch (const mapnik::config_error & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const mapnik::datasource_exception & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const std::runtime_error & ex )
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (const std::exception & ex)
    {
        return ThrowException(Exception::Error(
          String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
          String::New("unknown exception happened, please file bug")));
    }
    if (ds)
    {
        Datasource* d = new Datasource();
        d->Wrap(args.This());
        d->datasource_ = ds;
        return args.This();
    }

    return Undefined();
}
Пример #22
0
Handle<Value> Grid::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Grid* g =  static_cast<Grid*>(ptr);
        g->Wrap(args.This());
        return args.This();
    }

    if (args.Length() >= 2)
    {
        if (!args[0]->IsNumber() || !args[1]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("Grid 'width' and 'height' must be a integers")));

        // defaults
        std::string key("__id__");
        unsigned int resolution = 1;

        if (args.Length() >= 3) {

            if (!args[2]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("optional third arg must be an options object")));
            Local<Object> options = args[2]->ToObject();

            if (options->Has(String::New("key"))) {
                Local<Value> bind_opt = options->Get(String::New("key"));
                if (!bind_opt->IsString())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'key' must be an string")));

                key = TOSTR(bind_opt);
            }
            // TODO - remove, deprecated
            if (options->Has(String::New("resolution"))) {
                Local<Value> bind_opt = options->Get(String::New("resolution"));
                if (!bind_opt->IsNumber())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'resolution' must be an string")));

                resolution = bind_opt->IntegerValue();
            }
        }

        Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution);
        g->Wrap(args.This());
        return args.This();
    }
    else
    {
        return ThrowException(Exception::Error(
                                  String::New("please provide Grid width and height")));
    }
    return Undefined();
}
Пример #23
0
Handle<Value> Color::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Color* c = static_cast<Color*>(ptr);
        c->Wrap(args.This());
        return args.This();
    }

    color_ptr c_p;
    try
    {

        if (args.Length() == 1 && args[0]->IsString()){

            c_p = boost::make_shared<mapnik::color>(TOSTR(args[0]));

        } else if (args.Length() == 3) {

            int r = args[0]->IntegerValue();
            int g = args[1]->IntegerValue();
            int b = args[2]->IntegerValue();
            c_p = boost::make_shared<mapnik::color>(r,g,b);

        } else if (args.Length() == 4) {

            int r = args[0]->IntegerValue();
            int g = args[1]->IntegerValue();
            int b = args[2]->IntegerValue();
            int a = args[3]->IntegerValue();
            c_p = boost::make_shared<mapnik::color>(r,g,b,a);
        } else {
            return ThrowException(Exception::Error(
                                      String::New("invalid arguments: colors can be created from a string, integer r,g,b values, or integer r,g,b,a values")));


        }
        // todo allow int,int,int and int,int,int,int contructor

    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
    catch (...)
    {
        return ThrowException(Exception::Error(
                                  String::New("unknown exception happened, please file bug")));
    }

    if (c_p)
    {
        Color* c = new Color();
        c->Wrap(args.This());
        c->this_ = c_p;
        return args.This();
    }
    else
    {
        return ThrowException(Exception::Error(
                                  String::New("unknown exception happened, please file bug")));
    }

    return Undefined();
}