Add clang-format (#1086)

Co-authored-by: mwilsnd <mwilsnd@gmail.com>
This commit is contained in:
Bart Louwers
2023-05-01 16:57:37 +02:00
committed by GitHub
parent 403a12bd1b
commit 71f6da2722
1018 changed files with 27876 additions and 25862 deletions

View File

@@ -46,12 +46,13 @@ public:
return value->IsObject() && !value->IsArray();
}
static std::optional<v8::Local<v8::Value>> objectMember(const v8::Local<v8::Value>& value, const char * name) {
static std::optional<v8::Local<v8::Value>> objectMember(const v8::Local<v8::Value>& value, const char* name) {
Nan::EscapableHandleScope scope;
if (!Nan::Has(Nan::To<v8::Object>(value).ToLocalChecked(), Nan::New(name).ToLocalChecked()).FromJust()) {
return {};
}
Nan::MaybeLocal<v8::Value> result = Nan::Get(Nan::To<v8::Object>(value).ToLocalChecked(), Nan::New(name).ToLocalChecked());
Nan::MaybeLocal<v8::Value> result = Nan::Get(Nan::To<v8::Object>(value).ToLocalChecked(),
Nan::New(name).ToLocalChecked());
if (result.IsEmpty()) {
return {};
}
@@ -61,11 +62,13 @@ public:
template <class Fn>
static std::optional<Error> eachMember(const v8::Local<v8::Value>& value, Fn&& fn) {
Nan::HandleScope scope;
v8::Local<v8::Array> names = Nan::GetOwnPropertyNames(Nan::To<v8::Object>(value).ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Array> names =
Nan::GetOwnPropertyNames(Nan::To<v8::Object>(value).ToLocalChecked()).ToLocalChecked();
for (uint32_t i = 0; i < names->Length(); ++i) {
v8::Local<v8::Value> k = Nan::Get(names, i).ToLocalChecked();
v8::Local<v8::Value> v = Nan::Get(Nan::To<v8::Object>(value).ToLocalChecked(), k).ToLocalChecked();
std::optional<Error> result = fn(*Nan::Utf8String(k), std::move(v)); // NOLINT(performance-move-const-arg)
std::optional<Error> result = fn(*Nan::Utf8String(k),
std::move(v)); // NOLINT(performance-move-const-arg)
if (result) {
return result;
}
@@ -107,17 +110,17 @@ public:
static std::optional<Value> toValue(const v8::Local<v8::Value>& value) {
if (value->IsFalse()) {
return { false };
return {false};
} else if (value->IsTrue()) {
return { true };
return {true};
} else if (value->IsString()) {
return { std::string(*Nan::Utf8String(value)) };
return {std::string(*Nan::Utf8String(value))};
} else if (value->IsUint32()) {
return { Nan::To<std::uint32_t>(value).ToChecked() };
return {Nan::To<std::uint32_t>(value).ToChecked()};
} else if (value->IsInt32()) {
return { Nan::To<std::int32_t>(value).ToChecked() };
return {Nan::To<std::int32_t>(value).ToChecked()};
} else if (value->IsNumber()) {
return { Nan::To<double>(value).ToChecked() };
return {Nan::To<double>(value).ToChecked()};
} else {
return {};
}
@@ -131,14 +134,14 @@ public:
std::string string = *Nan::Utf8String(stringified);
return parseGeoJSON(string, error);
} catch (const std::exception& ex) {
error = { ex.what() };
error = {ex.what()};
return {};
}
}
};
template <class T, class...Args>
std::optional<T> convert(const v8::Local<v8::Value>& value, Error& error, Args&&...args) {
template <class T, class... Args>
std::optional<T> convert(const v8::Local<v8::Value>& value, Error& error, Args&&... args) {
return convert<T>(Convertible(value), error, std::forward<Args>(args)...);
}

View File

@@ -59,7 +59,8 @@ type::Type parseType(v8::Local<v8::Object> type) {
#else
v8::Local<v8::Context> context = type->GetCreationContext().ToLocalChecked();
#endif
type::Type itemType = parseType(Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject(context).ToLocalChecked());
type::Type itemType = parseType(
Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject(context).ToLocalChecked());
std::optional<std::size_t> N;
v8::Local<v8::String> Nkey = Nan::New("N").ToLocalChecked();
@@ -97,12 +98,8 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo<v8::Value>& info) {
for (std::size_t i = 0; i < errors.size(); ++i) {
const auto& error = errors[i];
v8::Local<v8::Object> err = Nan::New<v8::Object>();
Nan::Set(err,
Nan::New("key").ToLocalChecked(),
Nan::New(error.key.c_str()).ToLocalChecked());
Nan::Set(err,
Nan::New("error").ToLocalChecked(),
Nan::New(error.message.c_str()).ToLocalChecked());
Nan::Set(err, Nan::New("key").ToLocalChecked(), Nan::New(error.key.c_str()).ToLocalChecked());
Nan::Set(err, Nan::New("error").ToLocalChecked(), Nan::New(error.message.c_str()).ToLocalChecked());
Nan::Set(result, Nan::New(static_cast<uint32_t>(i)), err);
}
info.GetReturnValue().Set(result);
@@ -119,7 +116,7 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (func) {
return success(std::move(*func));
}
return fail({ { error.message, "" } });
return fail({{error.message, ""}});
}
ParsingContext ctx = expected ? ParsingContext(*expected) : ParsingContext();
@@ -129,7 +126,7 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo<v8::Value>& info) {
return success(std::move(*parsed));
}
return fail(ctx.getErrors());
} catch(std::exception &ex) {
} catch (std::exception& ex) {
return Nan::ThrowError(ex.what());
}
}
@@ -213,12 +210,10 @@ struct ToValue {
}
v8::Local<v8::Value> operator()(const mbgl::Color& color) {
return operator()(std::vector<Value> {
static_cast<double>(color.r),
static_cast<double>(color.g),
static_cast<double>(color.b),
static_cast<double>(color.a)
});
return operator()(std::vector<Value>{static_cast<double>(color.r),
static_cast<double>(color.g),
static_cast<double>(color.b),
static_cast<double>(color.a)});
}
v8::Local<v8::Value> operator()(const std::unordered_map<std::string, Value>& map) {
@@ -248,11 +243,14 @@ void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo<v8::Value>& info)
}
std::optional<float> zoom;
v8::Local<v8::Value> v8zoom = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Value> v8zoom =
Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked();
if (v8zoom->IsNumber()) zoom = static_cast<float>(Nan::To<double>(v8zoom).FromJust());
std::optional<double> heatmapDensity;
v8::Local<v8::Value> v8heatmapDensity = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("heatmapDensity").ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Value> v8heatmapDensity = Nan::Get(info[0]->ToObject(context).ToLocalChecked(),
Nan::New("heatmapDensity").ToLocalChecked())
.ToLocalChecked();
if (v8heatmapDensity->IsNumber()) heatmapDensity = Nan::To<double>(v8heatmapDensity).FromJust();
Nan::JSON NanJSON;
@@ -270,12 +268,11 @@ void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo<v8::Value>& info)
info.GetReturnValue().Set(toJS(*result));
} else {
v8::Local<v8::Object> res = Nan::New<v8::Object>();
Nan::Set(res,
Nan::New("error").ToLocalChecked(),
Nan::New(result.error().message.c_str()).ToLocalChecked());
Nan::Set(
res, Nan::New("error").ToLocalChecked(), Nan::New(result.error().message.c_str()).ToLocalChecked());
info.GetReturnValue().Set(res);
}
} catch(std::exception &ex) {
} catch (std::exception& ex) {
return Nan::ThrowTypeError(ex.what());
}
}
@@ -285,7 +282,7 @@ void NodeExpression::GetType(const Nan::FunctionCallbackInfo<v8::Value>& info) {
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
const type::Type type = expression->getType();
const std::string name = type.match([&] (const auto& t) { return t.getName(); });
const std::string name = type.match([&](const auto& t) { return t.getName(); });
info.GetReturnValue().Set(Nan::New(name.c_str()).ToLocalChecked());
}

