SkScalerContext.cpp revision 93d11b5b461a8677a8e3ffa94260f4f9897070ac
1/* libs/graphics/sgl/SkScalerContext.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#include "SkScalerContext.h"
19#include "SkColorPriv.h"
20#include "SkDescriptor.h"
21#include "SkDraw.h"
22#include "SkFontHost.h"
23#include "SkMaskFilter.h"
24#include "SkPathEffect.h"
25#include "SkRasterizer.h"
26#include "SkRegion.h"
27#include "SkStroke.h"
28#include "SkThread.h"
29
30#ifdef SK_DEBUG
31//    #define TRACK_MISSING_CHARS
32#endif
33
34#define ComputeBWRowBytes(width)        (((unsigned)(width) + 7) >> 3)
35
36static const uint8_t* gBlackGammaTable;
37static const uint8_t* gWhiteGammaTable;
38
39void SkGlyph::toMask(SkMask* mask) const {
40    SkASSERT(mask);
41
42    mask->fImage = (uint8_t*)fImage;
43    mask->fBounds.set(fLeft, fTop, fLeft + fWidth, fTop + fHeight);
44    mask->fRowBytes = this->rowBytes();
45    mask->fFormat = static_cast<SkMask::Format>(fMaskFormat);
46}
47
48size_t SkGlyph::computeImageSize() const {
49    const size_t size = this->rowBytes() * fHeight;
50
51    switch (fMaskFormat) {
52    case SkMask::kHorizontalLCD_Format:
53        return SkAlign4(size) + sizeof(uint32_t) * ((fWidth + 2) * fHeight);
54    case SkMask::kVerticalLCD_Format:
55        return SkAlign4(size) + sizeof(uint32_t) * (fWidth * (fHeight + 2));
56    case SkMask::k3D_Format:
57        return 3 * size;
58    default:
59        return size;
60    }
61}
62
63void SkGlyph::zeroMetrics() {
64    fAdvanceX = 0;
65    fAdvanceY = 0;
66    fWidth    = 0;
67    fHeight   = 0;
68    fTop      = 0;
69    fLeft     = 0;
70    fRsbDelta = 0;
71    fLsbDelta = 0;
72}
73
74void SkGlyph::expandA8ToLCD() const {
75    SkASSERT(fMaskFormat == SkMask::kHorizontalLCD_Format ||
76             fMaskFormat == SkMask::kVerticalLCD_Format);
77
78#if defined(SK_SUPPORT_LCDTEXT)
79    uint8_t* input = reinterpret_cast<uint8_t*>(fImage);
80    uint32_t* output = reinterpret_cast<uint32_t*>(input + SkAlign4(rowBytes() * fHeight));
81
82    if (fMaskFormat == SkMask::kHorizontalLCD_Format) {
83        for (unsigned y = 0; y < fHeight; ++y) {
84            const uint8_t* inputRow = input;
85            *output++ = 0;  // make the extra column on the left clear
86            for (unsigned x = 0; x < fWidth; ++x) {
87                const uint8_t alpha = *inputRow++;
88                *output++ = SkPackARGB32(alpha, alpha, alpha, alpha);
89            }
90            *output++ = 0;
91
92            input += rowBytes();
93        }
94    } else {
95        const unsigned outputRowBytes = sizeof(uint32_t) * fWidth;
96        memset(output, 0, outputRowBytes);
97        output += fWidth;
98
99        for (unsigned y = 0; y < fHeight; ++y) {
100            const uint8_t* inputRow = input;
101            for (unsigned x = 0; x < fWidth; ++x) {
102                const uint8_t alpha = *inputRow++;
103                *output++ = SkPackARGB32(alpha, alpha, alpha, alpha);
104            }
105
106            input += rowBytes();
107        }
108
109        memset(output, 0, outputRowBytes);
110        output += fWidth;
111    }
112#else
113#endif
114}
115
116///////////////////////////////////////////////////////////////////////////////
117
118#ifdef SK_DEBUG
119    #define DUMP_RECx
120#endif
121
122static SkFlattenable* load_flattenable(const SkDescriptor* desc, uint32_t tag) {
123    SkFlattenable*  obj = NULL;
124    uint32_t        len;
125    const void*     data = desc->findEntry(tag, &len);
126
127    if (data) {
128        SkFlattenableReadBuffer   buffer(data, len);
129        obj = buffer.readFlattenable();
130        SkASSERT(buffer.offset() == buffer.size());
131    }
132    return obj;
133}
134
135SkScalerContext::SkScalerContext(const SkDescriptor* desc)
136    : fPathEffect(NULL), fMaskFilter(NULL)
137{
138    static bool gHaveGammaTables;
139    if (!gHaveGammaTables) {
140        const uint8_t* tables[2];
141        SkFontHost::GetGammaTables(tables);
142        gBlackGammaTable = tables[0];
143        gWhiteGammaTable = tables[1];
144        gHaveGammaTables = true;
145    }
146
147    fBaseGlyphCount = 0;
148    fNextContext = NULL;
149
150    const Rec* rec = (const Rec*)desc->findEntry(kRec_SkDescriptorTag, NULL);
151    SkASSERT(rec);
152
153    fRec = *rec;
154
155#ifdef DUMP_REC
156    desc->assertChecksum();
157    SkDebugf("SkScalarContext checksum %x count %d length %d\n", desc->getChecksum(), desc->getCount(), desc->getLength());
158    SkDebugf(" textsize %g prescale %g preskew %g post [%g %g %g %g]\n",
159        rec->fTextSize, rec->fPreScaleX, rec->fPreSkewX, rec->fPost2x2[0][0],
160        rec->fPost2x2[0][1], rec->fPost2x2[1][0], rec->fPost2x2[1][1]);
161    SkDebugf("  frame %g miter %g hints %d framefill %d format %d join %d\n",
162        rec->fFrameWidth, rec->fMiterLimit, rec->fHints, rec->fFrameAndFill,
163        rec->fMaskFormat, rec->fStrokeJoin);
164    SkDebugf("  pathEffect %x maskFilter %x\n", desc->findEntry(kPathEffect_SkDescriptorTag, NULL),
165        desc->findEntry(kMaskFilter_SkDescriptorTag, NULL));
166#endif
167
168    fPathEffect = (SkPathEffect*)load_flattenable(desc, kPathEffect_SkDescriptorTag);
169    fMaskFilter = (SkMaskFilter*)load_flattenable(desc, kMaskFilter_SkDescriptorTag);
170    fRasterizer = (SkRasterizer*)load_flattenable(desc, kRasterizer_SkDescriptorTag);
171}
172
173SkScalerContext::~SkScalerContext() {
174    SkDELETE(fNextContext);
175
176    fPathEffect->safeUnref();
177    fMaskFilter->safeUnref();
178    fRasterizer->safeUnref();
179}
180
181static SkScalerContext* allocNextContext(const SkScalerContext::Rec& rec) {
182    // fonthost will determine the next possible font to search, based
183    // on the current font in fRec. It will return NULL if ctx is our
184    // last font that can be searched (i.e. ultimate fallback font)
185    uint32_t newFontID = SkFontHost::NextLogicalFont(rec.fFontID);
186    if (0 == newFontID) {
187        return NULL;
188    }
189
190    SkAutoDescriptor    ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1));
191    SkDescriptor*       desc = ad.getDesc();
192
193    desc->init();
194    SkScalerContext::Rec* newRec =
195    (SkScalerContext::Rec*)desc->addEntry(kRec_SkDescriptorTag,
196                                          sizeof(rec), &rec);
197    newRec->fFontID = newFontID;
198    desc->computeChecksum();
199
200    return SkFontHost::CreateScalerContext(desc);
201}
202
203/*  Return the next context, creating it if its not already created, but return
204    NULL if the fonthost says there are no more fonts to fallback to.
205 */
206SkScalerContext* SkScalerContext::getNextContext() {
207    SkScalerContext* next = fNextContext;
208    // if next is null, then either it isn't cached yet, or we're at the
209    // end of our possible chain
210    if (NULL == next) {
211        next = allocNextContext(fRec);
212        if (NULL == next) {
213            return NULL;
214        }
215        // next's base is our base + our local count
216        next->setBaseGlyphCount(fBaseGlyphCount + this->getGlyphCount());
217        // cache the answer
218        fNextContext = next;
219    }
220    return next;
221}
222
223SkScalerContext* SkScalerContext::getGlyphContext(const SkGlyph& glyph) {
224    unsigned glyphID = glyph.getGlyphID();
225    SkScalerContext* ctx = this;
226    for (;;) {
227        unsigned count = ctx->getGlyphCount();
228        if (glyphID < count) {
229            break;
230        }
231        glyphID -= count;
232        ctx = ctx->getNextContext();
233        if (NULL == ctx) {
234            SkDebugf("--- no context for glyph %x\n", glyph.getGlyphID());
235            // just return the original context (this)
236            return this;
237        }
238    }
239    return ctx;
240}
241
242/*  This loops through all available fallback contexts (if needed) until it
243    finds some context that can handle the unichar. If all fail, returns 0
244 */
245uint16_t SkScalerContext::charToGlyphID(SkUnichar uni) {
246    SkScalerContext* ctx = this;
247    unsigned glyphID;
248    for (;;) {
249        glyphID = ctx->generateCharToGlyph(uni);
250        if (glyphID) {
251            break;  // found it
252        }
253        ctx = ctx->getNextContext();
254        if (NULL == ctx) {
255            return 0;   // no more contexts, return missing glyph
256        }
257    }
258    // add the ctx's base, making glyphID unique for chain of contexts
259    glyphID += ctx->fBaseGlyphCount;
260    // check for overflow of 16bits, since our glyphID cannot exceed that
261    if (glyphID > 0xFFFF) {
262        glyphID = 0;
263    }
264    return SkToU16(glyphID);
265}
266
267void SkScalerContext::getAdvance(SkGlyph* glyph) {
268    // mark us as just having a valid advance
269    glyph->fMaskFormat = MASK_FORMAT_JUST_ADVANCE;
270    // we mark the format before making the call, in case the impl
271    // internally ends up calling its generateMetrics, which is OK
272    // albeit slower than strictly necessary
273    this->getGlyphContext(*glyph)->generateAdvance(glyph);
274}
275
276void SkScalerContext::getMetrics(SkGlyph* glyph) {
277    this->getGlyphContext(*glyph)->generateMetrics(glyph);
278
279    // for now we have separate cache entries for devkerning on and off
280    // in the future we might share caches, but make our measure/draw
281    // code make the distinction. Thus we zap the values if the caller
282    // has not asked for them.
283    if ((fRec.fFlags & SkScalerContext::kDevKernText_Flag) == 0) {
284        // no devkern, so zap the fields
285        glyph->fLsbDelta = glyph->fRsbDelta = 0;
286    }
287
288    // if either dimension is empty, zap the image bounds of the glyph
289    if (0 == glyph->fWidth || 0 == glyph->fHeight) {
290        glyph->fWidth   = 0;
291        glyph->fHeight  = 0;
292        glyph->fTop     = 0;
293        glyph->fLeft    = 0;
294        glyph->fMaskFormat = 0;
295        return;
296    }
297
298    if (fRec.fFrameWidth > 0 || fPathEffect != NULL || fRasterizer != NULL) {
299        SkPath      devPath, fillPath;
300        SkMatrix    fillToDevMatrix;
301
302        this->internalGetPath(*glyph, &fillPath, &devPath, &fillToDevMatrix);
303
304        if (fRasterizer) {
305            SkMask  mask;
306
307            if (fRasterizer->rasterize(fillPath, fillToDevMatrix, NULL,
308                                       fMaskFilter, &mask,
309                                       SkMask::kJustComputeBounds_CreateMode)) {
310                glyph->fLeft    = mask.fBounds.fLeft;
311                glyph->fTop     = mask.fBounds.fTop;
312                glyph->fWidth   = SkToU16(mask.fBounds.width());
313                glyph->fHeight  = SkToU16(mask.fBounds.height());
314            } else {
315                goto SK_ERROR;
316            }
317        } else {
318            // just use devPath
319            SkIRect ir;
320            devPath.getBounds().roundOut(&ir);
321
322            if (ir.isEmpty() || !ir.is16Bit()) {
323                goto SK_ERROR;
324            }
325            glyph->fLeft    = ir.fLeft;
326            glyph->fTop     = ir.fTop;
327            glyph->fWidth   = SkToU16(ir.width());
328            glyph->fHeight  = SkToU16(ir.height());
329        }
330    }
331
332    glyph->fMaskFormat = fRec.fMaskFormat;
333
334    if (fMaskFilter) {
335        SkMask      src, dst;
336        SkMatrix    matrix;
337
338        glyph->toMask(&src);
339        fRec.getMatrixFrom2x2(&matrix);
340
341        src.fImage = NULL;  // only want the bounds from the filter
342        if (fMaskFilter->filterMask(&dst, src, matrix, NULL)) {
343            SkASSERT(dst.fImage == NULL);
344            glyph->fLeft    = dst.fBounds.fLeft;
345            glyph->fTop     = dst.fBounds.fTop;
346            glyph->fWidth   = SkToU16(dst.fBounds.width());
347            glyph->fHeight  = SkToU16(dst.fBounds.height());
348            glyph->fMaskFormat = dst.fFormat;
349        }
350    }
351    return;
352
353SK_ERROR:
354    // draw nothing 'cause we failed
355    glyph->fLeft    = 0;
356    glyph->fTop     = 0;
357    glyph->fWidth   = 0;
358    glyph->fHeight  = 0;
359    // put a valid value here, in case it was earlier set to
360    // MASK_FORMAT_JUST_ADVANCE
361    glyph->fMaskFormat = fRec.fMaskFormat;
362}
363
364void SkScalerContext::getImage(const SkGlyph& origGlyph) {
365    const SkGlyph*  glyph = &origGlyph;
366    SkGlyph         tmpGlyph;
367
368    if (fMaskFilter) {   // restore the prefilter bounds
369        tmpGlyph.fID = origGlyph.fID;
370
371        // need the original bounds, sans our maskfilter
372        SkMaskFilter* mf = fMaskFilter;
373        fMaskFilter = NULL;             // temp disable
374        this->getMetrics(&tmpGlyph);
375        fMaskFilter = mf;               // restore
376
377        tmpGlyph.fImage = origGlyph.fImage;
378
379        // we need the prefilter bounds to be <= filter bounds
380        SkASSERT(tmpGlyph.fWidth <= origGlyph.fWidth);
381        SkASSERT(tmpGlyph.fHeight <= origGlyph.fHeight);
382        glyph = &tmpGlyph;
383    }
384
385    if (fRec.fFrameWidth > 0 || fPathEffect != NULL || fRasterizer != NULL) {
386        SkPath      devPath, fillPath;
387        SkMatrix    fillToDevMatrix;
388
389        this->internalGetPath(*glyph, &fillPath, &devPath, &fillToDevMatrix);
390
391        const bool lcdMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
392                             fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
393
394        if (fRasterizer) {
395            SkMask  mask;
396
397            glyph->toMask(&mask);
398            mask.fFormat = SkMask::kA8_Format;
399            sk_bzero(glyph->fImage, mask.computeImageSize());
400
401            if (!fRasterizer->rasterize(fillPath, fillToDevMatrix, NULL,
402                                        fMaskFilter, &mask,
403                                        SkMask::kJustRenderImage_CreateMode)) {
404                return;
405            }
406        } else {
407            SkBitmap    bm;
408            SkBitmap::Config config;
409            SkMatrix    matrix;
410            SkRegion    clip;
411            SkPaint     paint;
412            SkDraw      draw;
413
414            if (SkMask::kA8_Format == fRec.fMaskFormat || lcdMode) {
415                config = SkBitmap::kA8_Config;
416                paint.setAntiAlias(true);
417            } else {
418                SkASSERT(SkMask::kBW_Format == fRec.fMaskFormat);
419                config = SkBitmap::kA1_Config;
420                paint.setAntiAlias(false);
421            }
422
423            clip.setRect(0, 0, glyph->fWidth, glyph->fHeight);
424            matrix.setTranslate(-SkIntToScalar(glyph->fLeft),
425                                -SkIntToScalar(glyph->fTop));
426            bm.setConfig(config, glyph->fWidth, glyph->fHeight,
427                         glyph->rowBytes());
428            bm.setPixels(glyph->fImage);
429            sk_bzero(glyph->fImage, bm.height() * bm.rowBytes());
430
431            draw.fClip  = &clip;
432            draw.fMatrix = &matrix;
433            draw.fBitmap = &bm;
434            draw.fBounder = NULL;
435            draw.drawPath(devPath, paint);
436        }
437
438        if (lcdMode)
439            glyph->expandA8ToLCD();
440    } else {
441        this->getGlyphContext(*glyph)->generateImage(*glyph);
442    }
443
444    if (fMaskFilter) {
445        SkMask      srcM, dstM;
446        SkMatrix    matrix;
447
448        // the src glyph image shouldn't be 3D
449        SkASSERT(SkMask::k3D_Format != glyph->fMaskFormat);
450        glyph->toMask(&srcM);
451        fRec.getMatrixFrom2x2(&matrix);
452
453        if (fMaskFilter->filterMask(&dstM, srcM, matrix, NULL)) {
454            int width = SkFastMin32(origGlyph.fWidth, dstM.fBounds.width());
455            int height = SkFastMin32(origGlyph.fHeight, dstM.fBounds.height());
456            int dstRB = origGlyph.rowBytes();
457            int srcRB = dstM.fRowBytes;
458
459            const uint8_t* src = (const uint8_t*)dstM.fImage;
460            uint8_t* dst = (uint8_t*)origGlyph.fImage;
461
462            if (SkMask::k3D_Format == dstM.fFormat) {
463                // we have to copy 3 times as much
464                height *= 3;
465            }
466
467            // clean out our glyph, since it may be larger than dstM
468            //sk_bzero(dst, height * dstRB);
469
470            while (--height >= 0) {
471                memcpy(dst, src, width);
472                src += srcRB;
473                dst += dstRB;
474            }
475            SkMask::FreeImage(dstM.fImage);
476        }
477    }
478
479    // check to see if we should filter the alpha channel
480
481    if (NULL == fMaskFilter &&
482        fRec.fMaskFormat != SkMask::kBW_Format &&
483        (fRec.fFlags & (kGammaForBlack_Flag | kGammaForWhite_Flag)) != 0)
484    {
485        const uint8_t* table = (fRec.fFlags & kGammaForBlack_Flag) ? gBlackGammaTable : gWhiteGammaTable;
486        if (NULL != table)
487        {
488            uint8_t* dst = (uint8_t*)origGlyph.fImage;
489            unsigned rowBytes = origGlyph.rowBytes();
490
491            for (int y = origGlyph.fHeight - 1; y >= 0; --y)
492            {
493                for (int x = origGlyph.fWidth - 1; x >= 0; --x)
494                    dst[x] = table[dst[x]];
495                dst += rowBytes;
496            }
497        }
498    }
499}
500
501void SkScalerContext::getPath(const SkGlyph& glyph, SkPath* path)
502{
503    this->internalGetPath(glyph, NULL, path, NULL);
504}
505
506void SkScalerContext::getFontMetrics(SkPaint::FontMetrics* mx, SkPaint::FontMetrics* my)
507{
508    this->generateFontMetrics(mx, my);
509}
510
511///////////////////////////////////////////////////////////////////////
512
513void SkScalerContext::internalGetPath(const SkGlyph& glyph, SkPath* fillPath, SkPath* devPath, SkMatrix* fillToDevMatrix)
514{
515    SkPath  path;
516
517    this->getGlyphContext(glyph)->generatePath(glyph, &path);
518
519    if (fRec.fFrameWidth > 0 || fPathEffect != NULL)
520    {
521        // need the path in user-space, with only the point-size applied
522        // so that our stroking and effects will operate the same way they
523        // would if the user had extracted the path themself, and then
524        // called drawPath
525        SkPath      localPath;
526        SkMatrix    matrix, inverse;
527
528        fRec.getMatrixFrom2x2(&matrix);
529        matrix.invert(&inverse);
530        path.transform(inverse, &localPath);
531        // now localPath is only affected by the paint settings, and not the canvas matrix
532
533        SkScalar width = fRec.fFrameWidth;
534
535        if (fPathEffect)
536        {
537            SkPath effectPath;
538
539            if (fPathEffect->filterPath(&effectPath, localPath, &width))
540                localPath.swap(effectPath);
541        }
542
543        if (width > 0)
544        {
545            SkStroke    stroker;
546            SkPath      outline;
547
548            stroker.setWidth(width);
549            stroker.setMiterLimit(fRec.fMiterLimit);
550            stroker.setJoin((SkPaint::Join)fRec.fStrokeJoin);
551            stroker.setDoFill(SkToBool(fRec.fFlags & kFrameAndFill_Flag));
552            stroker.strokePath(localPath, &outline);
553            localPath.swap(outline);
554        }
555
556        // now return stuff to the caller
557        if (fillToDevMatrix)
558            *fillToDevMatrix = matrix;
559
560        if (devPath)
561            localPath.transform(matrix, devPath);
562
563        if (fillPath)
564            fillPath->swap(localPath);
565    }
566    else    // nothing tricky to do
567    {
568        if (fillToDevMatrix)
569            fillToDevMatrix->reset();
570
571        if (devPath)
572        {
573            if (fillPath == NULL)
574                devPath->swap(path);
575            else
576                *devPath = path;
577        }
578
579        if (fillPath)
580            fillPath->swap(path);
581    }
582
583    if (devPath)
584        devPath->updateBoundsCache();
585    if (fillPath)
586        fillPath->updateBoundsCache();
587}
588
589
590void SkScalerContext::Rec::getMatrixFrom2x2(SkMatrix* dst) const
591{
592    dst->reset();
593    dst->setScaleX(fPost2x2[0][0]);
594    dst->setSkewX( fPost2x2[0][1]);
595    dst->setSkewY( fPost2x2[1][0]);
596    dst->setScaleY(fPost2x2[1][1]);
597}
598
599void SkScalerContext::Rec::getLocalMatrix(SkMatrix* m) const
600{
601    m->setScale(SkScalarMul(fTextSize, fPreScaleX), fTextSize);
602    if (fPreSkewX)
603        m->postSkew(fPreSkewX, 0);
604}
605
606void SkScalerContext::Rec::getSingleMatrix(SkMatrix* m) const
607{
608    this->getLocalMatrix(m);
609
610    //  now concat the device matrix
611    {
612        SkMatrix    deviceMatrix;
613        this->getMatrixFrom2x2(&deviceMatrix);
614        m->postConcat(deviceMatrix);
615    }
616}
617
618///////////////////////////////////////////////////////////////////////////////
619
620#include "SkFontHost.h"
621
622class SkScalerContext_Empty : public SkScalerContext {
623public:
624    SkScalerContext_Empty(const SkDescriptor* desc) : SkScalerContext(desc) {}
625
626protected:
627    virtual unsigned generateGlyphCount() const {
628        return 0;
629    }
630    virtual uint16_t generateCharToGlyph(SkUnichar uni) {
631        return 0;
632    }
633    virtual void generateAdvance(SkGlyph* glyph) {
634        glyph->zeroMetrics();
635    }
636    virtual void generateMetrics(SkGlyph* glyph) {
637        glyph->zeroMetrics();
638    }
639    virtual void generateImage(const SkGlyph& glyph) {}
640    virtual void generatePath(const SkGlyph& glyph, SkPath* path) {}
641    virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
642                                     SkPaint::FontMetrics* my) {
643        if (mx) {
644            sk_bzero(mx, sizeof(*mx));
645        }
646        if (my) {
647            sk_bzero(my, sizeof(*my));
648        }
649    }
650};
651
652SkScalerContext* SkScalerContext::Create(const SkDescriptor* desc)
653{
654    SkScalerContext* c = SkFontHost::CreateScalerContext(desc);
655    if (NULL == c) {
656        c = SkNEW_ARGS(SkScalerContext_Empty, (desc));
657    }
658    return c;
659}
660
661