SkScalerContext.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. #ifndef SkScalerContext_DEFINED
  8. #define SkScalerContext_DEFINED
  9. #include <memory>
  10. #include "include/core/SkFont.h"
  11. #include "include/core/SkFontTypes.h"
  12. #include "include/core/SkMaskFilter.h"
  13. #include "include/core/SkMatrix.h"
  14. #include "include/core/SkPaint.h"
  15. #include "include/core/SkTypeface.h"
  16. #include "include/private/SkMacros.h"
  17. #include "src/core/SkGlyph.h"
  18. #include "src/core/SkMask.h"
  19. #include "src/core/SkMaskGamma.h"
  20. #include "src/core/SkStrikeInterface.h"
  21. #include "src/core/SkSurfacePriv.h"
  22. #include "src/core/SkWriteBuffer.h"
  23. class SkAutoDescriptor;
  24. class SkDescriptor;
  25. class SkMaskFilter;
  26. class SkPathEffect;
  27. class SkScalerContext;
  28. class SkScalerContext_DW;
  29. enum SkScalerContextFlags : uint32_t {
  30. kNone = 0,
  31. kFakeGamma = 1 << 0,
  32. kBoostContrast = 1 << 1,
  33. kFakeGammaAndBoostContrast = kFakeGamma | kBoostContrast,
  34. };
  35. enum SkAxisAlignment : uint32_t {
  36. kNone_SkAxisAlignment,
  37. kX_SkAxisAlignment,
  38. kY_SkAxisAlignment
  39. };
  40. /*
  41. * To allow this to be forward-declared, it must be its own typename, rather
  42. * than a nested struct inside SkScalerContext (where it started).
  43. *
  44. * SkScalerContextRec must be dense, and all bytes must be set to a know quantity because this
  45. * structure is used to calculate a checksum.
  46. */
  47. SK_BEGIN_REQUIRE_DENSE
  48. struct SkScalerContextRec {
  49. uint32_t fFontID;
  50. SkScalar fTextSize, fPreScaleX, fPreSkewX;
  51. SkScalar fPost2x2[2][2];
  52. SkScalar fFrameWidth, fMiterLimit;
  53. private:
  54. //These describe the parameters to create (uniquely identify) the pre-blend.
  55. uint32_t fLumBits;
  56. uint8_t fDeviceGamma; //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
  57. uint8_t fPaintGamma; //2.6, (0.0, 4.0) gamma, 0.0 for sRGB
  58. uint8_t fContrast; //0.8+1, [0.0, 1.0] artificial contrast
  59. const uint8_t fReservedAlign{0};
  60. public:
  61. SkScalar getDeviceGamma() const {
  62. return SkIntToScalar(fDeviceGamma) / (1 << 6);
  63. }
  64. void setDeviceGamma(SkScalar dg) {
  65. SkASSERT(0 <= dg && dg < SkIntToScalar(4));
  66. fDeviceGamma = SkScalarFloorToInt(dg * (1 << 6));
  67. }
  68. SkScalar getPaintGamma() const {
  69. return SkIntToScalar(fPaintGamma) / (1 << 6);
  70. }
  71. void setPaintGamma(SkScalar pg) {
  72. SkASSERT(0 <= pg && pg < SkIntToScalar(4));
  73. fPaintGamma = SkScalarFloorToInt(pg * (1 << 6));
  74. }
  75. SkScalar getContrast() const {
  76. sk_ignore_unused_variable(fReservedAlign);
  77. return SkIntToScalar(fContrast) / ((1 << 8) - 1);
  78. }
  79. void setContrast(SkScalar c) {
  80. SkASSERT(0 <= c && c <= SK_Scalar1);
  81. fContrast = SkScalarRoundToInt(c * ((1 << 8) - 1));
  82. }
  83. /**
  84. * Causes the luminance color to be ignored, and the paint and device
  85. * gamma to be effectively 1.0
  86. */
  87. void ignoreGamma() {
  88. setLuminanceColor(SK_ColorTRANSPARENT);
  89. setPaintGamma(SK_Scalar1);
  90. setDeviceGamma(SK_Scalar1);
  91. }
  92. /**
  93. * Causes the luminance color and contrast to be ignored, and the
  94. * paint and device gamma to be effectively 1.0.
  95. */
  96. void ignorePreBlend() {
  97. ignoreGamma();
  98. setContrast(0);
  99. }
  100. uint8_t fMaskFormat;
  101. private:
  102. uint8_t fStrokeJoin : 4;
  103. uint8_t fStrokeCap : 4;
  104. public:
  105. uint16_t fFlags;
  106. // Warning: when adding members note that the size of this structure
  107. // must be a multiple of 4. SkDescriptor requires that its arguments be
  108. // multiples of four and this structure is put in an SkDescriptor in
  109. // SkPaint::MakeRecAndEffects.
  110. SkString dump() const {
  111. SkString msg;
  112. msg.appendf("Rec\n");
  113. msg.appendf(" textsize %g prescale %g preskew %g post [%g %g %g %g]\n",
  114. fTextSize, fPreScaleX, fPreSkewX, fPost2x2[0][0],
  115. fPost2x2[0][1], fPost2x2[1][0], fPost2x2[1][1]);
  116. msg.appendf(" frame %g miter %g format %d join %d cap %d flags %#hx\n",
  117. fFrameWidth, fMiterLimit, fMaskFormat, fStrokeJoin, fStrokeCap, fFlags);
  118. msg.appendf(" lum bits %x, device gamma %d, paint gamma %d contrast %d\n", fLumBits,
  119. fDeviceGamma, fPaintGamma, fContrast);
  120. return msg;
  121. }
  122. void getMatrixFrom2x2(SkMatrix*) const;
  123. void getLocalMatrix(SkMatrix*) const;
  124. void getSingleMatrix(SkMatrix*) const;
  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. SkAxisAlignment computeAxisAlignmentForHText() const;
  170. inline SkFontHinting getHinting() const;
  171. inline void setHinting(SkFontHinting);
  172. SkMask::Format getFormat() const {
  173. return static_cast<SkMask::Format>(fMaskFormat);
  174. }
  175. SkColor getLuminanceColor() const {
  176. return fLumBits;
  177. }
  178. // setLuminanceColor forces the alpha to be 0xFF because the blitter that draws the glyph
  179. // will apply the alpha from the paint. Don't apply the alpha twice.
  180. void setLuminanceColor(SkColor c);
  181. private:
  182. // TODO: remove
  183. friend class SkScalerContext;
  184. };
  185. SK_END_REQUIRE_DENSE
  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.
  191. typedef SkTMaskGamma<3, 3, 3> SkMaskGamma;
  192. class SkScalerContext {
  193. public:
  194. enum Flags {
  195. kFrameAndFill_Flag = 0x0001,
  196. kUnused = 0x0002,
  197. kEmbeddedBitmapText_Flag = 0x0004,
  198. kEmbolden_Flag = 0x0008,
  199. kSubpixelPositioning_Flag = 0x0010,
  200. kForceAutohinting_Flag = 0x0020, // Use auto instead of bytcode hinting if hinting.
  201. // together, these two flags resulting in a two bit value which matches
  202. // up with the SkPaint::Hinting enum.
  203. kHinting_Shift = 7, // to shift into the other flags above
  204. kHintingBit1_Flag = 0x0080,
  205. kHintingBit2_Flag = 0x0100,
  206. // Pixel geometry information.
  207. // only meaningful if fMaskFormat is kLCD16
  208. kLCD_Vertical_Flag = 0x0200, // else Horizontal
  209. kLCD_BGROrder_Flag = 0x0400, // else RGB order
  210. // Generate A8 from LCD source (for GDI and CoreGraphics).
  211. // only meaningful if fMaskFormat is kA8
  212. kGenA8FromLCD_Flag = 0x0800, // could be 0x200 (bit meaning dependent on fMaskFormat)
  213. kLinearMetrics_Flag = 0x1000,
  214. };
  215. // computed values
  216. enum {
  217. kHinting_Mask = kHintingBit1_Flag | kHintingBit2_Flag,
  218. };
  219. SkScalerContext(sk_sp<SkTypeface>, const SkScalerContextEffects&, const SkDescriptor*);
  220. virtual ~SkScalerContext();
  221. SkTypeface* getTypeface() const { return fTypeface.get(); }
  222. SkMask::Format getMaskFormat() const {
  223. return (SkMask::Format)fRec.fMaskFormat;
  224. }
  225. bool isSubpixel() const {
  226. return SkToBool(fRec.fFlags & kSubpixelPositioning_Flag);
  227. }
  228. bool isLinearMetrics() const {
  229. return SkToBool(fRec.fFlags & kLinearMetrics_Flag);
  230. }
  231. // DEPRECATED
  232. bool isVertical() const { return false; }
  233. unsigned getGlyphCount() { return this->generateGlyphCount(); }
  234. void getAdvance(SkGlyph*);
  235. void getMetrics(SkGlyph*);
  236. void getImage(const SkGlyph&);
  237. bool SK_WARN_UNUSED_RESULT getPath(SkPackedGlyphID, SkPath*);
  238. void getFontMetrics(SkFontMetrics*);
  239. /** Return the size in bytes of the associated gamma lookup table
  240. */
  241. static size_t GetGammaLUTSize(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
  242. int* width, int* height);
  243. /** Get the associated gamma lookup table. The 'data' pointer must point to pre-allocated
  244. * memory, with size in bytes greater than or equal to the return value of getGammaLUTSize().
  245. *
  246. * If the lookup table hasn't been initialized (e.g., it's linear), this will return false.
  247. */
  248. static bool GetGammaLUTData(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
  249. uint8_t* data);
  250. static void MakeRecAndEffects(const SkFont& font, const SkPaint& paint,
  251. const SkSurfaceProps& surfaceProps,
  252. SkScalerContextFlags scalerContextFlags,
  253. const SkMatrix& deviceMatrix,
  254. SkScalerContextRec* rec,
  255. SkScalerContextEffects* effects);
  256. // If we are creating rec and effects from a font only, then there is no device around either.
  257. static void MakeRecAndEffectsFromFont(const SkFont& font,
  258. SkScalerContextRec* rec,
  259. SkScalerContextEffects* effects) {
  260. SkPaint paint;
  261. return MakeRecAndEffects(
  262. font, paint, SkSurfaceProps(SkSurfaceProps::kLegacyFontHost_InitType),
  263. SkScalerContextFlags::kNone, SkMatrix::I(), rec, effects);
  264. }
  265. static SkDescriptor* MakeDescriptorForPaths(SkFontID fontID,
  266. SkAutoDescriptor* ad);
  267. static SkDescriptor* AutoDescriptorGivenRecAndEffects(
  268. const SkScalerContextRec& rec,
  269. const SkScalerContextEffects& effects,
  270. SkAutoDescriptor* ad);
  271. static std::unique_ptr<SkDescriptor> DescriptorGivenRecAndEffects(
  272. const SkScalerContextRec& rec,
  273. const SkScalerContextEffects& effects);
  274. static void DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer);
  275. static bool CheckBufferSizeForRec(const SkScalerContextRec& rec,
  276. const SkScalerContextEffects& effects,
  277. size_t size);
  278. static SkMaskGamma::PreBlend GetMaskPreBlend(const SkScalerContextRec& rec);
  279. const SkScalerContextRec& getRec() const { return fRec; }
  280. SkScalerContextEffects getEffects() const {
  281. return { fPathEffect.get(), fMaskFilter.get() };
  282. }
  283. /**
  284. * Return the axis (if any) that the baseline for horizontal text should land on.
  285. * As an example, the identity matrix will return kX_SkAxisAlignment
  286. */
  287. SkAxisAlignment computeAxisAlignmentForHText() const;
  288. static SkDescriptor* CreateDescriptorAndEffectsUsingPaint(
  289. const SkFont&, const SkPaint&, const SkSurfaceProps&,
  290. SkScalerContextFlags scalerContextFlags,
  291. const SkMatrix& deviceMatrix, SkAutoDescriptor* ad,
  292. SkScalerContextEffects* effects);
  293. protected:
  294. SkScalerContextRec fRec;
  295. /** Generates the contents of glyph.fAdvanceX and glyph.fAdvanceY if it can do so quickly.
  296. * Returns true if it could, false otherwise.
  297. */
  298. virtual bool generateAdvance(SkGlyph* glyph) = 0;
  299. /** Generates the contents of glyph.fWidth, fHeight, fTop, fLeft,
  300. * as well as fAdvanceX and fAdvanceY if not already set.
  301. *
  302. * TODO: fMaskFormat is set by getMetrics later; cannot be set here.
  303. */
  304. virtual void generateMetrics(SkGlyph* glyph) = 0;
  305. /** Generates the contents of glyph.fImage.
  306. * When called, glyph.fImage will be pointing to a pre-allocated,
  307. * uninitialized region of memory of size glyph.imageSize().
  308. * This method may change glyph.fMaskFormat if the new image size is
  309. * less than or equal to the old image size.
  310. *
  311. * Because glyph.imageSize() will determine the size of fImage,
  312. * generateMetrics will be called before generateImage.
  313. */
  314. virtual void generateImage(const SkGlyph& glyph) = 0;
  315. /** Sets the passed path to the glyph outline.
  316. * If this cannot be done the path is set to empty;
  317. * @return false if this glyph does not have any path.
  318. */
  319. virtual bool SK_WARN_UNUSED_RESULT generatePath(SkGlyphID glyphId, SkPath* path) = 0;
  320. /** Retrieves font metrics. */
  321. virtual void generateFontMetrics(SkFontMetrics*) = 0;
  322. /** Returns the number of glyphs in the font. */
  323. virtual unsigned generateGlyphCount() = 0;
  324. void forceGenerateImageFromPath() { fGenerateImageFromPath = true; }
  325. void forceOffGenerateImageFromPath() { fGenerateImageFromPath = false; }
  326. private:
  327. friend class RandomScalerContext; // For debug purposes
  328. static SkScalerContextRec PreprocessRec(const SkTypeface& typeface,
  329. const SkScalerContextEffects& effects,
  330. const SkDescriptor& desc);
  331. // never null
  332. sk_sp<SkTypeface> fTypeface;
  333. // optional objects, which may be null
  334. sk_sp<SkPathEffect> fPathEffect;
  335. sk_sp<SkMaskFilter> fMaskFilter;
  336. // if this is set, we draw the image from a path, rather than
  337. // calling generateImage.
  338. bool fGenerateImageFromPath;
  339. /** Returns false if the glyph has no path at all. */
  340. bool internalGetPath(SkPackedGlyphID id, SkPath* devPath);
  341. // SkMaskGamma::PreBlend converts linear masks to gamma correcting masks.
  342. protected:
  343. // Visible to subclasses so that generateImage can apply the pre-blend directly.
  344. const SkMaskGamma::PreBlend fPreBlend;
  345. };
  346. #define kRec_SkDescriptorTag SkSetFourByteTag('s', 'r', 'e', 'c')
  347. #define kEffects_SkDescriptorTag SkSetFourByteTag('e', 'f', 'c', 't')
  348. ///////////////////////////////////////////////////////////////////////////////
  349. SkFontHinting SkScalerContextRec::getHinting() const {
  350. unsigned hint = (fFlags & SkScalerContext::kHinting_Mask) >>
  351. SkScalerContext::kHinting_Shift;
  352. return static_cast<SkFontHinting>(hint);
  353. }
  354. void SkScalerContextRec::setHinting(SkFontHinting hinting) {
  355. fFlags = (fFlags & ~SkScalerContext::kHinting_Mask) |
  356. (static_cast<unsigned>(hinting) << SkScalerContext::kHinting_Shift);
  357. }
  358. #endif