[general] moving ios and android project under ./platform folder

This commit is contained in:
Petr Pokorny
2020-12-20 12:38:56 +01:00
parent 8e759a51e4
commit 41f0be34e7
9877 changed files with 141 additions and 2889 deletions

View File

@@ -0,0 +1,146 @@
#pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
#include <mbgl/util/optional.hpp>
#include <mbgl/util/feature.hpp>
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/style/conversion_impl.hpp>
namespace mbgl {
namespace style {
namespace conversion {
template <>
class ConversionTraits<v8::Local<v8::Value>> {
public:
static bool isUndefined(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
return value->IsUndefined() || value->IsNull();
}
static bool isArray(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
return value->IsArray();
}
static std::size_t arrayLength(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
// const_cast because v8::Local<T>::As is not marked const until node v8.0
v8::Local<v8::Array> array = const_cast<v8::Local<v8::Value>&>(value).As<v8::Array>();
return array->Length();
}
static v8::Local<v8::Value> arrayMember(const v8::Local<v8::Value>& value, std::size_t i) {
Nan::EscapableHandleScope scope;
// const_cast because v8::Local<T>::As is not marked const until node v8.0
v8::Local<v8::Array> array = const_cast<v8::Local<v8::Value>&>(value).As<v8::Array>();
return scope.Escape(Nan::Get(array, i).ToLocalChecked());
}
static bool isObject(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
return value->IsObject() && !value->IsArray();
}
static 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());
if (result.IsEmpty()) {
return {};
}
return {scope.Escape(result.ToLocalChecked())};
}
template <class Fn>
static 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();
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();
optional<Error> result = fn(*Nan::Utf8String(k), std::move(v)); // NOLINT(performance-move-const-arg)
if (result) {
return result;
}
}
return {};
}
static optional<bool> toBool(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsBoolean()) {
return {};
}
return value->BooleanValue();
}
static optional<float> toNumber(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsNumber()) {
return {};
}
return value->NumberValue();
}
static optional<double> toDouble(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsNumber()) {
return {};
}
return value->NumberValue();
}
static optional<std::string> toString(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsString()) {
return {};
}
return std::string(*Nan::Utf8String(value));
}
static optional<Value> toValue(const v8::Local<v8::Value>& value) {
if (value->IsFalse()) {
return { false };
} else if (value->IsTrue()) {
return { true };
} else if (value->IsString()) {
return { std::string(*Nan::Utf8String(value)) };
} else if (value->IsUint32()) {
return { std::uint64_t(value->Uint32Value()) };
} else if (value->IsInt32()) {
return { std::int64_t(value->Int32Value()) };
} else if (value->IsNumber()) {
return { value->NumberValue() };
} else {
return {};
}
}
static optional<GeoJSON> toGeoJSON(const v8::Local<v8::Value>& value, Error& error) {
try {
Nan::JSON JSON;
std::string string = *Nan::Utf8String(JSON.Stringify(value->ToObject()).ToLocalChecked());
return parseGeoJSON(string, error);
} catch (const std::exception& ex) {
error = { ex.what() };
return {};
}
}
};
template <class T, class...Args>
optional<T> convert(const v8::Local<v8::Value>& value, Error& error, Args&&...args) {
return convert<T>(Convertible(value), error, std::forward<Args>(args)...);
}
} // namespace conversion
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,302 @@
#include "node_conversion.hpp"
#include "node_expression.hpp"
#include "node_feature.hpp"
#include <mbgl/style/expression/parsing_context.hpp>
#include <mbgl/style/expression/is_constant.hpp>
#include <mbgl/style/conversion/function.hpp>
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/util/geojson.hpp>
#include <nan.h>
using namespace mbgl::style;
using namespace mbgl::style::expression;
namespace node_mbgl {
Nan::Persistent<v8::Function> NodeExpression::constructor;
void NodeExpression::Init(v8::Local<v8::Object> target) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Expression").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1); // what is this doing?
Nan::SetPrototypeMethod(tpl, "evaluate", Evaluate);
Nan::SetPrototypeMethod(tpl, "getType", GetType);
Nan::SetPrototypeMethod(tpl, "isFeatureConstant", IsFeatureConstant);
Nan::SetPrototypeMethod(tpl, "isZoomConstant", IsZoomConstant);
Nan::SetPrototypeMethod(tpl, "serialize", Serialize);
Nan::SetMethod(tpl, "parse", Parse);
constructor.Reset(tpl->GetFunction()); // what is this doing?
Nan::Set(target, Nan::New("Expression").ToLocalChecked(), tpl->GetFunction());
}
type::Type parseType(v8::Local<v8::Object> type) {
static std::unordered_map<std::string, type::Type> types = {{"string", type::String},
{"number", type::Number},
{"boolean", type::Boolean},
{"object", type::Object},
{"color", type::Color},
{"value", type::Value},
{"formatted", type::Formatted},
{"number-format", type::String},
{"resolvedImage", type::Image}};
v8::Local<v8::Value> v8kind = Nan::Get(type, Nan::New("kind").ToLocalChecked()).ToLocalChecked();
std::string kind(*v8::String::Utf8Value(v8kind));
if (kind == "array") {
type::Type itemType = parseType(Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject());
mbgl::optional<std::size_t> N;
v8::Local<v8::String> Nkey = Nan::New("N").ToLocalChecked();
if (Nan::Has(type, Nkey).FromMaybe(false)) {
N = Nan::To<v8::Int32>(Nan::Get(type, Nkey).ToLocalChecked()).ToLocalChecked()->Value();
}
return type::Array(itemType, N);
}
return types[kind];
}
void NodeExpression::Parse(const Nan::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Function> cons = Nan::New(constructor);
if (info.Length() < 1 || info[0]->IsUndefined()) {
return Nan::ThrowTypeError("Requires a JSON style expression argument.");
}
mbgl::optional<type::Type> expected;
if (info.Length() > 1 && info[1]->IsObject()) {
expected = parseType(info[1]->ToObject());
}
auto success = [&cons, &info](std::unique_ptr<Expression> result) {
auto nodeExpr = new NodeExpression(std::move(result));
const int argc = 0;
v8::Local<v8::Value> argv[0] = {};
auto wrapped = Nan::NewInstance(cons, argc, argv).ToLocalChecked();
nodeExpr->Wrap(wrapped);
info.GetReturnValue().Set(wrapped);
};
auto fail = [&info](const std::vector<ParsingError>& errors) {
v8::Local<v8::Array> result = Nan::New<v8::Array>();
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(result, Nan::New(static_cast<uint32_t>(i)), err);
}
info.GetReturnValue().Set(result);
};
auto expr = info[0];
try {
mbgl::style::conversion::Convertible convertible(expr);
if (expr->IsObject() && !expr->IsArray() && expected) {
mbgl::style::conversion::Error error;
auto func = convertFunctionToExpression(*expected, convertible, error, false);
if (func) {
return success(std::move(*func));
}
return fail({ { error.message, "" } });
}
ParsingContext ctx = expected ? ParsingContext(*expected) : ParsingContext();
ParseResult parsed = ctx.parseLayerPropertyExpression(mbgl::style::conversion::Convertible(expr));
if (parsed) {
assert(ctx.getErrors().empty());
return success(std::move(*parsed));
}
return fail(ctx.getErrors());
} catch(std::exception &ex) {
return Nan::ThrowError(ex.what());
}
}
void NodeExpression::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to create new Expression objects");
}
info.GetReturnValue().Set(info.This());
}
struct ToValue {
v8::Local<v8::Value> operator()(mbgl::NullValue) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
v8::Local<v8::Value> operator()(bool t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(double t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(const std::string& t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t).ToLocalChecked());
}
v8::Local<v8::Value> operator()(const std::vector<Value>& array) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>();
for (std::size_t i = 0; i < array.size(); i++) {
result->Set(i, toJS(array[i]));
}
return scope.Escape(result);
}
v8::Local<v8::Value> operator()(const Collator&) {
// Collators are excluded from constant folding and there's no Literal parser
// for them so there shouldn't be any way to serialize this value.
assert(false);
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
v8::Local<v8::Value> operator()(const Formatted& formatted) {
// This mimics the internal structure of the Formatted class in formatted.js
// A better approach might be to use the explicit serialized form
// both here and on the JS side? e.g. toJS(fromExpressionValue<mbgl::Value>(formatted))
std::unordered_map<std::string, mbgl::Value> serialized;
std::vector<mbgl::Value> sections;
for (const auto& section : formatted.sections) {
std::unordered_map<std::string, mbgl::Value> serializedSection;
serializedSection.emplace("text", section.text);
if (section.fontScale) {
serializedSection.emplace("scale", *section.fontScale);
} else {
serializedSection.emplace("scale", mbgl::NullValue());
}
if (section.fontStack) {
std::string fontStackString;
serializedSection.emplace("fontStack", mbgl::fontStackToString(*section.fontStack));
} else {
serializedSection.emplace("fontStack", mbgl::NullValue());
}
if (section.textColor) {
serializedSection.emplace("textColor", section.textColor->toObject());
} else {
serializedSection.emplace("textColor", mbgl::NullValue());
}
sections.emplace_back(serializedSection);
}
serialized.emplace("sections", sections);
return toJS(serialized);
}
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)
});
}
v8::Local<v8::Value> operator()(const std::unordered_map<std::string, Value>& map) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
for (const auto& entry : map) {
Nan::Set(result, Nan::New(entry.first).ToLocalChecked(), toJS(entry.second));
}
return scope.Escape(result);
}
v8::Local<v8::Value> operator()(const Image& image) { return toJS(image.toValue()); }
};
v8::Local<v8::Value> toJS(const Value& value) {
return Value::visit(value, ToValue());
}
void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
if (info.Length() < 2 || !info[0]->IsObject()) {
return Nan::ThrowTypeError("Requires globals and feature arguments.");
}
mbgl::optional<float> zoom;
v8::Local<v8::Value> v8zoom = Nan::Get(info[0]->ToObject(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked();
if (v8zoom->IsNumber()) zoom = v8zoom->NumberValue();
mbgl::optional<double> heatmapDensity;
v8::Local<v8::Value> v8heatmapDensity = Nan::Get(info[0]->ToObject(), Nan::New("heatmapDensity").ToLocalChecked()).ToLocalChecked();
if (v8heatmapDensity->IsNumber()) heatmapDensity = v8heatmapDensity->NumberValue();
Nan::JSON NanJSON;
conversion::Error conversionError;
mbgl::optional<mbgl::GeoJSON> geoJSON = conversion::convert<mbgl::GeoJSON>(info[1], conversionError);
if (!geoJSON) {
Nan::ThrowTypeError(conversionError.message.c_str());
return;
}
try {
mapbox::geojson::feature feature = geoJSON->get<mapbox::geojson::feature>();
auto result = expression->evaluate(zoom, feature, heatmapDensity);
if (result) {
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());
info.GetReturnValue().Set(res);
}
} catch(std::exception &ex) {
return Nan::ThrowTypeError(ex.what());
}
}
void NodeExpression::GetType(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
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(); });
info.GetReturnValue().Set(Nan::New(name.c_str()).ToLocalChecked());
}
void NodeExpression::IsFeatureConstant(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
info.GetReturnValue().Set(Nan::New(isFeatureConstant(*expression)));
}
void NodeExpression::IsZoomConstant(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
info.GetReturnValue().Set(Nan::New(isZoomConstant(*expression)));
}
void NodeExpression::Serialize(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
const mbgl::Value serialized = expression->serialize();
info.GetReturnValue().Set(toJS(serialized));
}
} // namespace node_mbgl

