summaryrefslogtreecommitdiff
path: root/src/text/glyph_store.cpp
blob: edcecde7fff95e1fcfd5c41bfe0dd60752050365 (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
#include <mbgl/text/glyph_store.hpp>

#include <mbgl/util/std.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/utf.hpp>
#include <mbgl/util/pbf.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/token.hpp>
#include <mbgl/platform/platform.hpp>
#include <uv.h>
#include <algorithm>

namespace mbgl {


void FontStack::insert(uint32_t id, const SDFGlyph &glyph) {
    std::lock_guard<std::mutex> lock(mtx);
    metrics.emplace(id, glyph.metrics);
    bitmaps.emplace(id, glyph.bitmap);
    sdfs.emplace(id, glyph);
}

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

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

const Shaping FontStack::getShaping(const std::u32string &string, const float &maxWidth,
        const float &lineHeight, const float &alignment, const float &verticalAlignment,
        const float &letterSpacing) const {

    std::lock_guard<std::mutex> lock(mtx);
    uint32_t i = 0;
    uint32_t x = 0;
    Shaping shaping;
    // Loop through all characters of this label and shape.
    for (uint32_t chr : string) {
        shaping.emplace_back(0, chr, x, 0);
        i++;
        auto metric = metrics.find(chr);
        if (metric != metrics.end()) {
            x += metric->second.advance + letterSpacing;
        }
    }

    lineWrap(shaping, lineHeight, maxWidth, alignment, verticalAlignment);

    return shaping;
}

void alignVertically(Shaping &shaping, const uint32_t &lines, const float &lineHeight, const float &verticalAlign) {
    const float dy = -(lineHeight * (lines - 1) + 24) * verticalAlign - 5;
    for (GlyphPlacement &shape : shaping) {
        shape.y += dy;
    }
}

void alignHorizontally(Shaping &shaping, const std::map<uint32_t, GlyphMetrics> &metrics,
        const uint32_t &start, const uint32_t &end, const float &alignment) {
    auto & shape = shaping.at(end);
    auto metric = metrics.find(shape.glyph);
    if (metric != metrics.end()) {
        uint32_t lastAdvance = metric->second.advance;
        int32_t lineIndent = (shape.x + lastAdvance) * alignment;
        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 &alignment, const float &verticalAlignment) const {

    std::size_t num_shapes = shaping.size();
    if (!num_shapes) {
        return;
    }
    uint32_t lastSafeBreak = 0;
    uint32_t lengthBeforeCurrentLine = 0;
    uint32_t lineStartIndex = 0;
    uint32_t line = 0;

    for (uint32_t i = 0; i < shaping.size(); i++) {
        GlyphPlacement &shape = shaping[i];
        shape.x -= lengthBeforeCurrentLine;
        shape.y += lineHeight * line;

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

            uint32_t lineLength = shaping[lastSafeBreak + 1].x;

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

            if (alignment) {
                alignHorizontally(shaping, metrics, lineStartIndex, lastSafeBreak - 1, alignment);
            }

            lineStartIndex = lastSafeBreak + 1;
            lastSafeBreak = 0;
            lengthBeforeCurrentLine += lineLength;
            line++;
        }
        if (shape.glyph == 32) {
            lastSafeBreak = i;
        }
    }
    alignHorizontally(shaping, metrics, lineStartIndex, shaping.size() - 1, alignment);
    alignVertically(shaping, line + 1, lineHeight, verticalAlignment);
}

GlyphPBF::GlyphPBF(const std::string &glyphURL, const std::string &fontStack, GlyphRange glyphRange)
    : future(promise.get_future().share())
{
    // Load the glyph set URL
    std::string url = util::replaceTokens(glyphURL, [&](const std::string &name) -> std::string {
        if (name == "fontstack") return fontStack;
        if (name == "range") return std::to_string(glyphRange.first) + "-" + std::to_string(glyphRange.second);
        return "";
    });

    // TODO: Find more reliable URL normalization function
    std::replace(url.begin(), url.end(), ' ', '+');

#if defined(DEBUG)
    fprintf(stderr, "%s\n", url.c_str());
#endif

    platform::request_http(url, [&](platform::Response *res) {
        if (res->code != 200) {
            // Something went wrong with loading the glyph pbf. Pass on the error to the future listeners.
            const std::string msg = util::sprintf<255>("[ERROR] failed to load glyphs (%d): %s\n", res->code, res->error_message.c_str());
            promise.set_exception(std::make_exception_ptr(std::runtime_error(msg)));
        } 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.swap(res->body);
            promise.set_value(*this);
        }
    });
}

std::shared_future<GlyphPBF &> GlyphPBF::getFuture() {
    return future;
}

void GlyphPBF::parse(FontStack &stack) {
    std::lock_guard<std::mutex> lock(mtx);

    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();
}

GlyphStore::GlyphStore(const std::string &glyphURL)
    : glyphURL(glyphURL) {}

void GlyphStore::waitForGlyphRanges(const std::string &fontStack, const std::set<GlyphRange> &glyphRanges) {
    // We are implementing a blocking wait with futures: Every GlyphSet has a future that we are
    // waiting for until it is loaded.

    FontStack *stack = nullptr;

    std::vector<std::shared_future<GlyphPBF &>> futures;
    futures.reserve(glyphRanges.size());
    {
        std::lock_guard<std::mutex> lock(mtx);
        auto &rangeSets = ranges[fontStack];

        stack = &createFontStack(fontStack);

        // Attempt to load the glyph range. If the GlyphSet already exists, we are getting back
        // the same shared_future.
        for (GlyphRange range : glyphRanges) {
            futures.emplace_back(loadGlyphRange(fontStack, rangeSets, range));
        }
    }

    // Now that we potentially created all GlyphSets, we are waiting for the results, one by one.
    // When we get a result (or the GlyphSet is aready loaded), we are attempting to parse the
    // GlyphSet.
    for (std::shared_future<GlyphPBF &> &future : futures) {
        future.get().parse(*stack);
    }
}

std::shared_future<GlyphPBF &> GlyphStore::loadGlyphRange(const std::string &fontStack, std::map<GlyphRange, std::unique_ptr<GlyphPBF>> &rangeSets, const GlyphRange range) {
    auto range_it = rangeSets.find(range);
    if (range_it == rangeSets.end()) {
        // We don't have this glyph set yet for this font stack.
        range_it = rangeSets.emplace(range, std::make_unique<GlyphPBF>(glyphURL, fontStack, range)).first;
    }

    return range_it->second->getFuture();
}

FontStack &GlyphStore::createFontStack(const std::string &fontStack) {
    auto stack_it = stacks.find(fontStack);
    if (stack_it == stacks.end()) {
        stack_it = stacks.emplace(fontStack, std::make_unique<FontStack>()).first;
    }
    return *stack_it->second.get();
}

FontStack &GlyphStore::getFontStack(const std::string &fontStack) {
    std::lock_guard<std::mutex> lock(mtx);
    return createFontStack(fontStack);
}


}