1/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SkScalerContext_DEFINED
9#define SkScalerContext_DEFINED
10
11#include <memory>
12
13#include "SkGlyph.h"
14#include "SkMask.h"
15#include "SkMaskFilter.h"
16#include "SkMaskGamma.h"
17#include "SkMatrix.h"
18#include "SkPaint.h"
19#include "SkTypeface.h"
20#include "SkWriteBuffer.h"
21
22class SkAutoDescriptor;
23class SkDescriptor;
24class SkMaskFilter;
25class SkPathEffect;
26
27enum SkScalerContextFlags : uint32_t {
28    kNone                      = 0,
29    kFakeGamma                 = 1 << 0,
30    kBoostContrast             = 1 << 1,
31    kFakeGammaAndBoostContrast = kFakeGamma | kBoostContrast,
32};
33
34struct SkScalerContextEffects {
35    SkScalerContextEffects() : fPathEffect(nullptr), fMaskFilter(nullptr) {}
36    SkScalerContextEffects(SkPathEffect* pe, SkMaskFilter* mf)
37        : fPathEffect(pe), fMaskFilter(mf) {}
38    explicit SkScalerContextEffects(const SkPaint& paint)
39        : fPathEffect(paint.getPathEffect())
40        , fMaskFilter(paint.getMaskFilter()) {}
41
42    SkPathEffect*   fPathEffect;
43    SkMaskFilter*   fMaskFilter;
44};
45
46enum SkAxisAlignment {
47    kNone_SkAxisAlignment,
48    kX_SkAxisAlignment,
49    kY_SkAxisAlignment
50};
51
52/*
53 *  To allow this to be forward-declared, it must be its own typename, rather
54 *  than a nested struct inside SkScalerContext (where it started).
55 */
56struct SkScalerContextRec {
57    uint32_t    fFontID;
58    SkScalar    fTextSize, fPreScaleX, fPreSkewX;
59    SkScalar    fPost2x2[2][2];
60    SkScalar    fFrameWidth, fMiterLimit;
61
62    //These describe the parameters to create (uniquely identify) the pre-blend.
63    uint32_t    fLumBits;
64    uint8_t     fDeviceGamma; //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
65    uint8_t     fPaintGamma;  //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
66    uint8_t     fContrast;    //0.8+1, [0.0, 1.0] artificial contrast
67    uint8_t     fReservedAlign;
68
69    SkScalar getDeviceGamma() const {
70        return SkIntToScalar(fDeviceGamma) / (1 << 6);
71    }
72    void setDeviceGamma(SkScalar dg) {
73        SkASSERT(0 <= dg && dg < SkIntToScalar(4));
74        fDeviceGamma = SkScalarFloorToInt(dg * (1 << 6));
75    }
76
77    SkScalar getPaintGamma() const {
78        return SkIntToScalar(fPaintGamma) / (1 << 6);
79    }
80    void setPaintGamma(SkScalar pg) {
81        SkASSERT(0 <= pg && pg < SkIntToScalar(4));
82        fPaintGamma = SkScalarFloorToInt(pg * (1 << 6));
83    }
84
85    SkScalar getContrast() const {
86        return SkIntToScalar(fContrast) / ((1 << 8) - 1);
87    }
88    void setContrast(SkScalar c) {
89        SkASSERT(0 <= c && c <= SK_Scalar1);
90        fContrast = SkScalarRoundToInt(c * ((1 << 8) - 1));
91    }
92
93    /**
94     *  Causes the luminance color to be ignored, and the paint and device
95     *  gamma to be effectively 1.0
96     */
97    void ignoreGamma() {
98        setLuminanceColor(SK_ColorTRANSPARENT);
99        setPaintGamma(SK_Scalar1);
100        setDeviceGamma(SK_Scalar1);
101    }
102
103    /**
104     *  Causes the luminance color and contrast to be ignored, and the
105     *  paint and device gamma to be effectively 1.0.
106     */
107    void ignorePreBlend() {
108        ignoreGamma();
109        setContrast(0);
110    }
111
112    uint8_t     fMaskFormat;
113    uint8_t     fStrokeJoin : 4;
114    uint8_t     fStrokeCap : 4;
115    uint16_t    fFlags;
116    // Warning: when adding members note that the size of this structure
117    // must be a multiple of 4. SkDescriptor requires that its arguments be
118    // multiples of four and this structure is put in an SkDescriptor in
119    // SkPaint::MakeRecAndEffects.
120
121    void    getMatrixFrom2x2(SkMatrix*) const;
122    void    getLocalMatrix(SkMatrix*) const;
123    void    getSingleMatrix(SkMatrix*) const;
124
125    /** The kind of scale which will be applied by the underlying port (pre-matrix). */
126    enum PreMatrixScale {
127        kFull_PreMatrixScale,  // The underlying port can apply both x and y scale.
128        kVertical_PreMatrixScale,  // The underlying port can only apply a y scale.
129        kVerticalInteger_PreMatrixScale  // The underlying port can only apply an integer y scale.
130    };
131    /**
132     *  Compute useful matrices for use with sizing in underlying libraries.
133     *
134     *  There are two kinds of text size, a 'requested/logical size' which is like asking for size
135     *  '12' and a 'real' size which is the size after the matrix is applied. The matrices produced
136     *  by this method are based on the 'real' size. This method effectively finds the total device
137     *  matrix and decomposes it in various ways.
138     *
139     *  The most useful decomposition is into 'scale' and 'remaining'. The 'scale' is applied first
140     *  and then the 'remaining' to fully apply the total matrix. This decomposition is useful when
141     *  the text size ('scale') may have meaning apart from the total matrix. This is true when
142     *  hinting, and sometimes true for other properties as well.
143     *
144     *  The second (optional) decomposition is of 'remaining' into a non-rotational part
145     *  'remainingWithoutRotation' and a rotational part 'remainingRotation'. The 'scale' is applied
146     *  first, then 'remainingWithoutRotation', then 'remainingRotation' to fully apply the total
147     *  matrix. This decomposition is helpful when only horizontal metrics can be trusted, so the
148     *  'scale' and 'remainingWithoutRotation' will be handled by the underlying library, but
149     *  the final rotation 'remainingRotation' will be handled manually.
150     *
151     *  The 'total' matrix is also (optionally) available. This is useful in cases where the
152     *  underlying library will not be used, often when working directly with font data.
153     *
154     *  The parameters 'scale' and 'remaining' are required, the other pointers may be nullptr.
155     *
156     *  @param preMatrixScale the kind of scale to extract from the total matrix.
157     *  @param scale the scale extracted from the total matrix (both values positive).
158     *  @param remaining apply after scale to apply the total matrix.
159     *  @param remainingWithoutRotation apply after scale to apply the total matrix sans rotation.
160     *  @param remainingRotation apply after remainingWithoutRotation to apply the total matrix.
161     *  @param total the total matrix.
162     *  @return false if the matrix was singular. The output will be valid but not invertible.
163     */
164    bool computeMatrices(PreMatrixScale preMatrixScale,
165                         SkVector* scale, SkMatrix* remaining,
166                         SkMatrix* remainingWithoutRotation = nullptr,
167                         SkMatrix* remainingRotation = nullptr,
168                         SkMatrix* total = nullptr);
169
170    inline SkPaint::Hinting getHinting() const;
171    inline void setHinting(SkPaint::Hinting);
172
173    SkMask::Format getFormat() const {
174        return static_cast<SkMask::Format>(fMaskFormat);
175    }
176
177    SkColor getLuminanceColor() const {
178        return fLumBits;
179    }
180
181    void setLuminanceColor(SkColor c) {
182        fLumBits = c;
183    }
184};
185
186//The following typedef hides from the rest of the implementation the number of
187//most significant bits to consider when creating mask gamma tables. Two bits
188//per channel was chosen as a balance between fidelity (more bits) and cache
189//sizes (fewer bits). Three bits per channel was chosen when #303942; (used by
190//the Chrome UI) turned out too green.
191typedef SkTMaskGamma<3, 3, 3> SkMaskGamma;
192
193class SkScalerContext {
194public:
195    enum Flags {
196        kFrameAndFill_Flag        = 0x0001,
197        kDevKernText_Flag         = 0x0002,
198        kEmbeddedBitmapText_Flag  = 0x0004,
199        kEmbolden_Flag            = 0x0008,
200        kSubpixelPositioning_Flag = 0x0010,
201        kForceAutohinting_Flag    = 0x0020,  // Use auto instead of bytcode hinting if hinting.
202        kVertical_Flag            = 0x0040,
203
204        // together, these two flags resulting in a two bit value which matches
205        // up with the SkPaint::Hinting enum.
206        kHinting_Shift            = 7, // to shift into the other flags above
207        kHintingBit1_Flag         = 0x0080,
208        kHintingBit2_Flag         = 0x0100,
209
210        // Pixel geometry information.
211        // only meaningful if fMaskFormat is kLCD16
212        kLCD_Vertical_Flag        = 0x0200,    // else Horizontal
213        kLCD_BGROrder_Flag        = 0x0400,    // else RGB order
214
215        // Generate A8 from LCD source (for GDI and CoreGraphics).
216        // only meaningful if fMaskFormat is kA8
217        kGenA8FromLCD_Flag        = 0x0800, // could be 0x200 (bit meaning dependent on fMaskFormat)
218    };
219
220    // computed values
221    enum {
222        kHinting_Mask   = kHintingBit1_Flag | kHintingBit2_Flag,
223    };
224
225    SkScalerContext(sk_sp<SkTypeface>, const SkScalerContextEffects&, const SkDescriptor*);
226    virtual ~SkScalerContext();
227
228    SkTypeface* getTypeface() const { return fTypeface.get(); }
229
230    SkMask::Format getMaskFormat() const {
231        return (SkMask::Format)fRec.fMaskFormat;
232    }
233
234    bool isSubpixel() const {
235        return SkToBool(fRec.fFlags & kSubpixelPositioning_Flag);
236    }
237
238    bool isVertical() const {
239        return SkToBool(fRec.fFlags & kVertical_Flag);
240    }
241
242    /** Return the corresponding glyph for the specified unichar. Since contexts
243        may be chained (under the hood), the glyphID that is returned may in
244        fact correspond to a different font/context. In that case, we use the
245        base-glyph-count to know how to translate back into local glyph space.
246     */
247    uint16_t charToGlyphID(SkUnichar uni) {
248        return generateCharToGlyph(uni);
249    }
250
251    /** Map the glyphID to its glyph index, and then to its char code. Unmapped
252        glyphs return zero.
253    */
254    SkUnichar glyphIDToChar(uint16_t glyphID) {
255        return (glyphID < getGlyphCount()) ? generateGlyphToChar(glyphID) : 0;
256    }
257
258    unsigned    getGlyphCount() { return this->generateGlyphCount(); }
259    void        getAdvance(SkGlyph*);
260    void        getMetrics(SkGlyph*);
261    void        getImage(const SkGlyph&);
262    void        getPath(SkPackedGlyphID, SkPath*);
263    void        getFontMetrics(SkPaint::FontMetrics*);
264
265    /** Return the size in bytes of the associated gamma lookup table
266     */
267    static size_t GetGammaLUTSize(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
268                                  int* width, int* height);
269
270    /** Get the associated gamma lookup table. The 'data' pointer must point to pre-allocated
271     *  memory, with size in bytes greater than or equal to the return value of getGammaLUTSize().
272     *
273     *  If the lookup table hasn't been initialized (e.g., it's linear), this will return false.
274     */
275    static bool   GetGammaLUTData(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
276                                  uint8_t* data);
277
278    static void MakeRecAndEffects(const SkPaint& paint,
279                                  const SkSurfaceProps* surfaceProps,
280                                  const SkMatrix* deviceMatrix,
281                                  SkScalerContextFlags scalerContextFlags,
282                                  SkScalerContextRec* rec,
283                                  SkScalerContextEffects* effects);
284
285    static SkDescriptor* AutoDescriptorGivenRecAndEffects(
286        const SkScalerContextRec& rec,
287        const SkScalerContextEffects& effects,
288        SkAutoDescriptor* ad);
289
290    static std::unique_ptr<SkDescriptor> DescriptorGivenRecAndEffects(
291        const SkScalerContextRec& rec,
292        const SkScalerContextEffects& effects);
293
294    static void DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer);
295    static bool CheckBufferSizeForRec(const SkScalerContextRec& rec,
296                                      const SkScalerContextEffects& effects,
297                                      size_t size);
298
299    static SkMaskGamma::PreBlend GetMaskPreBlend(const SkScalerContextRec& rec);
300
301    const SkScalerContextRec& getRec() const { return fRec; }
302
303    SkScalerContextEffects getEffects() const {
304        return { fPathEffect.get(), fMaskFilter.get() };
305    }
306
307    /**
308    *  Return the axis (if any) that the baseline for horizontal text should land on.
309    *  As an example, the identity matrix will return kX_SkAxisAlignment
310    */
311    SkAxisAlignment computeAxisAlignmentForHText();
312
313    static SkDescriptor* CreateDescriptorAndEffectsUsingPaint(
314        const SkPaint& paint, const SkSurfaceProps* surfaceProps,
315        SkScalerContextFlags scalerContextFlags,
316        const SkMatrix* deviceMatrix, SkAutoDescriptor* ad,
317        SkScalerContextEffects* effects);
318
319protected:
320    SkScalerContextRec fRec;
321
322    /** Generates the contents of glyph.fAdvanceX and glyph.fAdvanceY.
323     *  May call getMetrics if that would be just as fast.
324     */
325    virtual void generateAdvance(SkGlyph* glyph) = 0;
326
327    /** Generates the contents of glyph.fWidth, fHeight, fTop, fLeft,
328     *  as well as fAdvanceX and fAdvanceY if not already set.
329     *
330     *  TODO: fMaskFormat is set by getMetrics later; cannot be set here.
331     */
332    virtual void generateMetrics(SkGlyph* glyph) = 0;
333
334    /** Generates the contents of glyph.fImage.
335     *  When called, glyph.fImage will be pointing to a pre-allocated,
336     *  uninitialized region of memory of size glyph.computeImageSize().
337     *  This method may change glyph.fMaskFormat if the new image size is
338     *  less than or equal to the old image size.
339     *
340     *  Because glyph.computeImageSize() will determine the size of fImage,
341     *  generateMetrics will be called before generateImage.
342     */
343    virtual void generateImage(const SkGlyph& glyph) = 0;
344
345    /** Sets the passed path to the glyph outline.
346     *  If this cannot be done the path is set to empty;
347     *  this is indistinguishable from a glyph with an empty path.
348     */
349    virtual void generatePath(SkGlyphID glyphId, SkPath* path) = 0;
350
351    /** Retrieves font metrics. */
352    virtual void generateFontMetrics(SkPaint::FontMetrics*) = 0;
353
354    /** Returns the number of glyphs in the font. */
355    virtual unsigned generateGlyphCount() = 0;
356
357    /** Returns the glyph id for the given unichar.
358     *  If there is no 1:1 mapping from the unichar to a glyph id, returns 0.
359     */
360    virtual uint16_t generateCharToGlyph(SkUnichar unichar) = 0;
361
362    /** Returns the unichar for the given glyph id.
363     *  If there is no 1:1 mapping from the glyph id to a unichar, returns 0.
364     *  The default implementation always returns 0, indicating failure.
365     */
366    virtual SkUnichar generateGlyphToChar(uint16_t glyphId);
367
368    void forceGenerateImageFromPath() { fGenerateImageFromPath = true; }
369    void forceOffGenerateImageFromPath() { fGenerateImageFromPath = false; }
370
371private:
372    friend class SkRandomScalerContext; // For debug purposes
373
374    // never null
375    sk_sp<SkTypeface> fTypeface;
376
377    // optional objects, which may be null
378    sk_sp<SkPathEffect> fPathEffect;
379    sk_sp<SkMaskFilter> fMaskFilter;
380
381    // if this is set, we draw the image from a path, rather than
382    // calling generateImage.
383    bool fGenerateImageFromPath;
384
385    void internalGetPath(SkPackedGlyphID id, SkPath* fillPath,
386                         SkPath* devPath, SkMatrix* fillToDevMatrix);
387
388    // SkMaskGamma::PreBlend converts linear masks to gamma correcting masks.
389protected:
390    // Visible to subclasses so that generateImage can apply the pre-blend directly.
391    const SkMaskGamma::PreBlend fPreBlend;
392private:
393    // When there is a filter, previous steps must create a linear mask
394    // and the pre-blend applied as a final step.
395    const SkMaskGamma::PreBlend fPreBlendForFilter;
396};
397
398#define kRec_SkDescriptorTag            SkSetFourByteTag('s', 'r', 'e', 'c')
399#define kPathEffect_SkDescriptorTag     SkSetFourByteTag('p', 't', 'h', 'e')
400#define kMaskFilter_SkDescriptorTag     SkSetFourByteTag('m', 's', 'k', 'f')
401
402///////////////////////////////////////////////////////////////////////////////
403
404SkPaint::Hinting SkScalerContextRec::getHinting() const {
405    unsigned hint = (fFlags & SkScalerContext::kHinting_Mask) >>
406                                            SkScalerContext::kHinting_Shift;
407    return static_cast<SkPaint::Hinting>(hint);
408}
409
410void SkScalerContextRec::setHinting(SkPaint::Hinting hinting) {
411    fFlags = (fFlags & ~SkScalerContext::kHinting_Mask) |
412                                (hinting << SkScalerContext::kHinting_Shift);
413}
414
415
416#endif
417