Layout.cpp revision 86fa46c5ebb0d2c3319e08f4fbf487d8c2abbbfc
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 <algorithm>
23#include <fstream>
24#include <iostream>  // for debugging
25#include <stdio.h>  // ditto
26
27#include <unicode/ubidi.h>
28#include <hb-icu.h>
29
30#include "MinikinInternal.h"
31#include <minikin/MinikinFontFreeType.h>
32#include <minikin/Layout.h>
33
34using std::string;
35using std::vector;
36
37namespace android {
38
39// TODO: globals are not cool, move to a factory-ish object
40hb_buffer_t* buffer = 0;
41
42// TODO: these should move into the header file, but for now we don't want
43// to cause namespace collisions with TextLayout.h
44enum {
45    kBidi_LTR = 0,
46    kBidi_RTL = 1,
47    kBidi_Default_LTR = 2,
48    kBidi_Default_RTL = 3,
49    kBidi_Force_LTR = 4,
50    kBidi_Force_RTL = 5,
51
52    kBidi_Mask = 0x7
53};
54
55const int kDirection_Mask = 0x1;
56
57Bitmap::Bitmap(int width, int height) : width(width), height(height) {
58    buf = new uint8_t[width * height]();
59}
60
61Bitmap::~Bitmap() {
62    delete[] buf;
63}
64
65void Bitmap::writePnm(std::ofstream &o) const {
66    o << "P5" << std::endl;
67    o << width << " " << height << std::endl;
68    o << "255" << std::endl;
69    o.write((const char *)buf, width * height);
70    o.close();
71}
72
73void Bitmap::drawGlyph(const GlyphBitmap& bitmap, int x, int y) {
74    int bmw = bitmap.width;
75    int bmh = bitmap.height;
76    x += bitmap.left;
77    y -= bitmap.top;
78    int x0 = std::max(0, x);
79    int x1 = std::min(width, x + bmw);
80    int y0 = std::max(0, y);
81    int y1 = std::min(height, y + bmh);
82    const unsigned char* src = bitmap.buffer + (y0 - y) * bmw + (x0 - x);
83    uint8_t* dst = buf + y0 * width;
84    for (int yy = y0; yy < y1; yy++) {
85        for (int xx = x0; xx < x1; xx++) {
86            int pixel = (int)dst[xx] + (int)src[xx - x];
87            pixel = pixel > 0xff ? 0xff : pixel;
88            dst[xx] = pixel;
89        }
90        src += bmw;
91        dst += width;
92    }
93}
94
95void MinikinRect::join(const MinikinRect& r) {
96    if (isEmpty()) {
97        set(r);
98    } else if (!r.isEmpty()) {
99        mLeft = std::min(mLeft, r.mLeft);
100        mTop = std::min(mTop, r.mTop);
101        mRight = std::max(mRight, r.mRight);
102        mBottom = std::max(mBottom, r.mBottom);
103    }
104}
105
106// TODO: the actual initialization is deferred, maybe make this explicit
107void Layout::init() {
108}
109
110void Layout::setFontCollection(const FontCollection *collection) {
111    mCollection = collection;
112}
113
114hb_blob_t* referenceTable(hb_face_t* face, hb_tag_t tag, void* userData)  {
115    MinikinFont* font = reinterpret_cast<MinikinFont *>(userData);
116    size_t length = 0;
117    bool ok = font->GetTable(tag, NULL, &length);
118    if (!ok) {
119        return 0;
120    }
121    char *buffer = reinterpret_cast<char*>(malloc(length));
122    if (!buffer) {
123        return 0;
124    }
125    ok = font->GetTable(tag, reinterpret_cast<uint8_t*>(buffer), &length);
126    printf("referenceTable %c%c%c%c length=%d %d\n",
127        (tag >>24) & 0xff, (tag>>16)&0xff, (tag>>8)&0xff, tag&0xff, length, ok);
128    if (!ok) {
129        free(buffer);
130        return 0;
131    }
132    return hb_blob_create(const_cast<char*>(buffer), length,
133        HB_MEMORY_MODE_WRITABLE, buffer, free);
134}
135
136static hb_bool_t harfbuzzGetGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData)
137{
138    MinikinPaint* paint = reinterpret_cast<MinikinPaint *>(fontData);
139    MinikinFont* font = paint->font;
140    uint32_t glyph_id;
141    bool ok = font->GetGlyph(unicode, &glyph_id);
142    if (ok) {
143        *glyph = glyph_id;
144    }
145    return ok;
146}
147
148static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData)
149{
150    MinikinPaint* paint = reinterpret_cast<MinikinPaint *>(fontData);
151    MinikinFont* font = paint->font;
152    float advance = font->GetHorizontalAdvance(glyph, *paint);
153    return 256 * advance + 0.5;
154}
155
156static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
157{
158    // Just return true, following the way that Harfbuzz-FreeType
159    // implementation does.
160    return true;
161}
162
163hb_font_funcs_t* getHbFontFuncs() {
164    static hb_font_funcs_t* hbFontFuncs = 0;
165
166    if (hbFontFuncs == 0) {
167        hbFontFuncs = hb_font_funcs_create();
168        hb_font_funcs_set_glyph_func(hbFontFuncs, harfbuzzGetGlyph, 0, 0);
169        hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0);
170        hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
171        hb_font_funcs_make_immutable(hbFontFuncs);
172    }
173    return hbFontFuncs;
174}
175
176hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) {
177    hb_face_t* face = hb_face_create_for_tables(referenceTable, minikinFont, NULL);
178    hb_font_t* font = hb_font_create(face);
179    hb_face_destroy(face);
180    hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0);
181    // TODO: manage ownership of face
182    return font;
183}
184
185static float HBFixedToFloat(hb_position_t v)
186{
187    return scalbnf (v, -8);
188}
189
190static hb_position_t HBFloatToFixed(float v)
191{
192    return scalbnf (v, +8);
193}
194
195Layout::~Layout() {
196    for (size_t ix = 0; ix < mHbFonts.size(); ix++) {
197        hb_font_destroy(mHbFonts[ix]);
198    }
199}
200
201void Layout::dump() const {
202    for (size_t i = 0; i < mGlyphs.size(); i++) {
203        const LayoutGlyph& glyph = mGlyphs[i];
204        std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl;
205    }
206}
207
208// A couple of things probably need to change:
209// 1. Deal with multiple sizes in a layout
210// 2. We'll probably store FT_Face as primary and then use a cache
211// for the hb fonts
212int Layout::findFace(MinikinFont* face, MinikinPaint* paint) {
213    unsigned int ix;
214    for (ix = 0; ix < mFaces.size(); ix++) {
215        if (mFaces[ix] == face) {
216            return ix;
217        }
218    }
219    mFaces.push_back(face);
220    hb_font_t *font = create_hb_font(face, paint);
221    mHbFonts.push_back(font);
222    return ix;
223}
224
225static FontStyle styleFromCss(const CssProperties &props) {
226    int weight = 4;
227    if (props.hasTag(fontWeight)) {
228        weight = props.value(fontWeight).getIntValue() / 100;
229    }
230    bool italic = false;
231    if (props.hasTag(fontStyle)) {
232        italic = props.value(fontStyle).getIntValue() != 0;
233    }
234    return FontStyle(weight, italic);
235}
236
237static hb_script_t codePointToScript(hb_codepoint_t codepoint) {
238    static hb_unicode_funcs_t *u = 0;
239    if (!u) {
240        u = hb_icu_get_unicode_funcs();
241    }
242    return hb_unicode_script(u, codepoint);
243}
244
245static hb_codepoint_t decodeUtf16(const uint16_t *chars, size_t len, ssize_t *iter) {
246    const uint16_t v = chars[(*iter)++];
247    // test whether v in (0xd800..0xdfff), lead or trail surrogate
248    if ((v & 0xf800) == 0xd800) {
249        // test whether v in (0xd800..0xdbff), lead surrogate
250        if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) {
251            const uint16_t v2 = chars[(*iter)++];
252            // test whether v2 in (0xdc00..0xdfff), trail surrogate
253            if ((v2 & 0xfc00) == 0xdc00) {
254                // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32
255                const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000;
256                return (((hb_codepoint_t)v) << 10) + v2 - delta;
257            }
258            (*iter) -= 2;
259            return ~0u;
260        } else {
261            (*iter)--;
262            return ~0u;
263        }
264    } else {
265        return v;
266    }
267}
268
269static hb_script_t getScriptRun(const uint16_t *chars, size_t len, ssize_t *iter) {
270    if (size_t(*iter) == len) {
271        return HB_SCRIPT_UNKNOWN;
272    }
273    uint32_t cp = decodeUtf16(chars, len, iter);
274    hb_script_t current_script = codePointToScript(cp);
275    for (;;) {
276        if (size_t(*iter) == len)
277            break;
278        const ssize_t prev_iter = *iter;
279        cp = decodeUtf16(chars, len, iter);
280        const hb_script_t script = codePointToScript(cp);
281        if (script != current_script) {
282            if (current_script == HB_SCRIPT_INHERITED ||
283                current_script == HB_SCRIPT_COMMON) {
284                current_script = script;
285            } else if (script == HB_SCRIPT_INHERITED ||
286                script == HB_SCRIPT_COMMON) {
287                continue;
288            } else {
289                *iter = prev_iter;
290                break;
291            }
292        }
293    }
294    if (current_script == HB_SCRIPT_INHERITED) {
295        current_script = HB_SCRIPT_COMMON;
296    }
297
298    return current_script;
299}
300
301// TODO: API should probably take context
302void Layout::doLayout(const uint16_t* buf, size_t nchars) {
303    AutoMutex _l(gMinikinLock);
304    if (buffer == 0) {
305        buffer = hb_buffer_create();
306    }
307    FT_Error error;
308
309    FontStyle style = styleFromCss(mProps);
310
311    MinikinPaint paint;
312    double size = mProps.value(fontSize).getFloatValue();
313    paint.size = size;
314    int bidiFlags = mProps.hasTag(minikinBidi) ? mProps.value(minikinBidi).getIntValue() : 0;
315    bool isRtl = (bidiFlags & kDirection_Mask) != 0;
316    bool doSingleRun = true;
317
318    mGlyphs.clear();
319    mFaces.clear();
320    mHbFonts.clear();
321    mBounds.setEmpty();
322    mAdvances.clear();
323    mAdvances.resize(nchars, 0);
324    mAdvance = 0;
325    if (!(bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL)) {
326        UBiDi* bidi = ubidi_open();
327        if (bidi) {
328            UErrorCode status = U_ZERO_ERROR;
329            UBiDiLevel bidiReq = bidiFlags;
330            if (bidiFlags == kBidi_Default_LTR) {
331                bidiReq = UBIDI_DEFAULT_LTR;
332            } else if (bidiFlags == kBidi_Default_RTL) {
333                bidiReq = UBIDI_DEFAULT_RTL;
334            }
335            ubidi_setPara(bidi, buf, nchars, bidiReq, NULL, &status);
336            if (U_SUCCESS(status)) {
337                int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask;
338                ssize_t rc = ubidi_countRuns(bidi, &status);
339                if (!U_SUCCESS(status) || rc < 1) {
340                    ALOGD("error counting bidi runs, status = %d", status);
341                }
342                if (!U_SUCCESS(status) || rc <= 1) {
343                    isRtl = (paraDir == kBidi_RTL);
344                } else {
345                    doSingleRun = false;
346                    // iterate through runs
347                    for (ssize_t i = 0; i < (ssize_t)rc; i++) {
348                        int32_t startRun = -1;
349                        int32_t lengthRun = -1;
350                        UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun);
351                        if (startRun == -1 || lengthRun == -1) {
352                            ALOGE("invalid visual run");
353                            // Note: this case will lose text; can it ever actually happen?
354                            break;
355                        }
356                        isRtl = (runDir == UBIDI_RTL);
357                        // TODO: min/max with context
358                        doLayoutRun(buf, startRun, lengthRun, nchars, isRtl, style, paint);
359                    }
360                }
361            } else {
362                ALOGE("error calling ubidi_setPara, status = %d", status);
363            }
364            ubidi_close(bidi);
365        } else {
366            ALOGE("error creating bidi object");
367        }
368    }
369    if (doSingleRun) {
370        doLayoutRun(buf, 0, nchars, nchars, isRtl, style, paint);
371    }
372}
373
374void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize,
375    bool isRtl, FontStyle style, MinikinPaint& paint) {
376    vector<FontCollection::Run> items;
377    mCollection->itemize(buf + start, count, style, &items);
378    if (isRtl) {
379        std::reverse(items.begin(), items.end());
380    }
381
382    float x = mAdvance;
383    float y = 0;
384    for (size_t run_ix = 0; run_ix < items.size(); run_ix++) {
385        FontCollection::Run &run = items[run_ix];
386        int font_ix = findFace(run.font, &paint);
387        paint.font = mFaces[font_ix];
388        hb_font_t *hbFont = mHbFonts[font_ix];
389        if (paint.font == NULL) {
390            // TODO: should log what went wrong
391            continue;
392        }
393#ifdef VERBOSE
394        std::cout << "Run " << run_ix << ", font " << font_ix <<
395            " [" << run.start << ":" << run.end << "]" << std::endl;
396#endif
397        double size = paint.size;
398        hb_font_set_ppem(hbFont, size, size);
399        hb_font_set_scale(hbFont, HBFloatToFixed(size), HBFloatToFixed(size));
400
401        // TODO: if there are multiple scripts within a font in an RTL run,
402        // we need to reorder those runs. This is unlikely with our current
403        // font stack, but should be done for correctness.
404        ssize_t srunend;
405        for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) {
406            srunend = srunstart;
407            hb_script_t script = getScriptRun(buf + start, run.end, &srunend);
408
409            hb_buffer_reset(buffer);
410            hb_buffer_set_script(buffer, script);
411            hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
412            hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart);
413            hb_shape(hbFont, buffer, NULL, 0);
414            unsigned int numGlyphs;
415            hb_glyph_info_t *info = hb_buffer_get_glyph_infos(buffer, &numGlyphs);
416            hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer, NULL);
417            for (unsigned int i = 0; i < numGlyphs; i++) {
418    #ifdef VERBOSE
419                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 <<
420                ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl;
421    #endif
422                hb_codepoint_t glyph_ix = info[i].codepoint;
423                float xoff = HBFixedToFloat(positions[i].x_offset);
424                float yoff = HBFixedToFloat(positions[i].y_offset);
425                LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff};
426                mGlyphs.push_back(glyph);
427                float xAdvance = HBFixedToFloat(positions[i].x_advance);
428                MinikinRect glyphBounds;
429                paint.font->GetBounds(&glyphBounds, glyph_ix, paint);
430                glyphBounds.offset(x + xoff, y + yoff);
431                mBounds.join(glyphBounds);
432                size_t cluster = info[i].cluster;
433                mAdvances[cluster] += xAdvance;
434                x += xAdvance;
435            }
436        }
437    }
438    mAdvance = x;
439}
440
441void Layout::draw(Bitmap* surface, int x0, int y0) const {
442    /*
443    TODO: redo as MinikinPaint settings
444    if (mProps.hasTag(minikinHinting)) {
445        int hintflags = mProps.value(minikinHinting).getIntValue();
446        if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING;
447        if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT;
448    }
449    */
450    for (size_t i = 0; i < mGlyphs.size(); i++) {
451        const LayoutGlyph& glyph = mGlyphs[i];
452        MinikinFont *mf = mFaces[glyph.font_ix];
453        MinikinFontFreeType *face = static_cast<MinikinFontFreeType *>(mf);
454        GlyphBitmap glyphBitmap;
455        MinikinPaint paint;
456        paint.size = mProps.value(fontSize).getFloatValue();
457        bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap);
458        printf("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d\n",
459            glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok);
460        if (ok) {
461            surface->drawGlyph(glyphBitmap,
462                x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5)));
463        }
464    }
465}
466
467void Layout::setProperties(string css) {
468    mProps.parse(css);
469}
470
471size_t Layout::nGlyphs() const {
472    return mGlyphs.size();
473}
474
475MinikinFont *Layout::getFont(int i) const {
476    const LayoutGlyph& glyph = mGlyphs[i];
477    return mFaces[glyph.font_ix];
478}
479
480unsigned int Layout::getGlyphId(int i) const {
481    const LayoutGlyph& glyph = mGlyphs[i];
482    return glyph.glyph_id;
483}
484
485float Layout::getX(int i) const {
486    const LayoutGlyph& glyph = mGlyphs[i];
487    return glyph.x;
488}
489
490float Layout::getY(int i) const {
491    const LayoutGlyph& glyph = mGlyphs[i];
492    return glyph.y;
493}
494
495float Layout::getAdvance() const {
496    return mAdvance;
497}
498
499void Layout::getAdvances(float* advances) {
500    memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float));
501}
502
503void Layout::getBounds(MinikinRect* bounds) {
504    bounds->set(mBounds);
505}
506
507}  // namespace android
508