View File

@@ -14,37 +14,21 @@ using Properties = mbgl::PropertyMap;
template <class T>
struct ToType {
public:
v8::Local<v8::String> operator()(const empty&) {
return type("Empty");
}
v8::Local<v8::String> operator()(const empty&) { return type("Empty"); }
v8::Local<v8::String> operator()(const point<T>&) {
return type("Point");
}
v8::Local<v8::String> operator()(const point<T>&) { return type("Point"); }
v8::Local<v8::String> operator()(const line_string<T>&) {
return type("LineString");
}
v8::Local<v8::String> operator()(const line_string<T>&) { return type("LineString"); }
v8::Local<v8::String> operator()(const polygon<T>&) {
return type("Polygon");
}
v8::Local<v8::String> operator()(const polygon<T>&) { return type("Polygon"); }
v8::Local<v8::String> operator()(const multi_point<T>&) {
return type("MultiPoint");
}
v8::Local<v8::String> operator()(const multi_point<T>&) { return type("MultiPoint"); }
v8::Local<v8::String> operator()(const multi_line_string<T>&) {
return type("MultiLineString");
}
v8::Local<v8::String> operator()(const multi_line_string<T>&) { return type("MultiLineString"); }
v8::Local<v8::String> operator()(const multi_polygon<T>&) {
return type("MultiPolygon");
}
v8::Local<v8::String> operator()(const multi_polygon<T>&) { return type("MultiPolygon"); }
v8::Local<v8::String> operator()(const geometry_collection<T>&) {
return type("GeometryCollection");
}
v8::Local<v8::String> operator()(const geometry_collection<T>&) { return type("GeometryCollection"); }
private:
v8::Local<v8::String> type(const char* type_) {
@@ -56,7 +40,8 @@ private:
template <class T>
struct ToCoordinatesOrGeometries {
public:
// Handles line_string, polygon, multi_point, multi_line_string, multi_polygon, and geometry_collection.
// Handles line_string, polygon, multi_point, multi_line_string,
// multi_polygon, and geometry_collection.
template <class E>
v8::Local<v8::Object> operator()(const std::vector<E>& vector) {
Nan::EscapableHandleScope scope;
@@ -75,9 +60,7 @@ public:
return scope.Escape(result);
}
v8::Local<v8::Object> operator()(const geometry<T>& geometry) {
return toJS(geometry);
}
v8::Local<v8::Object> operator()(const geometry<T>& geometry) { return toJS(geometry); }
};
struct ToValue {
@@ -91,13 +74,9 @@ struct ToValue {
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(int64_t t) {
return operator()(static_cast<double>(t));
}
v8::Local<v8::Value> operator()(int64_t t) { return operator()(static_cast<double>(t)); }
v8::Local<v8::Value> operator()(uint64_t t) {
return operator()(static_cast<double>(t));
}
v8::Local<v8::Value> operator()(uint64_t t) { return operator()(static_cast<double>(t)); }
v8::Local<v8::Value> operator()(double t) {
Nan::EscapableHandleScope scope;
@@ -118,9 +97,7 @@ struct ToValue {
return scope.Escape(result);
}
v8::Local<v8::Value> operator()(const std::unordered_map<std::string, mbgl::Value>& map) {
return toJS(map);
}
v8::Local<v8::Value> operator()(const std::unordered_map<std::string, mbgl::Value>& map) { return toJS(map); }
};
v8::Local<v8::Object> toJS(const Geometry& geometry) {
@@ -128,13 +105,11 @@ v8::Local<v8::Object> toJS(const Geometry& geometry) {
v8::Local<v8::Object> result = Nan::New<v8::Object>();
Nan::Set(result,
Nan::New("type").ToLocalChecked(),
Geometry::visit(geometry, ToType<double>()));
Nan::Set(result, Nan::New("type").ToLocalChecked(), Geometry::visit(geometry, ToType<double>()));
Nan::Set(result,
Nan::New(geometry.is<GeometryCollection>() ? "geometries" : "coordinates").ToLocalChecked(),
Geometry::visit(geometry, ToCoordinatesOrGeometries<double>()));
Nan::New(geometry.is<GeometryCollection>() ? "geometries" : "coordinates").ToLocalChecked(),
Geometry::visit(geometry, ToCoordinatesOrGeometries<double>()));
return scope.Escape(result);
}

View File

@@ -15,4 +15,4 @@ v8::Local<v8::Object> toJS(const mbgl::Feature&);
v8::Local<v8::Object> toJS(const mbgl::Feature::geometry_type&);
v8::Local<v8::Object> toJS(const mbgl::PropertyMap&);
}
} // namespace node_mbgl

View File

@@ -12,9 +12,9 @@ struct NodeLogObserver::LogMessage {
LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_)
: severity(severity_),
event(event_),
code(code_),
text(std::move(text_)) {}
event(event_),
code(code_),
text(std::move(text_)) {}
};
NodeLogObserver::NodeLogObserver(v8::Local<v8::Object> target)
@@ -23,25 +23,26 @@ NodeLogObserver::NodeLogObserver(v8::Local<v8::Object> target)
auto msg = Nan::New<v8::Object>();
Nan::Set(msg, Nan::New("class").ToLocalChecked(),
Nan::New(mbgl::Enum<mbgl::Event>::toString(message.event)).ToLocalChecked());
Nan::Set(msg,
Nan::New("class").ToLocalChecked(),
Nan::New(mbgl::Enum<mbgl::Event>::toString(message.event)).ToLocalChecked());
Nan::Set(msg, Nan::New("severity").ToLocalChecked(),
Nan::New(mbgl::Enum<mbgl::EventSeverity>::toString(message.severity)).ToLocalChecked());
Nan::Set(msg,
Nan::New("severity").ToLocalChecked(),
Nan::New(mbgl::Enum<mbgl::EventSeverity>::toString(message.severity)).ToLocalChecked());
if (message.code != -1) {
Nan::Set(msg, Nan::New("code").ToLocalChecked(),
Nan::New<v8::Number>(message.code));
Nan::Set(msg, Nan::New("code").ToLocalChecked(), Nan::New<v8::Number>(message.code));
}
if (!message.text.empty()) {
Nan::Set(msg, Nan::New("text").ToLocalChecked(),
Nan::New(message.text).ToLocalChecked());
Nan::Set(msg, Nan::New("text").ToLocalChecked(), Nan::New(message.text).ToLocalChecked());
}
v8::Local<v8::Value> argv[] = { Nan::New("message").ToLocalChecked(), msg };
v8::Local<v8::Value> argv[] = {Nan::New("message").ToLocalChecked(), msg};
auto handle = Nan::New<v8::Object>(module);
auto emit = Nan::To<v8::Object>(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()).ToLocalChecked();
auto emit = Nan::To<v8::Object>(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked())
.ToLocalChecked();
Nan::CallAsFunction(emit, handle, 2, argv);
})) {
Nan::HandleScope scope;
@@ -56,7 +57,7 @@ NodeLogObserver::~NodeLogObserver() {
}
bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) {
queue->send({ severity, event, code, text });
queue->send({severity, event, code, text});
return true;
}

View File