View File

@@ -0,0 +1,40 @@
#pragma once
#include <mbgl/style/conversion_impl.hpp>
#include <mbgl/style/expression/expression.hpp>
#include <exception>
#include <memory>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace node_mbgl {
v8::Local<v8::Value> toJS(const mbgl::style::expression::Value&);
class NodeExpression : public Nan::ObjectWrap {
public:
static void Init(v8::Local<v8::Object>);
private:
NodeExpression(std::unique_ptr<mbgl::style::expression::Expression> expression_)
: expression(std::move(expression_)){};
static void New(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Parse(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Evaluate(const Nan::FunctionCallbackInfo<v8::Value>&);
static void GetType(const Nan::FunctionCallbackInfo<v8::Value>&);
static void IsFeatureConstant(const Nan::FunctionCallbackInfo<v8::Value>&);
static void IsZoomConstant(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Serialize(const Nan::FunctionCallbackInfo<v8::Value>&);
static Nan::Persistent<v8::Function> constructor;
std::unique_ptr<mbgl::style::expression::Expression> expression;
};
} // namespace node_mbgl

View File

@@ -0,0 +1,179 @@
#include "node_feature.hpp"
namespace node_mbgl {
using namespace mapbox::geometry;
using Value = mbgl::Value;
using Feature = mbgl::Feature;
using FeatureIdentifier = mbgl::FeatureIdentifier;
using Geometry = mbgl::Feature::geometry_type;
using GeometryCollection = mapbox::geometry::geometry_collection<double>;
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 point<T>&) {
return type("Point");
}
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 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_polygon<T>&) {
return type("MultiPolygon");
}
v8::Local<v8::String> operator()(const geometry_collection<T>&) {
return type("GeometryCollection");
}
private:
v8::Local<v8::String> type(const char* type_) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(type_).ToLocalChecked());
}
};
template <class T>
struct ToCoordinatesOrGeometries {
public:
// 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;
v8::Local<v8::Array> result = Nan::New<v8::Array>(vector.size());
for (std::size_t i = 0; i < vector.size(); ++i) {
Nan::Set(result, i, operator()(vector[i]));
}
return scope.Escape(result);
}
v8::Local<v8::Object> operator()(const point<T>& point) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>(2);
Nan::Set(result, 0, Nan::New(point.x));
Nan::Set(result, 1, Nan::New(point.y));
return scope.Escape(result);
}
v8::Local<v8::Object> operator()(const geometry<T>& geometry) {
return toJS(geometry);
}
};
struct ToValue {
v8::Local<v8::Value> operator()(mbgl::NullValue) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
v8::Local<v8::Value> operator()(bool t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(int64_t t) {
return operator()(double(t));
}
v8::Local<v8::Value> operator()(uint64_t t) {
return operator()(double(t));
}
v8::Local<v8::Value> operator()(double t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(const std::string& t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t).ToLocalChecked());
}
v8::Local<v8::Value> operator()(const std::vector<mbgl::Value>& array) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>();
for (std::size_t i = 0; i < array.size(); i++) {
result->Set(i, toJS(array[i]));
}
return scope.Escape(result);
}
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) {
Nan::EscapableHandleScope scope;
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(geometry.is<GeometryCollection>() ? "geometries" : "coordinates").ToLocalChecked(),
Geometry::visit(geometry, ToCoordinatesOrGeometries<double>()));
return scope.Escape(result);
}
v8::Local<v8::Value> toJS(const Value& value) {
return Value::visit(value, ToValue());
}
v8::Local<v8::Object> toJS(const Properties& properties) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
for (const auto& property : properties) {
Nan::Set(result, Nan::New(property.first).ToLocalChecked(), toJS(property.second));
}
return scope.Escape(result);
}
v8::Local<v8::Object> toJS(const Feature& feature) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
Nan::Set(result, Nan::New("type").ToLocalChecked(), Nan::New("Feature").ToLocalChecked());
Nan::Set(result, Nan::New("geometry").ToLocalChecked(), toJS(feature.geometry));
Nan::Set(result, Nan::New("properties").ToLocalChecked(), toJS(feature.properties));
if (!feature.id.is<mbgl::NullValue>()) {
Nan::Set(result, Nan::New("id").ToLocalChecked(), FeatureIdentifier::visit(feature.id, ToValue()));
}
Nan::Set(result, Nan::New("source").ToLocalChecked(), toJS(feature.source));
if (!feature.sourceLayer.empty()) {
Nan::Set(result, Nan::New("sourceLayer").ToLocalChecked(), toJS(feature.sourceLayer));
}
Nan::Set(result, Nan::New("state").ToLocalChecked(), toJS(feature.state));
return scope.Escape(result);
}
} // namespace node_mbgl

