Layout.cpp revision 0a689bb956183beebe7d59fccb226a82680f265a
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Minikin"
18#include <cutils/log.h>
19
20#include <string>
21#include <vector>
22#include <fstream>
23#include <iostream>  // for debugging
24#include <stdio.h>  // ditto
25
26#include <hb-icu.h>
27
28#include "MinikinInternal.h"
29#include <minikin/MinikinFontFreeType.h>
30#include <minikin/Layout.h>
31
32using std::string;
33using std::vector;
34
35namespace android {
36
37// TODO: globals are not cool, move to a factory-ish object
38hb_buffer_t* buffer = 0;
39
40Bitmap::Bitmap(int width, int height) : width(width), height(height) {
41    buf = new uint8_t[width * height]();
42}
43
44Bitmap::~Bitmap() {
45    delete[] buf;
46}
47
48void Bitmap::writePnm(std::ofstream &o) const {
49    o << "P5" << std::endl;
50    o << width << " " << height << std::endl;
51    o << "255" << std::endl;
52    o.write((const char *)buf, width * height);
53    o.close();
54}
55
56void Bitmap::drawGlyph(const GlyphBitmap& bitmap, int x, int y) {
57    int bmw = bitmap.width;
58    int bmh = bitmap.height;
59    x += bitmap.left;
60    y -= bitmap.top;
61    int x0 = std::max(0, x);
62    int x1 = std::min(width, x + bmw);
63    int y0 = std::max(0, y);
64    int y1 = std::min(height, y + bmh);
65    const unsigned char* src = bitmap.buffer + (y0 - y) * bmw + (x0 - x);
66    uint8_t* dst = buf + y0 * width;
67    for (int yy = y0; yy < y1; yy++) {
68        for (int xx = x0; xx < x1; xx++) {
69            int pixel = (int)dst[xx] + (int)src[xx - x];
70            pixel = pixel > 0xff ? 0xff : pixel;
71            dst[xx] = pixel;
72        }
73        src += bmw;
74        dst += width;
75    }
76}
77
78void MinikinRect::join(const MinikinRect& r) {
79    if (isEmpty()) {
80        set(r);
81    } else if (!r.isEmpty()) {
82        mLeft = std::min(mLeft, r.mLeft);
83        mTop = std::min(mTop, r.mTop);
84        mRight = std::max(mRight, r.mRight);
85        mBottom = std::max(mBottom, r.mBottom);
86    }
87}
88
89// TODO: the actual initialization is deferred, maybe make this explicit
90void Layout::init() {
91}
92
93void Layout::setFontCollection(const FontCollection *collection) {
94    ALOGD("setFontCollection(%p)", collection);
95    mCollection = collection;
96}
97
98hb_blob_t* referenceTable(hb_face_t* face, hb_tag_t tag, void* userData)  {
99    MinikinFont* font = reinterpret_cast<MinikinFont *>(userData);
100    size_t length = 0;
101    bool ok = font->GetTable(tag, NULL, &length);
102    if (!ok) {
103        return 0;
104    }
105    char *buffer = reinterpret_cast<char*>(malloc(length));
106    if (!buffer) {
107        return 0;
108    }
109    ok = font->GetTable(tag, reinterpret_cast<uint8_t*>(buffer), &length);
110    printf("referenceTable %c%c%c%c length=%d %d\n",
111        (tag >>24) & 0xff, (tag>>16)&0xff, (tag>>8)&0xff, tag&0xff, length, ok);
112    if (!ok) {
113        free(buffer);
114        return 0;
115    }
116    return hb_blob_create(const_cast<char*>(buffer), length,
117        HB_MEMORY_MODE_WRITABLE, buffer, free);
118}
119
120static hb_bool_t harfbuzzGetGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData)
121{
122    MinikinPaint* paint = reinterpret_cast<MinikinPaint *>(fontData);
123    MinikinFont* font = paint->font;
124    uint32_t glyph_id;
125    bool ok = font->GetGlyph(unicode, &glyph_id);
126    if (ok) {
127        *glyph = glyph_id;
128    }
129    return ok;
130}
131
132static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData)
133{
134    MinikinPaint* paint = reinterpret_cast<MinikinPaint *>(fontData);
135    MinikinFont* font = paint->font;
136    float advance = font->GetHorizontalAdvance(glyph, *paint);
137    return 256 * advance + 0.5;
138}
139
140static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
141{
142    // Just return true, following the way that Harfbuzz-FreeType
143    // implementation does.
144    return true;
145}
146
147hb_font_funcs_t* getHbFontFuncs() {
148    static hb_font_funcs_t* hbFontFuncs = 0;
149
150    if (hbFontFuncs == 0) {
151        hbFontFuncs = hb_font_funcs_create();
152        hb_font_funcs_set_glyph_func(hbFontFuncs, harfbuzzGetGlyph, 0, 0);
153        hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0);
154        hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
155        hb_font_funcs_make_immutable(hbFontFuncs);
156    }
157    return hbFontFuncs;
158}
159
160hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) {
161    hb_face_t* face = hb_face_create_for_tables(referenceTable, minikinFont, NULL);
162    hb_font_t* font = hb_font_create(face);
163    hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0);
164    // TODO: manage ownership of face
165    return font;
166}
167
168static float HBFixedToFloat(hb_position_t v)
169{
170    return scalbnf (v, -8);
171}
172
173static hb_position_t HBFloatToFixed(float v)
174{
175    return scalbnf (v, +8);
176}
177
178void Layout::dump() const {
179    for (size_t i = 0; i < mGlyphs.size(); i++) {
180        const LayoutGlyph& glyph = mGlyphs[i];
181        std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl;
182    }
183}
184
185// A couple of things probably need to change:
186// 1. Deal with multiple sizes in a layout
187// 2. We'll probably store FT_Face as primary and then use a cache
188// for the hb fonts
189int Layout::findFace(MinikinFont* face, MinikinPaint* paint) {
190    unsigned int ix;
191    for (ix = 0; ix < mFaces.size(); ix++) {
192        if (mFaces[ix] == face) {
193            return ix;
194        }
195    }
196    mFaces.push_back(face);
197    hb_font_t *font = create_hb_font(face, paint);
198    mHbFonts.push_back(font);
199    return ix;
200}
201
202static FontStyle styleFromCss(const CssProperties &props) {
203    int weight = 4;
204    if (props.hasTag(fontWeight)) {
205        weight = props.value(fontWeight).getIntValue() / 100;
206    }
207    bool italic = false;
208    if (props.hasTag(fontStyle)) {
209        italic = props.value(fontStyle).getIntValue() != 0;
210    }
211    return FontStyle(weight, italic);
212}
213
214static hb_script_t codePointToScript(hb_codepoint_t codepoint) {
215    static hb_unicode_funcs_t *u = 0;
216    if (!u) {
217        u = hb_icu_get_unicode_funcs();
218    }
219    return hb_unicode_script(u, codepoint);
220}
221
222static hb_codepoint_t decodeUtf16(const uint16_t *chars, size_t len, ssize_t *iter) {
223    const uint16_t v = chars[(*iter)++];
224    // test whether v in (0xd800..0xdfff), lead or trail surrogate
225    if ((v & 0xf800) == 0xd800) {
226        // test whether v in (0xd800..0xdbff), lead surrogate
227        if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) {
228            const uint16_t v2 = chars[(*iter)++];
229            // test whether v2 in (0xdc00..0xdfff), trail surrogate
230            if ((v2 & 0xfc00) == 0xdc00) {
231                // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32
232                const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000;
233                return (((hb_codepoint_t)v) << 10) + v2 - delta;
234            }
235            (*iter) -= 2;
236            return ~0u;
237        } else {
238            (*iter)--;
239            return ~0u;
240        }
241    } else {
242        return v;
243    }
244}
245
246static hb_script_t getScriptRun(const uint16_t *chars, size_t len, ssize_t *iter) {
247    if (size_t(*iter) == len) {
248        return HB_SCRIPT_UNKNOWN;
249    }
250    uint32_t cp = decodeUtf16(chars, len, iter);
251    hb_script_t current_script = codePointToScript(cp);
252    for (;;) {
253        if (size_t(*iter) == len)
254            break;
255        const ssize_t prev_iter = *iter;
256        cp = decodeUtf16(chars, len, iter);
257        const hb_script_t script = codePointToScript(cp);
258        if (script != current_script) {
259            if (current_script == HB_SCRIPT_INHERITED ||
260                current_script == HB_SCRIPT_COMMON) {
261                current_script = script;
262            } else if (script == HB_SCRIPT_INHERITED ||
263                script == HB_SCRIPT_COMMON) {
264                continue;
265            } else {
266                *iter = prev_iter;
267                break;
268            }
269        }
270    }
271    if (current_script == HB_SCRIPT_INHERITED) {
272        current_script = HB_SCRIPT_COMMON;
273    }
274
275    return current_script;
276}
277
278// TODO: API should probably take context
279void Layout::doLayout(const uint16_t* buf, size_t nchars) {
280    AutoMutex _l(gMinikinLock);
281    if (buffer == 0) {
282        buffer = hb_buffer_create();
283    }
284    FT_Error error;
285
286    vector<FontCollection::Run> items;
287    FontStyle style = styleFromCss(mProps);
288    mCollection->itemize(buf, nchars, style, &items);
289
290    MinikinPaint paint;
291    double size = mProps.value(fontSize).getFloatValue();
292    paint.size = size;
293
294    mGlyphs.clear();
295    mFaces.clear();
296    mHbFonts.clear();
297    mBounds.setEmpty();
298    mAdvances.clear();
299    mAdvances.resize(nchars, 0);
300    float x = 0;
301    float y = 0;
302    for (size_t run_ix = 0; run_ix < items.size(); run_ix++) {
303        FontCollection::Run &run = items[run_ix];
304        int font_ix = findFace(run.font, &paint);
305        paint.font = mFaces[font_ix];
306        hb_font_t *hbFont = mHbFonts[font_ix];
307        if (paint.font == NULL) {
308            // TODO: should log what went wrong
309            continue;
310        }
311#ifdef VERBOSE
312        std::cout << "Run " << run_ix << ", font " << font_ix <<
313            " [" << run.start << ":" << run.end << "]" << std::endl;
314#endif
315        hb_font_set_ppem(hbFont, size, size);
316        hb_font_set_scale(hbFont, HBFloatToFixed(size), HBFloatToFixed(size));
317
318        ssize_t srunend;
319        for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) {
320            srunend = srunstart;
321            hb_script_t script = getScriptRun(buf, run.end, &srunend);
322
323            hb_buffer_reset(buffer);
324            hb_buffer_set_script(buffer, script);
325            hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
326            hb_buffer_add_utf16(buffer, buf, nchars, srunstart, srunend - srunstart);
327            hb_shape(hbFont, buffer, NULL, 0);
328            unsigned int numGlyphs;
329            hb_glyph_info_t *info = hb_buffer_get_glyph_infos(buffer, &numGlyphs);
330            hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer, NULL);
331            for (unsigned int i = 0; i < numGlyphs; i++) {
332    #ifdef VERBOSE
333                std::cout << positions[i].x_advance << " " << positions[i].y_advance << " " << positions[i].x_offset << " " << positions[i].y_offset << std::endl;            std::cout << "DoLayout " << info[i].codepoint <<
334                ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl;
335    #endif
336                hb_codepoint_t glyph_ix = info[i].codepoint;
337                float xoff = HBFixedToFloat(positions[i].x_offset);
338                float yoff = HBFixedToFloat(positions[i].y_offset);
339                LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff};
340                mGlyphs.push_back(glyph);
341                float xAdvance = HBFixedToFloat(positions[i].x_advance);
342                MinikinRect glyphBounds;
343                paint.font->GetBounds(&glyphBounds, glyph_ix, paint);
344                glyphBounds.offset(x + xoff, y + yoff);
345                mBounds.join(glyphBounds);
346                size_t cluster = info[i].cluster;
347                mAdvances[cluster] += xAdvance;
348                x += xAdvance;
349            }
350        }
351    }
352    mAdvance = x;
353}
354
355void Layout::draw(Bitmap* surface, int x0, int y0) const {
356    /*
357    TODO: redo as MinikinPaint settings
358    if (mProps.hasTag(minikinHinting)) {
359        int hintflags = mProps.value(minikinHinting).getIntValue();
360        if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING;
361        if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT;
362    }
363    */
364    for (size_t i = 0; i < mGlyphs.size(); i++) {
365        const LayoutGlyph& glyph = mGlyphs[i];
366        MinikinFont *mf = mFaces[glyph.font_ix];
367        MinikinFontFreeType *face = static_cast<MinikinFontFreeType *>(mf);
368        GlyphBitmap glyphBitmap;
369        MinikinPaint paint;
370        paint.size = mProps.value(fontSize).getFloatValue();
371        bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap);
372        printf("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d\n",
373            glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok);
374        if (ok) {
375            surface->drawGlyph(glyphBitmap,
376                x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5)));
377        }
378    }
379}
380
381void Layout::setProperties(string css) {
382    mProps.parse(css);
383}
384
385size_t Layout::nGlyphs() const {
386    return mGlyphs.size();
387}
388
389MinikinFont *Layout::getFont(int i) const {
390    const LayoutGlyph& glyph = mGlyphs[i];
391    return mFaces[glyph.font_ix];
392}
393
394unsigned int Layout::getGlyphId(int i) const {
395    const LayoutGlyph& glyph = mGlyphs[i];
396    return glyph.glyph_id;
397}
398
399float Layout::getX(int i) const {
400    const LayoutGlyph& glyph = mGlyphs[i];
401    return glyph.x;
402}
403
404float Layout::getY(int i) const {
405    const LayoutGlyph& glyph = mGlyphs[i];
406    return glyph.y;
407}
408
409float Layout::getAdvance() const {
410    return mAdvance;
411}
412
413void Layout::getAdvances(float* advances) {
414    memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float));
415}
416
417void Layout::getBounds(MinikinRect* bounds) {
418    bounds->set(mBounds);
419}
420
421}  // namespace android
422