summaryrefslogtreecommitdiff
path: root/src/mbgl/text/glyph_store.cpp
blob: 72c7b16a846ddfa78aeb8a35b240d65d11022408 (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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#include <mbgl/text/glyph_store.hpp>

#include <mbgl/map/environment.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/platform/platform.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/exception.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/util/pbf.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/token.hpp>
#include <mbgl/util/url.hpp>
#include <mbgl/util/utf.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <mbgl/util/uv_detail.hpp>

#include <algorithm>
#include <sstream>

namespace mbgl {


void FontStack::insert(uint32_t id, const SDFGlyph &glyph) {
    metrics.emplace(id, glyph.metrics);
    bitmaps.emplace(id, glyph.bitmap);
    sdfs.emplace(id, glyph);
}

const std::map<uint32_t, GlyphMetrics> &FontStack::getMetrics() const {
    return metrics;
}

const std::map<uint32_t, SDFGlyph> &FontStack::getSDFs() const {
    return sdfs;
}

const Shaping FontStack::getShaping(const std::u32string &string, const float maxWidth,
                                    const float lineHeight, const float horizontalAlign,
                                    const float verticalAlign, const float justify,
                                    const float spacing, const vec2<float> &translate) const {
    Shaping shaping;

    int32_t x = std::round(translate.x * 24); // one em
    const int32_t y = std::round(translate.y * 24); // one em

    // Loop through all characters of this label and shape.
    for (uint32_t chr : string) {
        shaping.emplace_back(chr, x, y);
        auto metric = metrics.find(chr);
        if (metric != metrics.end()) {
            x += metric->second.advance + spacing;
        }
    }

    if (!shaping.size())
        return shaping;

    lineWrap(shaping, lineHeight, maxWidth, horizontalAlign, verticalAlign, justify);

    return shaping;
}

void align(Shaping &shaping, const float justify, const float horizontalAlign,
           const float verticalAlign, const uint32_t maxLineLength, const float lineHeight,
           const uint32_t line) {
    const float shiftX = (justify - horizontalAlign) * maxLineLength;
    const float shiftY = (-verticalAlign * (line + 1) + 0.5) * lineHeight;

    for (auto& glyph : shaping) {
        glyph.x += shiftX;
        glyph.y += shiftY;
    }
}

void justifyLine(Shaping &shaping, const std::map<uint32_t, GlyphMetrics> &metrics, uint32_t start,
                 uint32_t end, float justify) {
    PositionedGlyph &glyph = shaping[end];
    auto metric = metrics.find(glyph.glyph);
    if (metric != metrics.end()) {
        const uint32_t lastAdvance = metric->second.advance;
        const float lineIndent = float(glyph.x + lastAdvance) * justify;

        for (uint32_t j = start; j <= end; j++) {
            shaping[j].x -= lineIndent;
        }
    }
}

void FontStack::lineWrap(Shaping &shaping, const float lineHeight, const float maxWidth,
                         const float horizontalAlign, const float verticalAlign,
                         const float justify) const {
    uint32_t lastSafeBreak = 0;

    uint32_t lengthBeforeCurrentLine = 0;
    uint32_t lineStartIndex = 0;
    uint32_t line = 0;

    uint32_t maxLineLength = 0;

    if (maxWidth) {
        for (uint32_t i = 0; i < shaping.size(); i++) {
            PositionedGlyph &shape = shaping[i];

            shape.x -= lengthBeforeCurrentLine;
            shape.y += lineHeight * line;

            if (shape.x > maxWidth && lastSafeBreak > 0) {

                uint32_t lineLength = shaping[lastSafeBreak + 1].x;
                maxLineLength = util::max(lineLength, maxLineLength);

                for (uint32_t k = lastSafeBreak + 1; k <= i; k++) {
                    shaping[k].y += lineHeight;
                    shaping[k].x -= lineLength;
                }

                if (justify) {
                    justifyLine(shaping, metrics, lineStartIndex, lastSafeBreak - 1, justify);
                }

                lineStartIndex = lastSafeBreak + 1;
                lastSafeBreak = 0;
                lengthBeforeCurrentLine += lineLength;
                line++;
            }

            if (shape.glyph == 32) {
                lastSafeBreak = i;
            }
        }
    }

    if (!maxLineLength) maxLineLength = shaping.back().x;

    justifyLine(shaping, metrics, lineStartIndex, uint32_t(shaping.size()) - 1, justify);
    align(shaping, justify, horizontalAlign, verticalAlign, maxLineLength, lineHeight, line);
}

GlyphPBF::GlyphPBF(const std::string& glyphURL,
                   const std::string& fontStack,
                   GlyphRange glyphRange,
                   Environment& env_,
                   const GlyphLoadedCallback& successCallback,
                   const GlyphLoadingFailedCallback& failureCallback)
    : parsed(false), env(env_) {
    // Load the glyph set URL
    std::string url = util::replaceTokens(glyphURL, [&](const std::string &name) -> std::string {
        if (name == "fontstack") return util::percentEncode(fontStack);
        if (name == "range") return util::toString(glyphRange.first) + "-" + util::toString(glyphRange.second);
        return "";
    });

    // The prepare call jumps back to the main thread.
    req = env.request({ Resource::Kind::Glyphs, url }, [&, url, successCallback, failureCallback](const Response &res) {
        req = nullptr;

        if (res.status != Response::Successful) {
            std::stringstream message;
            message <<  "Failed to load [" << url << "]: " << res.message;
            failureCallback(message.str());
        } else {
            // Transfer the data to the GlyphSet and signal its availability.
            // Once it is available, the caller will need to call parse() to actually
            // parse the data we received. We are not doing this here since this callback is being
            // called from another (unknown) thread.
            data = res.data;
            successCallback(this);
        }
    });
}

GlyphPBF::~GlyphPBF() {
    if (req) {
        env.cancelRequest(req);
    }
}

void GlyphPBF::parse(FontStack &stack) {
    if (!data.size()) {
        // If there is no data, this means we either haven't received any data, or
        // we have already parsed the data.
        return;
    }

    // Parse the glyph PBF
    pbf glyphs_pbf(reinterpret_cast<const uint8_t *>(data.data()), data.size());

    while (glyphs_pbf.next()) {
        if (glyphs_pbf.tag == 1) { // stacks
            pbf fontstack_pbf = glyphs_pbf.message();
            while (fontstack_pbf.next()) {
                if (fontstack_pbf.tag == 3) { // glyphs
                    pbf glyph_pbf = fontstack_pbf.message();

                    SDFGlyph glyph;

                    while (glyph_pbf.next()) {
                        if (glyph_pbf.tag == 1) { // id
                            glyph.id = glyph_pbf.varint();
                        } else if (glyph_pbf.tag == 2) { // bitmap
                            glyph.bitmap = glyph_pbf.string();
                        } else if (glyph_pbf.tag == 3) { // width
                            glyph.metrics.width = glyph_pbf.varint();
                        } else if (glyph_pbf.tag == 4) { // height
                            glyph.metrics.height = glyph_pbf.varint();
                        } else if (glyph_pbf.tag == 5) { // left
                            glyph.metrics.left = glyph_pbf.svarint();
                        } else if (glyph_pbf.tag == 6) { // top
                            glyph.metrics.top = glyph_pbf.svarint();
                        } else if (glyph_pbf.tag == 7) { // advance
                            glyph.metrics.advance = glyph_pbf.varint();
                        } else {
                            glyph_pbf.skip();
                        }
                    }

                    stack.insert(glyph.id, glyph);
                } else {
                    fontstack_pbf.skip();
                }
            }
        } else {
            glyphs_pbf.skip();
        }
    }

    data.clear();

    parsed = true;
}

bool GlyphPBF::isParsed() const {
    return parsed;
}

GlyphStore::GlyphStore(uv_loop_t* loop, Environment& env_)
    : env(env_),
      asyncEmitGlyphRangeLoaded(util::make_unique<uv::async>(loop, [this] { emitGlyphRangeLoaded(); })),
      asyncEmitGlyphRangeLoadedingFailed(util::make_unique<uv::async>(loop, [this] { emitGlyphRangeLoadingFailed(); })),
      observer(nullptr) {
    asyncEmitGlyphRangeLoaded->unref();
    asyncEmitGlyphRangeLoadedingFailed->unref();
}

GlyphStore::~GlyphStore() {
    observer = nullptr;
}

void GlyphStore::setURL(const std::string &url) {
    glyphURL = url;
}

bool GlyphStore::requestGlyphRangesIfNeeded(const std::string& fontStackName,
                                            const std::set<GlyphRange>& glyphRanges) {
    bool requestIsNeeded = false;

    if (glyphRanges.empty()) {
        return requestIsNeeded;
    }

    auto successCallback = [this, fontStackName](GlyphPBF* glyph) {
        auto fontStack = createFontStack(fontStackName);
        glyph->parse(**fontStack);
        asyncEmitGlyphRangeLoaded->send();
    };

    auto failureCallback = [this](const std::string& message) {
        std::lock_guard<std::mutex> lock(errorMessageMutex);
        errorMessage = message;
        asyncEmitGlyphRangeLoadedingFailed->send();
    };

    std::lock_guard<std::mutex> lock(rangesMutex);
    auto& rangeSets = ranges[fontStackName];

    for (const auto& range : glyphRanges) {
        const auto& rangeSets_it = rangeSets.find(range);
        if (rangeSets_it == rangeSets.end()) {
            auto glyph = util::make_unique<GlyphPBF>(glyphURL, fontStackName, range, env,
                successCallback, failureCallback);
            rangeSets.emplace(range, std::move(glyph));
            requestIsNeeded = true;
            continue;
        }

        if (!rangeSets_it->second->isParsed()) {
            requestIsNeeded = true;
        }
    }

    return requestIsNeeded;
}

util::exclusive<FontStack> GlyphStore::createFontStack(const std::string &fontStack) {
    auto lock = util::make_unique<std::lock_guard<std::mutex>>(stacksMutex);

    auto stack_it = stacks.find(fontStack);
    if (stack_it == stacks.end()) {
        stack_it = stacks.emplace(fontStack, util::make_unique<FontStack>()).first;
    }

    return { stack_it->second.get(), std::move(lock) };
}

util::exclusive<FontStack> GlyphStore::getFontStack(const std::string &fontStack) {
    auto lock = util::make_unique<std::lock_guard<std::mutex>>(stacksMutex);

    const auto& stack_it = stacks.find(fontStack);
    if (stack_it == stacks.end()) {
        return { nullptr, nullptr };
    }

    return { stack_it->second.get(), std::move(lock) };
}

void GlyphStore::setObserver(Observer* observer_) {
    observer = observer_;
}

void GlyphStore::emitGlyphRangeLoaded() {
    if (observer) {
        observer->onGlyphRangeLoaded();
    }
}

void GlyphStore::emitGlyphRangeLoadingFailed() {
    if (!observer) {
        return;
    }

    std::lock_guard<std::mutex> lock(errorMessageMutex);
    auto error = std::make_exception_ptr(util::GlyphRangeLoadingException(errorMessage));
    observer->onGlyphRangeLoadingFailed(error);
}

}