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