View File

@@ -0,0 +1,18 @@
#pragma once
#include <mbgl/util/feature.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace node_mbgl {
v8::Local<v8::Value> toJS(const mbgl::Value&);
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&);
}

View File

@@ -0,0 +1,63 @@
#include "node_logging.hpp"
#include <mbgl/util/enum.hpp>
namespace node_mbgl {
struct NodeLogObserver::LogMessage {
mbgl::EventSeverity severity;
mbgl::Event event;
int64_t code;
std::string text;
LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_)
: severity(severity_),
event(event_),
code(code_),
text(std::move(text_)) {}
};
NodeLogObserver::NodeLogObserver(v8::Local<v8::Object> target)
: queue(new util::AsyncQueue<LogMessage>(uv_default_loop(), [this](LogMessage &message) {
Nan::HandleScope scope;
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("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));
}
if (!message.text.empty()) {
Nan::Set(msg, Nan::New("text").ToLocalChecked(),
Nan::New(message.text).ToLocalChecked());
}
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();
Nan::CallAsFunction(emit, handle, 2, argv);
})) {
Nan::HandleScope scope;
module.Reset(target);
// Don't keep the event loop alive.
queue->unref();
}
NodeLogObserver::~NodeLogObserver() {
queue->stop();
}
bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) {
queue->send({ severity, event, code, text });
return true;
}
} // namespace node_mbgl