@@ -12,7 +12,10 @@
namespace node_mbgl {
namespace util { template <typename T> class AsyncQueue; }
namespace util {
template <typename T>
class AsyncQueue;
}
class NodeLogObserver : public mbgl::Log::Observer {
public:

View File

@@ -41,7 +41,7 @@ struct NodeMap::RenderOptions {
double pitch = 0;
double latitude = 0;
double longitude = 0;
mbgl::Size size = { 512, 512 };
mbgl::Size size = {512, 512};
bool axonometric = false;
double xSkew = 0;
double ySkew = 1;
@@ -77,7 +77,9 @@ class ParseError extends Error {
}
}
}
ParseError)JS").ToLocalChecked()).ToLocalChecked();
ParseError)JS")
.ToLocalChecked())
.ToLocalChecked();
parseError.Reset(Nan::To<v8::Object>(Nan::RunScript(script).ToLocalChecked()).ToLocalChecked());
Nan::Set(target, Nan::New("ParseError").ToLocalChecked(), Nan::New(parseError));
@@ -177,35 +179,36 @@ void NodeMap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> options;
if(info.Length() > 0) {
if (info.Length() > 0) {
options = Nan::To<v8::Object>(info[0]).ToLocalChecked();
} else {
options = Nan::New<v8::Object>();
}
// Check that if 'request' is set it must be a function, if 'cancel' is set it must be a
// function and if 'ratio' is set it must be a number.
if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust()
&& !Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
// Check that if 'request' is set it must be a function, if 'cancel' is set
// it must be a function and if 'ratio' is set it must be a number.
if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() &&
!Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
return Nan::ThrowError("Options object 'request' property must be a function");
}
if (Nan::Has(options, Nan::New("cancel").ToLocalChecked()).FromJust()
&& !Nan::Get(options, Nan::New("cancel").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
if (Nan::Has(options, Nan::New("cancel").ToLocalChecked()).FromJust() &&
!Nan::Get(options, Nan::New("cancel").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
return Nan::ThrowError("Options object 'cancel' property must be a function");
}
if (Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust()
&& !Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->IsNumber()) {
if (Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust() &&
!Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->IsNumber()) {
return Nan::ThrowError("Options object 'ratio' property must be a number");
}
info.This()->SetInternalField(1, options);
if(Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust()
&& Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() &&
Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
mbgl::FileSourceManager::get()->registerFileSourceFactory(
mbgl::FileSourceType::ResourceLoader, [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions&) {
mbgl::FileSourceType::ResourceLoader,
[](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions&) {
return std::make_unique<node_mbgl::NodeFileSource>(
reinterpret_cast<node_mbgl::NodeMap*>(resourceOptions.platformContext()));
});
@@ -214,7 +217,7 @@ void NodeMap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
auto nodeMap = new NodeMap(options);
nodeMap->Wrap(info.This());
} catch(std::exception &ex) {
} catch (std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -267,7 +270,7 @@ void NodeMap::Load(const Nan::FunctionCallbackInfo<v8::Value>& info) {
nodeMap->map->getStyle().loadJSON(style);
} catch (const mbgl::util::StyleParseException& ex) {
return Nan::ThrowError(ParseError(ex.what()));
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -278,9 +281,12 @@ void NodeMap::Load(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto options = Nan::To<v8::Object>(info[1]).ToLocalChecked();
if (Nan::Has(options, Nan::New("defaultStyleCamera").ToLocalChecked()).FromJust()) {
if (!Nan::Get(options, Nan::New("defaultStyleCamera").ToLocalChecked()).ToLocalChecked()->IsBoolean()) {
return Nan::ThrowError("Options object 'defaultStyleCamera' property must be a boolean");
return Nan::ThrowError(
"Options object 'defaultStyleCamera' property must be a "
"boolean");
}
if (Nan::To<bool>(Nan::Get(options, Nan::New("cameraMutated").ToLocalChecked()).ToLocalChecked()).ToChecked()) {
if (Nan::To<bool>(Nan::Get(options, Nan::New("cameraMutated").ToLocalChecked()).ToLocalChecked())
.ToChecked()) {
nodeMap->map->jumpTo(nodeMap->map->getStyle().getDefaultCamera());
}
}
@@ -299,7 +305,7 @@ void NodeMap::Loaded(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
loaded = nodeMap->map->isFullyLoaded();
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -316,7 +322,8 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
}
if (Nan::Has(obj, Nan::New("bearing").ToLocalChecked()).FromJust()) {
options.bearing = Nan::To<double>(Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()).ToChecked();
options.bearing =
Nan::To<double>(Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()).ToChecked();
}
if (Nan::Has(obj, Nan::New("pitch").ToLocalChecked()).FromJust()) {
@@ -334,15 +341,20 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
}
if (Nan::Has(obj, Nan::New("axonometric").ToLocalChecked()).FromJust()) {
options.axonometric = Nan::To<bool>(Nan::Get(obj, Nan::New("axonometric").ToLocalChecked()).ToLocalChecked()).ToChecked();
options.axonometric =
Nan::To<bool>(Nan::Get(obj, Nan::New("axonometric").ToLocalChecked()).ToLocalChecked()).ToChecked();
}
if (Nan::Has(obj, Nan::New("skew").ToLocalChecked()).FromJust()) {
auto skewObj = Nan::Get(obj, Nan::New("skew").ToLocalChecked()).ToLocalChecked();
if (skewObj->IsArray()) {
auto skew = skewObj.As<v8::Array>();
if (skew->Length() > 0) { options.xSkew = Nan::To<double>(Nan::Get(skew, 0).ToLocalChecked()).ToChecked(); }
if (skew->Length() > 1) { options.ySkew = Nan::To<double>(Nan::Get(skew, 1).ToLocalChecked()).ToChecked(); }
if (skew->Length() > 0) {
options.xSkew = Nan::To<double>(Nan::Get(skew, 0).ToLocalChecked()).ToChecked();
}
if (skew->Length() > 1) {
options.ySkew = Nan::To<double>(Nan::Get(skew, 1).ToLocalChecked()).ToChecked();
}
}
}
@@ -350,30 +362,40 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
auto centerObj = Nan::Get(obj, Nan::New("center").ToLocalChecked()).ToLocalChecked();
if (centerObj->IsArray()) {
auto center = centerObj.As<v8::Array>();
if (center->Length() > 0) { options.longitude = Nan::To<double>(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); }
if (center->Length() > 1) { options.latitude = Nan::To<double>(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); }
if (center->Length() > 0) {
options.longitude = Nan::To<double>(Nan::Get(center, 0).ToLocalChecked()).ToChecked();
}
if (center->Length() > 1) {
options.latitude = Nan::To<double>(Nan::Get(center, 1).ToLocalChecked()).ToChecked();
}
}
}
if (Nan::Has(obj, Nan::New("width").ToLocalChecked()).FromJust()) {
options.size.width = static_cast<uint32_t>(Nan::To<int64_t>(Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked());
options.size.width = static_cast<uint32_t>(
Nan::To<int64_t>(Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked());
}
if (Nan::Has(obj, Nan::New("height").ToLocalChecked()).FromJust()) {
options.size.height = static_cast<uint32_t>(Nan::To<int64_t>(Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked());
options.size.height = static_cast<uint32_t>(
Nan::To<int64_t>(Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked());
}
if (Nan::Has(obj, Nan::New("classes").ToLocalChecked()).FromJust()) {
auto classes = Nan::To<v8::Object>(Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked()).ToLocalChecked().As<v8::Array>();
auto classes = Nan::To<v8::Object>(Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked())
.ToLocalChecked()
.As<v8::Array>();
const int length = classes->Length();
options.classes.reserve(length);
for (int i = 0; i < length; i++) {
options.classes.emplace_back(std::string { *Nan::Utf8String(Nan::To<v8::String>(Nan::Get(classes, i).ToLocalChecked()).ToLocalChecked()) });
options.classes.emplace_back(std::string{
*Nan::Utf8String(Nan::To<v8::String>(Nan::Get(classes, i).ToLocalChecked()).ToLocalChecked())});
}
}
if (Nan::Has(obj, Nan::New("debug").ToLocalChecked()).FromJust()) {
auto debug = Nan::To<v8::Object>(Nan::Get(obj, Nan::New("debug").ToLocalChecked()).ToLocalChecked()).ToLocalChecked();
auto debug =
Nan::To<v8::Object>(Nan::Get(obj, Nan::New("debug").ToLocalChecked()).ToLocalChecked()).ToLocalChecked();
if (Nan::Has(debug, Nan::New("tileBorders").ToLocalChecked()).FromJust()) {
if (Nan::To<bool>(Nan::Get(debug, Nan::New("tileBorders").ToLocalChecked()).ToLocalChecked()).ToChecked()) {
options.debugOptions = options.debugOptions | mbgl::MapDebugOptions::TileBorders;
@@ -406,12 +428,11 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
class RenderRequest : public Nan::AsyncResource {
public:
explicit RenderRequest(v8::Local<v8::Function> callback_) : AsyncResource("mbgl:RenderRequest") {
explicit RenderRequest(v8::Local<v8::Function> callback_)
: AsyncResource("mbgl:RenderRequest") {
callback.Reset(callback_);
}
~RenderRequest() {
callback.Reset();
}
~RenderRequest() { callback.Reset(); }
Nan::Persistent<v8::Function> callback;
};
@@ -471,7 +492,7 @@ void NodeMap::Render(const Nan::FunctionCallbackInfo<v8::Value>& info) {
return Nan::ThrowTypeError(err.message.c_str());
} catch (const mbgl::util::StyleParseException& ex) {
return Nan::ThrowError(ParseError(ex.what()));
} catch (const mbgl::util::Exception &ex) {
} catch (const mbgl::util::Exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -490,12 +511,12 @@ void NodeMap::startRender() {
}
});
// Retain this object, otherwise it might get destructed before we are finished rendering the
// still image.
// Retain this object, otherwise it might get destructed before we are
// finished rendering the still image.
Ref();
// Similarly, we're now waiting for the async to be called, so we need to make sure that it
// keeps the loop alive.
// Similarly, we're now waiting for the async to be called, so we need to
// make sure that it keeps the loop alive.
uv_ref(reinterpret_cast<uv_handle_t*>(async));
}
@@ -504,15 +525,13 @@ void NodeMap::startRender(const NodeMap::RenderOptions& options) {
map->setSize(options.size);
mbgl::CameraOptions camera;
camera.center = mbgl::LatLng { options.latitude, options.longitude };
camera.center = mbgl::LatLng{options.latitude, options.longitude};
camera.zoom = options.zoom;
camera.bearing = options.bearing;
camera.pitch = options.pitch;
auto projectionOptions = mbgl::ProjectionMode()
.withAxonometric(options.axonometric)
.withXSkew(options.xSkew)
.withYSkew(options.ySkew);
auto projectionOptions =
mbgl::ProjectionMode().withAxonometric(options.axonometric).withXSkew(options.xSkew).withYSkew(options.ySkew);
map->setProjectionMode(projectionOptions);
@@ -527,17 +546,17 @@ void NodeMap::startRender(const NodeMap::RenderOptions& options) {
}
});
// Retain this object, otherwise it might get destructed before we are finished rendering the
// still image.
// Retain this object, otherwise it might get destructed before we are
// finished rendering the still image.
Ref();
// Similarly, we're now waiting for the async to be called, so we need to make sure that it
// keeps the loop alive.
uv_ref(reinterpret_cast<uv_handle_t *>(async));
// Similarly, we're now waiting for the async to be called, so we need to
// make sure that it keeps the loop alive.
uv_ref(reinterpret_cast<uv_handle_t*>(async));
}
v8::Local<v8::Value> NodeMap::ParseError(const char* msg) {
v8::Local<v8::Value> argv[] = { Nan::New(msg).ToLocalChecked() };
v8::Local<v8::Value> argv[] = {Nan::New(msg).ToLocalChecked()};
return Nan::CallAsConstructor(Nan::New(parseError), 1, argv).ToLocalChecked();
}
@@ -547,7 +566,7 @@ void NodeMap::renderFinished() {
Nan::HandleScope scope;
// We're done with this render call, so we're unrefing so that the loop could close.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
uv_unref(reinterpret_cast<uv_handle_t*>(async));
// Move the callback and image out of the way so that the callback can start a new render call.
auto request = std::move(req);
@@ -573,9 +592,7 @@ void NodeMap::renderFinished() {
err = Nan::Error(ex.what());
}
v8::Local<v8::Value> argv[] = {
err
};
v8::Local<v8::Value> argv[] = {err};
// This must be empty to be prepared for the next render call.
error = nullptr;
@@ -584,31 +601,25 @@ void NodeMap::renderFinished() {
request->runInAsyncScope(target, callback, 1, argv);
} else if (img.data) {
v8::Local<v8::Object> pixels = Nan::NewBuffer(
reinterpret_cast<char *>(img.data.get()), img.bytes(),
// Retain the data until the buffer is deleted.
[](char *, void * hint) {
delete [] reinterpret_cast<uint8_t*>(hint);
},
img.data.get()
).ToLocalChecked();
reinterpret_cast<char*>(img.data.get()),
img.bytes(),
// Retain the data until the buffer is deleted.
[](char*, void* hint) { delete[] reinterpret_cast<uint8_t*>(hint); },
img.data.get())
.ToLocalChecked();
if (!pixels.IsEmpty()) {
img.data.release();
}
v8::Local<v8::Value> argv[] = {
Nan::Null(),
pixels
};
v8::Local<v8::Value> argv[] = {Nan::Null(), pixels};
request->runInAsyncScope(target, callback, 2, argv);
} else {
v8::Local<v8::Value> argv[] = {
Nan::Error("Didn't get an image")
};
v8::Local<v8::Value> argv[] = {Nan::Error("Didn't get an image")};
request->runInAsyncScope(target, callback, 1, argv);
}
// There is no render pending anymore, we the GC could now delete this object if it went out
// of scope.
// There is no render pending anymore, we the GC could now delete this
// object if it went out of scope.
Unref();
}
@@ -623,7 +634,7 @@ void NodeMap::Release(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
nodeMap->release();
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -633,9 +644,7 @@ void NodeMap::Release(const Nan::FunctionCallbackInfo<v8::Value>& info) {
void NodeMap::release() {
if (!map) throw mbgl::util::Exception(releasedMessage());
uv_close(reinterpret_cast<uv_handle_t *>(async), [] (uv_handle_t *h) {
delete reinterpret_cast<uv_async_t *>(h);
});
uv_close(reinterpret_cast<uv_handle_t*>(async), [](uv_handle_t* h) { delete reinterpret_cast<uv_async_t*>(h); });
map.reset();
frontend.reset();
@@ -655,7 +664,7 @@ void NodeMap::Cancel(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
nodeMap->cancel();
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -669,22 +678,21 @@ void NodeMap::cancel() {
map.reset();
// Remove the existing async handle to flush any scheduled calls to renderFinished.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
uv_close(reinterpret_cast<uv_handle_t *>(async), [] (uv_handle_t *h) {
delete reinterpret_cast<uv_async_t *>(h);
});
uv_unref(reinterpret_cast<uv_handle_t*>(async));
uv_close(reinterpret_cast<uv_handle_t*>(async), [](uv_handle_t* h) { delete reinterpret_cast<uv_async_t*>(h); });
async = new uv_async_t;
async->data = this;
uv_async_init(uv_default_loop(), async, [](uv_async_t* h) {
reinterpret_cast<NodeMap *>(h->data)->renderFinished();
});
uv_async_init(
uv_default_loop(), async, [](uv_async_t* h) { reinterpret_cast<NodeMap*>(h->data)->renderFinished(); });
frontend = std::make_unique<mbgl::HeadlessFrontend>(mbgl::Size{ 512, 512 }, pixelRatio);
map = std::make_unique<mbgl::Map>(*frontend, mapObserver,
mbgl::MapOptions().withSize(frontend->getSize())
.withPixelRatio(pixelRatio)
.withMapMode(mode)
.withCrossSourceCollisions(crossSourceCollisions),
frontend = std::make_unique<mbgl::HeadlessFrontend>(mbgl::Size{512, 512}, pixelRatio);
map = std::make_unique<mbgl::Map>(*frontend,
mapObserver,
mbgl::MapOptions()
.withSize(frontend->getSize())
.withPixelRatio(pixelRatio)
.withMapMode(mode)
.withCrossSourceCollisions(crossSourceCollisions),
mbgl::ResourceOptions().withPlatformContext(reinterpret_cast<void*>(this)),
mbgl::ClientOptions());
@@ -717,7 +725,8 @@ void NodeMap::AddSource(const Nan::FunctionCallbackInfo<v8::Value>& info) {
}
Error error;
std::optional<std::unique_ptr<Source>> source = convert<std::unique_ptr<Source>>(info[1], error, *Nan::Utf8String(info[0]));
std::optional<std::unique_ptr<Source>> source = convert<std::unique_ptr<Source>>(
info[1], error, *Nan::Utf8String(info[0]));
if (!source) {
Nan::ThrowTypeError(error.message.c_str());
return;
@@ -822,8 +831,10 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo<v8::Value>& info) {
return Nan::ThrowTypeError("pixelRatio parameter required");
}
uint32_t imageHeight = Nan::To<uint32_t>(Nan::Get(optionObject, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked();
uint32_t imageWidth = Nan::To<uint32_t>(Nan::Get(optionObject, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked();
uint32_t imageHeight =
Nan::To<uint32_t>(Nan::Get(optionObject, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked();
uint32_t imageWidth =
Nan::To<uint32_t>(Nan::Get(optionObject, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked();
if (imageWidth > 1024 || imageHeight > 1024) {
return Nan::ThrowTypeError("Max height and width is 1024");
@@ -834,10 +845,12 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo<v8::Value>& info) {
sdf = Nan::To<bool>(Nan::Get(optionObject, Nan::New("sdf").ToLocalChecked()).ToLocalChecked()).ToChecked();
}
float pixelRatio = (float)Nan::To<double>(Nan::Get(optionObject, Nan::New("pixelRatio").ToLocalChecked()).ToLocalChecked()).ToChecked();
float pixelRatio = (float)Nan::To<double>(
Nan::Get(optionObject, Nan::New("pixelRatio").ToLocalChecked()).ToLocalChecked())
.ToChecked();
auto imageBuffer = Nan::To<v8::Object>(info[1]).ToLocalChecked()->ToObject(context).ToLocalChecked();
char * imageDataBuffer = node::Buffer::Data(imageBuffer);
char* imageDataBuffer = node::Buffer::Data(imageBuffer);
size_t imageLength = node::Buffer::Length(imageBuffer);
if (imageLength != imageHeight * imageWidth * 4) {
@@ -847,9 +860,10 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo<v8::Value>& info) {
std::unique_ptr<uint8_t[]> data = std::make_unique<uint8_t[]>(imageLength);
std::copy(imageDataBuffer, imageDataBuffer + imageLength, data.get());
mbgl::UnassociatedImage cImage({ imageWidth, imageHeight}, std::move(data));
mbgl::UnassociatedImage cImage({imageWidth, imageHeight}, std::move(data));
mbgl::PremultipliedImage cPremultipliedImage = mbgl::util::premultiply(std::move(cImage));
nodeMap->map->getStyle().addImage(std::make_unique<mbgl::style::Image>(*Nan::Utf8String(info[0]), std::move(cPremultipliedImage), pixelRatio, sdf));
nodeMap->map->getStyle().addImage(std::make_unique<mbgl::style::Image>(
*Nan::Utf8String(info[0]), std::move(cPremultipliedImage), pixelRatio, sdf));
}
void NodeMap::RemoveImage(const Nan::FunctionCallbackInfo<v8::Value>& info) {
@@ -973,15 +987,19 @@ void NodeMap::SetSize(const Nan::FunctionCallbackInfo<v8::Value>& info) {
}
auto size = info[0].As<v8::Array>();
uint32_t width= 0;
uint32_t width = 0;
uint32_t height = 0;
if (size->Length() > 0) { width = Nan::To<uint32_t>(Nan::Get(size, 0).ToLocalChecked()).ToChecked(); }
if (size->Length() > 1) { height = Nan::To<uint32_t>(Nan::Get(size, 1).ToLocalChecked()).ToChecked(); }
if (size->Length() > 0) {
width = Nan::To<uint32_t>(Nan::Get(size, 0).ToLocalChecked()).ToChecked();
}
if (size->Length() > 1) {
height = Nan::To<uint32_t>(Nan::Get(size, 1).ToLocalChecked()).ToChecked();
}
try {
nodeMap->frontend->setSize({ width, height });
nodeMap->map->setSize({ width, height });
} catch (const std::exception &ex) {
nodeMap->frontend->setSize({width, height});
nodeMap->map->setSize({width, height});
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -999,12 +1017,16 @@ void NodeMap::SetCenter(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto center = info[0].As<v8::Array>();
double latitude = 0;
double longitude = 0;
if (center->Length() > 0) { longitude = Nan::To<double>(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); }
if (center->Length() > 1) { latitude = Nan::To<double>(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); }
if (center->Length() > 0) {
longitude = Nan::To<double>(Nan::Get(center, 0).ToLocalChecked()).ToChecked();
}
if (center->Length() > 1) {
latitude = Nan::To<double>(Nan::Get(center, 1).ToLocalChecked()).ToChecked();
}
try {
nodeMap->map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude, longitude }));
} catch (const std::exception &ex) {
nodeMap->map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude, longitude}));
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1021,7 +1043,7 @@ void NodeMap::SetZoom(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
nodeMap->map->jumpTo(mbgl::CameraOptions().withZoom(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1038,7 +1060,7 @@ void NodeMap::SetBearing(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
nodeMap->map->jumpTo(mbgl::CameraOptions().withBearing(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1055,7 +1077,7 @@ void NodeMap::SetPitch(const Nan::FunctionCallbackInfo<v8::Value>& info) {
try {
nodeMap->map->jumpTo(mbgl::CameraOptions().withPitch(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1080,7 +1102,7 @@ void NodeMap::SetLight(const Nan::FunctionCallbackInfo<v8::Value>& info) {
} else {
return Nan::ThrowTypeError(conversionError.message.c_str());
}
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1096,9 +1118,8 @@ void NodeMap::SetAxonometric(const Nan::FunctionCallbackInfo<v8::Value>& info) {
}
try {
nodeMap->map->setProjectionMode(mbgl::ProjectionMode()
.withAxonometric(Nan::To<bool>(info[0]).ToChecked()));
} catch (const std::exception &ex) {
nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withAxonometric(Nan::To<bool>(info[0]).ToChecked()));
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1114,9 +1135,8 @@ void NodeMap::SetXSkew(const Nan::FunctionCallbackInfo<v8::Value>& info) {
}
try {
nodeMap->map->setProjectionMode(mbgl::ProjectionMode()
.withXSkew(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception &ex) {
nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withXSkew(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1132,9 +1152,8 @@ void NodeMap::SetYSkew(const Nan::FunctionCallbackInfo<v8::Value>& info) {
}
try {
nodeMap->map->setProjectionMode(mbgl::ProjectionMode()
.withYSkew(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception &ex) {
nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withYSkew(Nan::To<double>(info[0]).ToChecked()));
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
@@ -1173,7 +1192,9 @@ void NodeMap::SetFeatureState(const Nan::FunctionCallbackInfo<v8::Value>& info)
if (Nan::Has(feature, Nan::New("sourceLayer").ToLocalChecked()).FromJust()) {
auto sourceLayerOption = Nan::Get(feature, Nan::New("sourceLayer").ToLocalChecked()).ToLocalChecked();
if (!sourceLayerOption->IsString()) {
return Nan::ThrowTypeError("SetFeatureState: Requires feature.sourceLayer property to be a string");
return Nan::ThrowTypeError(
"SetFeatureState: Requires feature.sourceLayer property to be "
"a string");
}
sourceLayerID = {*Nan::Utf8String(sourceLayerOption)};
}
@@ -1274,7 +1295,9 @@ void NodeMap::GetFeatureState(const Nan::FunctionCallbackInfo<v8::Value>& info)
if (Nan::Has(feature, Nan::New("sourceLayer").ToLocalChecked()).FromJust()) {
auto sourceLayerOption = Nan::Get(feature, Nan::New("sourceLayer").ToLocalChecked()).ToLocalChecked();
if (!sourceLayerOption->IsString()) {
return Nan::ThrowTypeError("GetFeatureState: Requires feature.sourceLayer property to be a string");
return Nan::ThrowTypeError(
"GetFeatureState: Requires feature.sourceLayer property to be "
"a string");
}
sourceLayerID = {*Nan::Utf8String(sourceLayerOption)};
}
@@ -1333,7 +1356,9 @@ void NodeMap::RemoveFeatureState(const Nan::FunctionCallbackInfo<v8::Value>& inf
if (Nan::Has(feature, Nan::New("sourceLayer").ToLocalChecked()).FromJust()) {
auto sourceLayerOption = Nan::Get(feature, Nan::New("sourceLayer").ToLocalChecked()).ToLocalChecked();
if (!sourceLayerOption->IsString()) {
return Nan::ThrowTypeError("RemoveFeatureState: Requires feature.sourceLayer property to be a string");
return Nan::ThrowTypeError(
"RemoveFeatureState: Requires feature.sourceLayer property to "
"be a string");
}
sourceLayerID = {*Nan::Utf8String(sourceLayerOption)};
}
@@ -1349,7 +1374,9 @@ void NodeMap::RemoveFeatureState(const Nan::FunctionCallbackInfo<v8::Value>& inf
if (info.Length() == 2) {
auto keyParam = Nan::To<v8::String>(info[1]).ToLocalChecked();
if (!keyParam->IsString()) {
return Nan::ThrowTypeError("RemoveFeatureState: Requires feature key property to be a string");
return Nan::ThrowTypeError(
"RemoveFeatureState: Requires feature key property to be a "
"string");
}
stateKey = {*Nan::Utf8String(keyParam)};
}
@@ -1397,7 +1424,7 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo<v8::Value>&
auto options = Nan::To<v8::Object>(info[1]).ToLocalChecked();
//Check if layers is set. If provided, it must be an array of strings
// Check if layers is set. If provided, it must be an array of strings
if (Nan::Has(options, Nan::New("layers").ToLocalChecked()).FromJust()) {
auto layersOption = Nan::Get(options, Nan::New("layers").ToLocalChecked()).ToLocalChecked();
if (!layersOption->IsArray()) {
@@ -1405,13 +1432,13 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo<v8::Value>&
}
auto layers = layersOption.As<v8::Array>();
std::vector<std::string> layersVec;
for (uint32_t i=0; i < layers->Length(); i++) {
layersVec.emplace_back(*Nan::Utf8String(Nan::Get(layers,i).ToLocalChecked()));
for (uint32_t i = 0; i < layers->Length(); i++) {
layersVec.emplace_back(*Nan::Utf8String(Nan::Get(layers, i).ToLocalChecked()));
}
queryOptions.layerIDs = layersVec;
}
//Check if filter is provided. If set it must be a valid Filter object
// Check if filter is provided. If set it must be a valid Filter object
if (Nan::Has(options, Nan::New("filter").ToLocalChecked()).FromJust()) {
auto filterOption = Nan::Get(options, Nan::New("filter").ToLocalChecked()).ToLocalChecked();
Error error;
@@ -1427,25 +1454,21 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo<v8::Value>&
std::vector<mbgl::Feature> optional;
if (Nan::Get(posOrBox, 0).ToLocalChecked()->IsArray()) {
auto pos0 = Nan::Get(posOrBox, 0).ToLocalChecked().As<v8::Array>();
auto pos1 = Nan::Get(posOrBox, 1).ToLocalChecked().As<v8::Array>();
optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(mbgl::ScreenBox {
{
Nan::To<double>(Nan::Get(pos0, 0).ToLocalChecked()).ToChecked(),
Nan::To<double>(Nan::Get(pos0, 1).ToLocalChecked()).ToChecked()
}, {
Nan::To<double>(Nan::Get(pos1, 0).ToLocalChecked()).ToChecked(),
Nan::To<double>(Nan::Get(pos1, 1).ToLocalChecked()).ToChecked()
}
}, queryOptions);
optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(
mbgl::ScreenBox{{Nan::To<double>(Nan::Get(pos0, 0).ToLocalChecked()).ToChecked(),
Nan::To<double>(Nan::Get(pos0, 1).ToLocalChecked()).ToChecked()},
{Nan::To<double>(Nan::Get(pos1, 0).ToLocalChecked()).ToChecked(),
Nan::To<double>(Nan::Get(pos1, 1).ToLocalChecked()).ToChecked()}},
queryOptions);
} else {
optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(mbgl::ScreenCoordinate {
Nan::To<double>(Nan::Get(posOrBox, 0).ToLocalChecked()).ToChecked(),
Nan::To<double>(Nan::Get(posOrBox, 1).ToLocalChecked()).ToChecked()
}, queryOptions);
optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(
mbgl::ScreenCoordinate{Nan::To<double>(Nan::Get(posOrBox, 0).ToLocalChecked()).ToChecked(),
Nan::To<double>(Nan::Get(posOrBox, 1).ToLocalChecked()).ToChecked()},
queryOptions);
}
auto array = Nan::New<v8::Array>();
@@ -1453,7 +1476,7 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo<v8::Value>&
Nan::Set(array, static_cast<uint32_t>(i), toJS(optional[i]));
}
info.GetReturnValue().Set(array);
} catch (const std::exception &ex) {
} catch (const std::exception& ex) {
return Nan::ThrowError(ex.what());
}
}
@@ -1462,42 +1485,47 @@ NodeMap::NodeMap(v8::Local<v8::Object> options)
: pixelRatio([&] {
Nan::HandleScope scope;
return Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust()
? static_cast<float>(Nan::To<double>(Nan::Get(options, Nan::New("ratio").ToLocalChecked())
.ToLocalChecked()).ToChecked())
? static_cast<float>(
Nan::To<double>(Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked())
.ToChecked())
: 1.0f;
}())
, mode([&] {
Nan::HandleScope scope;
if (std::string(*v8::String::Utf8Value(v8::Isolate::GetCurrent(), Nan::Get(options, Nan::New("mode").ToLocalChecked()).ToLocalChecked())) == "tile") {
return mbgl::MapMode::Tile;
} else {
return mbgl::MapMode::Static;
}
}())
, crossSourceCollisions([&] {
Nan::HandleScope scope;
return Nan::Has(options, Nan::New("crossSourceCollisions").ToLocalChecked()).FromJust()
? Nan::To<bool>(Nan::Get(options, Nan::New("crossSourceCollisions").ToLocalChecked())
.ToLocalChecked()).ToChecked()
: true;
}())
, mapObserver(NodeMapObserver())
, frontend(std::make_unique<mbgl::HeadlessFrontend>(mbgl::Size { 512, 512 }, pixelRatio))
, map(std::make_unique<mbgl::Map>(*frontend, mapObserver,
mbgl::MapOptions().withSize(frontend->getSize())
.withPixelRatio(pixelRatio)
.withMapMode(mode)
.withCrossSourceCollisions(crossSourceCollisions),
}()),
mode([&] {
Nan::HandleScope scope;
if (std::string(*v8::String::Utf8Value(
v8::Isolate::GetCurrent(), Nan::Get(options, Nan::New("mode").ToLocalChecked()).ToLocalChecked())) ==
"tile") {
return mbgl::MapMode::Tile;
} else {
return mbgl::MapMode::Static;
}
}()),
crossSourceCollisions([&] {
Nan::HandleScope scope;
return Nan::Has(options, Nan::New("crossSourceCollisions").ToLocalChecked()).FromJust()
? Nan::To<bool>(
Nan::Get(options, Nan::New("crossSourceCollisions").ToLocalChecked()).ToLocalChecked())
.ToChecked()
: true;
}()),
mapObserver(NodeMapObserver()),
frontend(std::make_unique<mbgl::HeadlessFrontend>(mbgl::Size{512, 512}, pixelRatio)),
map(std::make_unique<mbgl::Map>(*frontend,
mapObserver,
mbgl::MapOptions()
.withSize(frontend->getSize())
.withPixelRatio(pixelRatio)
.withMapMode(mode)
.withCrossSourceCollisions(crossSourceCollisions),
mbgl::ResourceOptions().withPlatformContext(reinterpret_cast<void*>(this)),
mbgl::ClientOptions()))
, async(new uv_async_t) {
mbgl::ClientOptions())),
async(new uv_async_t) {
async->data = this;
uv_async_init(uv_default_loop(), async, [](uv_async_t* h) {
reinterpret_cast<NodeMap *>(h->data)->renderFinished();
});
uv_async_init(
uv_default_loop(), async, [](uv_async_t* h) { reinterpret_cast<NodeMap*>(h->data)->renderFinished(); });
// Make sure the async handle doesn't keep the loop alive.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
uv_unref(reinterpret_cast<uv_handle_t*>(async));
}
NodeMap::~NodeMap() {
@@ -1508,24 +1536,24 @@ NodeMap::~NodeMap() {
}
}
std::unique_ptr<mbgl::AsyncRequest> NodeFileSource::request(const mbgl::Resource& resource, mbgl::FileSource::Callback callback_) {
std::unique_ptr<mbgl::AsyncRequest> NodeFileSource::request(const mbgl::Resource& resource,
mbgl::FileSource::Callback callback_) {
assert(nodeMap);
Nan::HandleScope scope;
// Because this method may be called while this NodeMap is already eligible for garbage collection,
// we need to explicitly hold onto our own handle here so that GC during a v8 call doesn't destroy
// *this while we're still executing code.
// Because this method may be called while this NodeMap is already eligible
// for garbage collection, we need to explicitly hold onto our own handle
// here so that GC during a v8 call doesn't destroy *this while we're still
// executing code.
nodeMap->handle();
auto asyncRequest = std::make_unique<node_mbgl::NodeAsyncRequest>();
v8::Local<v8::Value> argv[] = {
Nan::New<v8::External>(nodeMap),
Nan::New<v8::External>(&callback_),
Nan::New<v8::External>(asyncRequest.get()),
Nan::New(resource.url).ToLocalChecked(),
Nan::New<v8::Integer>(resource.kind)
};
v8::Local<v8::Value> argv[] = {Nan::New<v8::External>(nodeMap),
Nan::New<v8::External>(&callback_),
Nan::New<v8::External>(asyncRequest.get()),
Nan::New(resource.url).ToLocalChecked(),
Nan::New<v8::Integer>(resource.kind)};
Nan::NewInstance(Nan::New(node_mbgl::NodeRequest::constructor), 5, argv).ToLocalChecked();
@@ -1537,7 +1565,7 @@ bool NodeFileSource::canRequest(const mbgl::Resource&) const {
}
void NodeFileSource::setResourceOptions(mbgl::ResourceOptions options) {
this->_resourceOptions = std::move(options);
this->_resourceOptions = std::move(options);
}
mbgl::ResourceOptions NodeFileSource::getResourceOptions() {

View File

@@ -94,13 +94,14 @@ public:
std::unique_ptr<RenderRequest> req;
// Async for delivering the notifications of render completion.
uv_async_t *async;
uv_async_t* async;
bool loaded = false;
};
struct NodeFileSource : public mbgl::FileSource {
NodeFileSource(NodeMap* nodeMap_) : nodeMap(nodeMap_) {}
NodeFileSource(NodeMap* nodeMap_)
: nodeMap(nodeMap_) {}
~NodeFileSource() override = default;
std::unique_ptr<mbgl::AsyncRequest> request(const mbgl::Resource&, mbgl::FileSource::Callback) final;
bool canRequest(const mbgl::Resource&) const override;

View File

@@ -14,20 +14,20 @@
#include "node_request.hpp"
#include "node_expression.hpp"
void SetBackendType(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1 || info[0]->IsUndefined()) {
return Nan::ThrowTypeError("Requires a render backend name");
}
const std::string backendName { *Nan::Utf8String(info[0]) };
const std::string backendName{*Nan::Utf8String(info[0])};
(void)backendName;
}
void RegisterModule(v8::Local<v8::Object> target, v8::Local<v8::Object> module) {
// This has the effect of:
// a) Ensuring that the static local variable is initialized before any thread contention.
// b) unreffing an async handle, which otherwise would keep the default loop running.
// a) Ensuring that the static local variable is initialized before any
// thread contention. b) unreffing an async handle, which otherwise would
// keep the default loop running.
static mbgl::util::RunLoop nodeRunLoop;
nodeRunLoop.stop();
@@ -40,54 +40,35 @@ void RegisterModule(v8::Local<v8::Object> target, v8::Local<v8::Object> module)
// Exports Resource constants.
v8::Local<v8::Object> resource = Nan::New<v8::Object>();
Nan::Set(resource,
Nan::New("Unknown").ToLocalChecked(),
Nan::New(mbgl::Resource::Unknown));
Nan::Set(resource, Nan::New("Unknown").ToLocalChecked(), Nan::New(mbgl::Resource::Unknown));
Nan::Set(resource,
Nan::New("Style").ToLocalChecked(),
Nan::New(mbgl::Resource::Style));
Nan::Set(resource, Nan::New("Style").ToLocalChecked(), Nan::New(mbgl::Resource::Style));
Nan::Set(resource,
Nan::New("Source").ToLocalChecked(),
Nan::New(mbgl::Resource::Source));
Nan::Set(resource, Nan::New("Source").ToLocalChecked(), Nan::New(mbgl::Resource::Source));
Nan::Set(resource,
Nan::New("Tile").ToLocalChecked(),
Nan::New(mbgl::Resource::Tile));
Nan::Set(resource, Nan::New("Tile").ToLocalChecked(), Nan::New(mbgl::Resource::Tile));
Nan::Set(resource,
Nan::New("Glyphs").ToLocalChecked(),
Nan::New(mbgl::Resource::Glyphs));
Nan::Set(resource, Nan::New("Glyphs").ToLocalChecked(), Nan::New(mbgl::Resource::Glyphs));
Nan::Set(resource,
Nan::New("SpriteImage").ToLocalChecked(),
Nan::New(mbgl::Resource::SpriteImage));
Nan::Set(resource, Nan::New("SpriteImage").ToLocalChecked(), Nan::New(mbgl::Resource::SpriteImage));
Nan::Set(resource,
Nan::New("SpriteJSON").ToLocalChecked(),
Nan::New(mbgl::Resource::SpriteJSON));
Nan::Set(resource, Nan::New("SpriteJSON").ToLocalChecked(), Nan::New(mbgl::Resource::SpriteJSON));
Nan::Set(target,
Nan::New("Resource").ToLocalChecked(),
resource);
Nan::Set(target, Nan::New("Resource").ToLocalChecked(), resource);
// Make the exported object inherit from EventEmitter
v8::Local<v8::Function> require = Nan::Get(module,
Nan::New("require").ToLocalChecked()).ToLocalChecked().As<v8::Function>();
v8::Local<v8::Function> require =
Nan::Get(module, Nan::New("require").ToLocalChecked()).ToLocalChecked().As<v8::Function>();
v8::Local<v8::Value> eventsString = Nan::New("events").ToLocalChecked();
v8::Local<v8::Object> events = Nan::To<v8::Object>(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Object> events =
Nan::To<v8::Object>(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Object> EventEmitter = Nan::To<v8::Object>(
Nan::Get(
events,
Nan::New("EventEmitter").ToLocalChecked()
).ToLocalChecked()
).ToLocalChecked();
v8::Local<v8::Object> EventEmitter =
Nan::To<v8::Object>(Nan::Get(events, Nan::New("EventEmitter").ToLocalChecked()).ToLocalChecked())
.ToLocalChecked();
Nan::SetPrototype(target,
Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked());
Nan::SetPrototype(target, Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked());
Nan::CallAsFunction(EventEmitter, target, 0, nullptr);
mbgl::Log::setObserver(std::make_unique<node_mbgl::NodeLogObserver>(target));

View File

@@ -7,12 +7,10 @@
namespace node_mbgl {
NodeRequest::NodeRequest(
mbgl::FileSource::Callback callback_,
NodeAsyncRequest* asyncRequest_)
NodeRequest::NodeRequest(mbgl::FileSource::Callback callback_, NodeAsyncRequest* asyncRequest_)
: callback(std::move(callback_)),
asyncRequest(asyncRequest_) {
asyncRequest->request = this;
asyncRequest(asyncRequest_) {
asyncRequest->request = this;
}
NodeRequest::~NodeRequest() {
@@ -53,13 +51,9 @@ void NodeRequest::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
request->Ref();
Nan::Set(info.This(), Nan::New("url").ToLocalChecked(), info[3]);
Nan::Set(info.This(), Nan::New("kind").ToLocalChecked(), info[4]);
v8::Local<v8::Value> argv[] = { info.This() };
v8::Local<v8::Value> argv[] = {info.This()};
request->asyncResource->runInAsyncScope(
Nan::To<v8::Object>(target->handle()->GetInternalField(1)).ToLocalChecked(),
"request",
1,
argv
);
Nan::To<v8::Object>(target->handle()->GetInternalField(1)).ToLocalChecked(), "request", 1, argv);
info.GetReturnValue().Set(info.This());
}
@@ -84,15 +78,11 @@ void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo<v8::Value>& inf
if (Nan::Has(err, msg).FromJust()) {
response.error = std::make_unique<mbgl::Response::Error>(
mbgl::Response::Error::Reason::Other,
*Nan::Utf8String(Nan::Get(err, msg).ToLocalChecked())
);
mbgl::Response::Error::Reason::Other, *Nan::Utf8String(Nan::Get(err, msg).ToLocalChecked()));
}
} else if (info[0]->IsString()) {
response.error = std::make_unique<mbgl::Response::Error>(
mbgl::Response::Error::Reason::Other,
*Nan::Utf8String(info[0])
);
response.error = std::make_unique<mbgl::Response::Error>(mbgl::Response::Error::Reason::Other,
*Nan::Utf8String(info[0]));
} else if (info.Length() < 2 || !info[1]->IsObject()) {
request->unrefRequest();
return Nan::ThrowTypeError("Second argument must be a response object");
@@ -100,33 +90,30 @@ void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo<v8::Value>& inf
auto res = Nan::To<v8::Object>(info[1]).ToLocalChecked();
if (Nan::Has(res, Nan::New("modified").ToLocalChecked()).FromJust()) {
const double modified = Nan::To<double>(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust();
const double modified =
Nan::To<double>(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust();
if (!std::isnan(modified)) {
response.modified = mbgl::Timestamp{ mbgl::Seconds(
static_cast<mbgl::Seconds::rep>(modified / 1000)) };
response.modified = mbgl::Timestamp{mbgl::Seconds(static_cast<mbgl::Seconds::rep>(modified / 1000))};
}
}
if (Nan::Has(res, Nan::New("expires").ToLocalChecked()).FromJust()) {
const double expires = Nan::To<double>(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust();
const double expires =
Nan::To<double>(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust();
if (!std::isnan(expires)) {
response.expires = mbgl::Timestamp{ mbgl::Seconds(
static_cast<mbgl::Seconds::rep>(expires / 1000)) };
response.expires = mbgl::Timestamp{mbgl::Seconds(static_cast<mbgl::Seconds::rep>(expires / 1000))};
}
}
if (Nan::Has(res, Nan::New("etag").ToLocalChecked()).FromJust()) {
const Nan::Utf8String etag(Nan::Get(res, Nan::New("etag").ToLocalChecked()).ToLocalChecked());
response.etag = std::string { *etag, size_t(etag.length()) };
response.etag = std::string{*etag, size_t(etag.length())};
}
if (Nan::Has(res, Nan::New("data").ToLocalChecked()).FromJust()) {
auto data = Nan::Get(res, Nan::New("data").ToLocalChecked()).ToLocalChecked();
if (node::Buffer::HasInstance(data)) {
response.data = std::make_shared<std::string>(
node::Buffer::Data(data),
node::Buffer::Length(data)
);
response.data = std::make_shared<std::string>(node::Buffer::Data(data), node::Buffer::Length(data));
} else {
request->unrefRequest();
return Nan::ThrowTypeError("Response data must be a Buffer");

View File

@@ -21,9 +21,7 @@ struct NodeAsyncRequest : public mbgl::AsyncRequest {
};
class NodeRequest : public Nan::ObjectWrap {
public:
NodeRequest(mbgl::FileSource::Callback, NodeAsyncRequest*);
~NodeRequest() override;

View File

@@ -15,9 +15,10 @@ namespace util {
template <typename T>
class AsyncQueue {
public:
AsyncQueue(uv_loop_t *loop, std::function<void(T &)> fn) : callback(std::move(fn)) {
AsyncQueue(uv_loop_t *loop, std::function<void(T &)> fn)
: callback(std::move(fn)) {
async.data = this;
uv_async_init(loop, &async, [](uv_async_t* handle) {
uv_async_init(loop, &async, [](uv_async_t *handle) {
auto q = reinterpret_cast<AsyncQueue *>(handle->data);
q->process();
});