summaryrefslogtreecommitdiff
path: root/src/mbgl/style/sources/geojson_source.cpp
blob: 2ac80517afe5f1a15ebac4dcf4f56913da532baf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#include <mbgl/storage/file_source.hpp>
#include <mbgl/style/conversion/constant.hpp>
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/style/conversion/geojson_options.hpp>
#include <mbgl/style/conversion/json.hpp>
#include <mbgl/style/conversion_impl.hpp>
#include <mbgl/style/layer.hpp>
#include <mbgl/style/source_observer.hpp>
#include <mbgl/style/sources/geojson_source.hpp>
#include <mbgl/style/sources/geojson_source_impl.hpp>
#include <mbgl/tile/tile.hpp>
#include <mbgl/util/async_request.hpp>
#include <mbgl/util/logging.hpp>
#include <mbgl/util/thread_pool.hpp>

namespace mbgl {
namespace style {

// static
Immutable<GeoJSONOptions> GeoJSONOptions::defaultOptions() {
    static Immutable<GeoJSONOptions> options = makeMutable<GeoJSONOptions>();
    return options;
}

GeoJSONSource::GeoJSONSource(std::string id, Immutable<GeoJSONOptions> options)
    : Source(makeMutable<Impl>(std::move(id), std::move(options))), threadPool(Scheduler::GetBackground()) {}

GeoJSONSource::~GeoJSONSource() = default;

const GeoJSONSource::Impl& GeoJSONSource::impl() const {
    return static_cast<const Impl&>(*baseImpl);
}

void GeoJSONSource::setURL(const std::string& url_) {
    url = url_;

    // Signal that the source description needs a reload
    if (loaded || req) {
        loaded = false;
        req.reset();
        observer->onSourceDescriptionChanged(*this);
    }
}

namespace {

inline std::shared_ptr<GeoJSONData> createGeoJSONData(const mapbox::geojson::geojson& geoJSON,
                                                      const GeoJSONSource::Impl& impl) {
    if (auto data = impl.getData().lock()) {
        return GeoJSONData::create(geoJSON, impl.getOptions(), data->getScheduler());
    }
    return GeoJSONData::create(geoJSON, impl.getOptions());
}

} // namespace

void GeoJSONSource::setGeoJSON(const mapbox::geojson::geojson& geoJSON) {
    setGeoJSONData(createGeoJSONData(geoJSON, impl()));
}

void GeoJSONSource::setGeoJSONData(std::shared_ptr<GeoJSONData> geoJSONData) {
    req.reset();
    baseImpl = makeMutable<Impl>(impl(), std::move(geoJSONData));
    observer->onSourceChanged(*this);
}

optional<Resource> GeoJSONSource::getResource() const {
    if (!url) return nullopt;
    return Resource::source(*url);
}

const GeoJSONData* GeoJSONSource::getGeoJSONData() const {
    auto data = impl().getData().lock();
    return data.get();
}

optional<std::string> GeoJSONSource::getURL() const {
    return url;
}

const GeoJSONOptions& GeoJSONSource::getOptions() const {
    return *impl().getOptions();
}

void GeoJSONSource::loadDescription(FileSource& fileSource) {
    if (!url) {
        loaded = true;
        return;
    }

    if (req) {
        return;
    }

    req = fileSource.request(Resource::source(*url), [this](const Response& res) {
        if (res.error) {
            observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message)));
        } else if (res.notModified) {
            return;
        } else if (res.noContent) {
            observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error("unexpectedly empty GeoJSON")));
        } else {
            auto makeImplInBackground = [currentImpl = baseImpl, data = res.data]() -> Immutable<Source::Impl> {
                assert(data);
                auto& current = static_cast<const Impl&>(*currentImpl);
                conversion::Error error;
                std::shared_ptr<GeoJSONData> geoJSONData;
                if (optional<GeoJSON> geoJSON = conversion::convertJSON<GeoJSON>(*data, error)) {
                    geoJSONData = createGeoJSONData(*geoJSON, current);
                } else {
                    // Create an empty GeoJSON VT object to make sure we're not infinitely waiting for tiles to load.
                    Log::Error(Event::ParseStyle, "Failed to parse GeoJSON data: %s", error.message.c_str());
                }
                return makeMutable<Impl>(current, std::move(geoJSONData));
            };
            auto onImplReady = [this, self = makeWeakPtr(), capturedReq = req.get()](Immutable<Source::Impl> newImpl) {
                assert(capturedReq);
                if (!self) return;                    // This source has been deleted.
                if (capturedReq != req.get()) return; // A new request is being processed, ignore this impl.

                baseImpl = std::move(newImpl);
                loaded = true;
                observer->onSourceLoaded(*this);
            };
            threadPool->scheduleAndReplyValue(makeImplInBackground, onImplReady);
        }
    });
}

bool GeoJSONSource::supportsLayerType(const mbgl::style::LayerTypeInfo* info) const {
    return mbgl::underlying_type(TileKind::Geometry) == mbgl::underlying_type(info->tileKind);
}

Mutable<Source::Impl> GeoJSONSource::createMutable() const noexcept {
    return staticMutableCast<Source::Impl>(makeMutable<Impl>(impl()));
}

optional<conversion::Error> GeoJSONSource::setPropertyInternal(const std::string& name,
                                                               const conversion::Convertible& value) {
    using namespace conversion;
    optional<Error> error = Source::setPropertyInternal(name, value);
    assert(error);
    if (name == "data") {
        if (isObject(value)) {
            if (auto geoJSON = convert<GeoJSON>(value, *error)) {
                setGeoJSON(*geoJSON);
                return nullopt;
            }
        } else if (auto url_ = convert<std::string>(value, *error)) {
            setURL(*url_);
            return nullopt;
        } else {
            error = Error{"GeoJSON data must be a URL or an object"};
        }
    }
    return error;
}

Value GeoJSONSource::getPropertyInternal(const std::string& name) const {
    using namespace conversion;
    if (name == "options") return makeValue(getOptions());
    return Value();
}

Value GeoJSONSource::getPropertyDefaultValueInternal(const std::string& name) const {
    using namespace conversion;
    if (name == "options") return makeValue(*GeoJSONOptions::defaultOptions());
    return Value();
}

Value GeoJSONSource::serialize() const {
    auto value = Source::serialize();
    assert(value.getObject());

    if (url.has_value()) {
        value.getObject()->insert({"data", url.value()});
    }

    return value;
}

} // namespace style
} // namespace mbgl