View File

@@ -0,0 +1,32 @@
#pragma once
#include "util/async_queue.hpp"
#include <mbgl/util/logging.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace node_mbgl {
namespace util { template <typename T> class AsyncQueue; }
class NodeLogObserver : public mbgl::Log::Observer {
public:
NodeLogObserver(v8::Local<v8::Object> target);
~NodeLogObserver() override;
// Log::Observer implementation
bool onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string& text) override;
private:
Nan::Persistent<v8::Object> module;
struct LogMessage;
util::AsyncQueue<LogMessage>* queue;
};
} // namespace node_mbgl

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,106 @@
#pragma once
#include <mbgl/map/map.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/util/async_request.hpp>
#include <mbgl/util/image.hpp>
#include <exception>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace mbgl {
class HeadlessFrontend;
} // namespace mbgl
namespace node_mbgl {
struct NodeMapObserver : public mbgl::MapObserver {
void onDidFailLoadingMap(mbgl::MapLoadError, const std::string&) final;
};
class RenderRequest;
class NodeMap : public Nan::ObjectWrap {
public:
struct RenderOptions;
class RenderWorker;
NodeMap(v8::Local<v8::Object>);
~NodeMap() override;
static Nan::Persistent<v8::Function> constructor;
static Nan::Persistent<v8::Object> parseError;
static void Init(v8::Local<v8::Object>);
static void New(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Load(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Loaded(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Render(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Release(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Cancel(const Nan::FunctionCallbackInfo<v8::Value>&);
static void AddSource(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveSource(const Nan::FunctionCallbackInfo<v8::Value>&);
static void AddLayer(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveLayer(const Nan::FunctionCallbackInfo<v8::Value>&);
static void AddImage(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveImage(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetLayerZoomRange(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetLayerProperty(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetFilter(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetCenter(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetZoom(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetBearing(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetPitch(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetLight(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetAxonometric(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetXSkew(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetYSkew(const Nan::FunctionCallbackInfo<v8::Value>&);
static void DumpDebugLogs(const Nan::FunctionCallbackInfo<v8::Value>&);
static void QueryRenderedFeatures(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetFeatureState(const Nan::FunctionCallbackInfo<v8::Value>&);
static void GetFeatureState(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveFeatureState(const Nan::FunctionCallbackInfo<v8::Value>&);
static v8::Local<v8::Value> ParseError(const char* msg);
void startRender(const RenderOptions& options);
void renderFinished();
void release();
void cancel();
static RenderOptions ParseOptions(v8::Local<v8::Object>);
const float pixelRatio;
mbgl::MapMode mode;
bool crossSourceCollisions;
NodeMapObserver mapObserver;
std::unique_ptr<mbgl::HeadlessFrontend> frontend;
std::unique_ptr<mbgl::Map> map;
std::exception_ptr error;
mbgl::PremultipliedImage image;
std::unique_ptr<RenderRequest> req;
// Async for delivering the notifications of render completion.
uv_async_t *async;
bool loaded = false;
};
struct NodeFileSource : public mbgl::FileSource {
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;
NodeMap* nodeMap;
};
} // namespace node_mbgl

View File

@@ -0,0 +1,95 @@
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <node.h>
#include <nan.h>
#pragma GCC diagnostic pop
#include <mbgl/util/run_loop.hpp>
#include <mbgl/gfx/backend.hpp>
#include "node_map.hpp"
#include "node_logging.hpp"
#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]) };
(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.
static mbgl::util::RunLoop nodeRunLoop;
nodeRunLoop.stop();
Nan::SetMethod(target, "setBackendType", SetBackendType);
node_mbgl::NodeMap::Init(target);
node_mbgl::NodeRequest::Init();
node_mbgl::NodeExpression::Init(target);
// 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("Style").ToLocalChecked(),
Nan::New(mbgl::Resource::Style));
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("Glyphs").ToLocalChecked(),
Nan::New(mbgl::Resource::Glyphs));
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(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::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> 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::CallAsFunction(EventEmitter, target, 0, nullptr);
mbgl::Log::setObserver(std::make_unique<node_mbgl::NodeLogObserver>(target));
}
NODE_MODULE(mapbox_gl_native, RegisterModule)

View File

@@ -0,0 +1,153 @@
#include "node_request.hpp"
#include "node_map.hpp"
#include <mbgl/storage/response.hpp>
#include <mbgl/util/chrono.hpp>
#include <cmath>
namespace node_mbgl {
NodeRequest::NodeRequest(
mbgl::FileSource::Callback callback_,
NodeAsyncRequest* asyncRequest_)
: callback(std::move(callback_)),
asyncRequest(asyncRequest_) {
asyncRequest->request = this;
}
NodeRequest::~NodeRequest() {
// When this object gets garbage collected, make sure that the
// AsyncRequest can no longer attempt to remove the callback function
// this object was holding (it can't be fired anymore).
if (asyncRequest) {
asyncRequest->request = nullptr;
}
}
Nan::Persistent<v8::Function> NodeRequest::constructor;
void NodeRequest::Init() {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New("Request").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "respond", HandleCallback);
constructor.Reset(tpl->GetFunction());
}
void NodeRequest::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto target = reinterpret_cast<NodeMap*>(info[0].As<v8::External>()->Value());
auto callback = reinterpret_cast<mbgl::FileSource::Callback*>(info[1].As<v8::External>()->Value());
auto asyncRequest = reinterpret_cast<NodeAsyncRequest*>(info[2].As<v8::External>()->Value());
auto request = new NodeRequest(*callback, asyncRequest);
request->Wrap(info.This());
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() };
request->asyncResource->runInAsyncScope(Nan::To<v8::Object>(target->handle()->GetInternalField(1)).ToLocalChecked(), "request", 1, argv);
info.GetReturnValue().Set(info.This());
}
void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto request = Nan::ObjectWrap::Unwrap<NodeRequest>(info.Holder());
// Move out of the object so callback() can only be fired once.
auto callback = std::move(request->callback);
request->callback = {};
if (!callback) {
request->unrefRequest();
return info.GetReturnValue().SetUndefined();
}
mbgl::Response response;
if (info.Length() < 1) {
response.noContent = true;
} else if (info[0]->IsObject()) {
auto err = Nan::To<v8::Object>(info[0]).ToLocalChecked();
auto msg = Nan::New("message").ToLocalChecked();
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())
);
}
} else if (info[0]->IsString()) {
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");
} else {
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();
if (!std::isnan(modified)) {
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();
if (!std::isnan(expires)) {
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()) };
}
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)
);
} else {
request->unrefRequest();
return Nan::ThrowTypeError("Response data must be a Buffer");
}
}
}
// Send the response object to the NodeFileSource object
callback(response);
request->unrefRequest();
info.GetReturnValue().SetUndefined();
}
void NodeRequest::unrefRequest() {
Nan::HandleScope scope;
delete asyncResource;
asyncResource = nullptr;
Unref();
}
NodeAsyncRequest::NodeAsyncRequest() = default;
NodeAsyncRequest::~NodeAsyncRequest() {
if (request) {
// Remove the callback function because the AsyncRequest was
// canceled and we are no longer interested in the result.
if (request->callback) {
request->callback = {};
}
request->asyncRequest = nullptr;
}
}
} // namespace node_mbgl

View File

@@ -0,0 +1,44 @@
#pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
#include <mbgl/storage/file_source.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/util/async_request.hpp>
namespace node_mbgl {
class NodeRequest;
struct NodeAsyncRequest : public mbgl::AsyncRequest {
NodeAsyncRequest();
~NodeAsyncRequest() override;
NodeRequest* request = nullptr;
};
class NodeRequest : public Nan::ObjectWrap {
public:
NodeRequest(mbgl::FileSource::Callback, NodeAsyncRequest*);
~NodeRequest() override;
static Nan::Persistent<v8::Function> constructor;
static void Init();
static void New(const Nan::FunctionCallbackInfo<v8::Value>&);
static void HandleCallback(const Nan::FunctionCallbackInfo<v8::Value>&);
void unrefRequest();
mbgl::FileSource::Callback callback;
NodeAsyncRequest* asyncRequest;
Nan::AsyncResource* asyncResource = new Nan::AsyncResource("mbgl:execute");
};
} // namespace node_mbgl

View File

@@ -0,0 +1,76 @@
#pragma once
#include <uv.h>
#include <functional>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <utility>
namespace node_mbgl {
namespace util {
template <typename T>
class AsyncQueue {
public:
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) {
auto q = reinterpret_cast<AsyncQueue *>(handle->data);
q->process();
});
}
~AsyncQueue() = default;
void send(T &&data) {
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::make_unique<T>(std::move(data)));
}
uv_async_send(&async);
}
void send(std::unique_ptr<T> data) {
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::move(data));
}
uv_async_send(&async);
}
void stop() {
uv_close(reinterpret_cast<uv_handle_t *>(&async),
[](uv_handle_t *handle) { delete reinterpret_cast<AsyncQueue *>(handle->data); });
}
void ref() { uv_ref(reinterpret_cast<uv_handle_t *>(&async)); }
void unref() { uv_unref(reinterpret_cast<uv_handle_t *>(&async)); }
private:
void process() {
std::unique_ptr<T> item;
while (true) {
mutex.lock();
if (queue.empty()) {
mutex.unlock();
break;
}
item = std::move(queue.front());
queue.pop();
mutex.unlock();
callback(*item);
}
}
private:
std::mutex mutex;
uv_async_t async;
std::queue<std::unique_ptr<T>> queue;
std::function<void(T &)> callback;
};
} // namespace util
} // namespace node_mbgl