forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgfxFont.h
2217 lines (1907 loc) · 86.6 KB
/
gfxFont.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=4 et sw=4 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef GFX_FONT_H
#define GFX_FONT_H
#include "gfxTypes.h"
#include "gfxFontEntry.h"
#include "nsString.h"
#include "gfxPoint.h"
#include "nsTArray.h"
#include "nsTHashtable.h"
#include "nsHashKeys.h"
#include "gfxRect.h"
#include "nsExpirationTracker.h"
#include "gfxPlatform.h"
#include "nsIAtom.h"
#include "mozilla/HashFunctions.h"
#include "nsIMemoryReporter.h"
#include "nsIObserver.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Attributes.h"
#include <algorithm>
#include "DrawMode.h"
#include "nsDataHashtable.h"
#include "harfbuzz/hb.h"
#include "mozilla/gfx/2D.h"
#include "nsColor.h"
typedef struct _cairo cairo_t;
typedef struct _cairo_scaled_font cairo_scaled_font_t;
//typedef struct gr_face gr_face;
#ifdef DEBUG
#include <stdio.h>
#endif
class gfxContext;
class gfxTextRun;
class gfxFont;
class gfxGlyphExtents;
class gfxShapedText;
class gfxShapedWord;
class gfxSkipChars;
class gfxTextContextPaint;
#define FONT_MAX_SIZE 2000.0
#define NO_FONT_LANGUAGE_OVERRIDE 0
#define SMALL_CAPS_SCALE_FACTOR 0.8
// The skew factor used for synthetic-italic [oblique] fonts;
// we use a platform-dependent value to harmonize with the platform's own APIs.
#ifdef XP_WIN
#define OBLIQUE_SKEW_FACTOR 0.3
#elif defined(MOZ_WIDGET_GTK) || defined(MOZ_WIDGET_QT)
#define OBLIQUE_SKEW_FACTOR 0.2
#else
#define OBLIQUE_SKEW_FACTOR 0.25
#endif
struct gfxTextRunDrawCallbacks;
namespace mozilla {
namespace gfx {
class GlyphRenderingOptions;
} // namespace gfx
} // namespace mozilla
struct gfxFontStyle {
gfxFontStyle();
gfxFontStyle(uint8_t aStyle, uint16_t aWeight, int16_t aStretch,
gfxFloat aSize, nsIAtom *aLanguage, bool aExplicitLanguage,
float aSizeAdjust, bool aSystemFont,
bool aPrinterFont,
bool aWeightSynthesis, bool aStyleSynthesis,
const nsString& aLanguageOverride);
gfxFontStyle(const gfxFontStyle& aStyle);
// the language (may be an internal langGroup code rather than an actual
// language code) specified in the document or element's lang property,
// or inferred from the charset
RefPtr<nsIAtom> language;
// Features are composed of (1) features from style rules (2) features
// from feature setttings rules and (3) family-specific features. (1) and
// (3) are guaranteed to be mutually exclusive
// custom opentype feature settings
nsTArray<gfxFontFeature> featureSettings;
// Some font-variant property values require font-specific settings
// defined via @font-feature-values rules. These are resolved after
// font matching occurs.
// -- list of value tags for specific alternate features
nsTArray<gfxAlternateValue> alternateValues;
// -- object used to look these up once the font is matched
RefPtr<gfxFontFeatureValueSet> featureValueLookup;
// The logical size of the font, in pixels
gfxFloat size;
// The aspect-value (ie., the ratio actualsize:actualxheight) that any
// actual physical font created from this font structure must have when
// rendering or measuring a string. A value of -1.0 means no adjustment
// needs to be done; otherwise the value must be nonnegative.
float sizeAdjust;
// baseline offset, used when simulating sub/superscript glyphs
float baselineOffset;
// Language system tag, to override document language;
// an OpenType "language system" tag represented as a 32-bit integer
// (see http://www.microsoft.com/typography/otspec/languagetags.htm).
// Normally 0, so font rendering will use the document or element language
// (see above) to control any language-specific rendering, but the author
// can override this for cases where the options implemented in the font
// do not directly match the actual language. (E.g. lang may be Macedonian,
// but the font in use does not explicitly support this; the author can
// use font-language-override to request the Serbian option in the font
// in order to get correct glyph shapes.)
uint32_t languageOverride;
// The weight of the font: 100, 200, ... 900.
uint16_t weight;
// The stretch of the font (the sum of various NS_FONT_STRETCH_*
// constants; see gfxFontConstants.h).
int8_t stretch;
// Say that this font is a system font and therefore does not
// require certain fixup that we do for fonts from untrusted
// sources.
bool systemFont : 1;
// Say that this font is used for print or print preview.
bool printerFont : 1;
// Used to imitate -webkit-font-smoothing: antialiased
bool useGrayscaleAntialiasing : 1;
// The style of font (normal, italic, oblique)
uint8_t style : 2;
// Whether synthetic styles are allowed
bool allowSyntheticWeight : 1;
bool allowSyntheticStyle : 1;
// some variant features require fallback which complicates the shaping
// code, so set up a bool to indicate when shaping with fallback is needed
bool noFallbackVariantFeatures : 1;
// whether the |language| field comes from explicit lang tagging in the
// document, or was inferred from charset/system locale
bool explicitLanguage : 1;
// caps variant (small-caps, petite-caps, etc.)
uint8_t variantCaps;
// sub/superscript variant
uint8_t variantSubSuper;
// Return the final adjusted font size for the given aspect ratio.
// Not meant to be called when sizeAdjust = -1.0.
gfxFloat GetAdjustedSize(gfxFloat aspect) const {
NS_ASSERTION(sizeAdjust >= 0.0, "Not meant to be called when sizeAdjust = -1.0");
gfxFloat adjustedSize = std::max(NS_round(size*(sizeAdjust/aspect)), 1.0);
return std::min(adjustedSize, FONT_MAX_SIZE);
}
PLDHashNumber Hash() const {
return ((style + (systemFont << 7) +
(weight << 8)) + uint32_t(size*1000) + uint32_t(sizeAdjust*1000)) ^
nsISupportsHashKey::HashKey(language);
}
int8_t ComputeWeight() const;
// Adjust this style to simulate sub/superscript (as requested in the
// variantSubSuper field) using size and baselineOffset instead.
void AdjustForSubSuperscript(int32_t aAppUnitsPerDevPixel);
bool Equals(const gfxFontStyle& other) const {
return
(*reinterpret_cast<const uint64_t*>(&size) ==
*reinterpret_cast<const uint64_t*>(&other.size)) &&
(style == other.style) &&
(variantCaps == other.variantCaps) &&
(variantSubSuper == other.variantSubSuper) &&
(allowSyntheticWeight == other.allowSyntheticWeight) &&
(allowSyntheticStyle == other.allowSyntheticStyle) &&
(systemFont == other.systemFont) &&
(printerFont == other.printerFont) &&
(useGrayscaleAntialiasing == other.useGrayscaleAntialiasing) &&
(explicitLanguage == other.explicitLanguage) &&
(weight == other.weight) &&
(stretch == other.stretch) &&
(language == other.language) &&
(baselineOffset == other.baselineOffset) &&
(*reinterpret_cast<const uint32_t*>(&sizeAdjust) ==
*reinterpret_cast<const uint32_t*>(&other.sizeAdjust)) &&
(featureSettings == other.featureSettings) &&
(languageOverride == other.languageOverride) &&
(alternateValues == other.alternateValues) &&
(featureValueLookup == other.featureValueLookup);
}
static void ParseFontFeatureSettings(const nsString& aFeatureString,
nsTArray<gfxFontFeature>& aFeatures);
static uint32_t ParseFontLanguageOverride(const nsString& aLangTag);
};
struct gfxTextRange {
enum {
// flags for recording the kind of font-matching that was used
kFontGroup = 0x0001,
kPrefsFallback = 0x0002,
kSystemFallback = 0x0004
};
gfxTextRange(uint32_t aStart, uint32_t aEnd,
gfxFont* aFont, uint8_t aMatchType,
uint16_t aOrientation)
: start(aStart),
end(aEnd),
font(aFont),
matchType(aMatchType),
orientation(aOrientation)
{ }
uint32_t Length() const { return end - start; }
uint32_t start, end;
RefPtr<gfxFont> font;
uint8_t matchType;
uint16_t orientation;
};
/**
* Font cache design:
*
* The mFonts hashtable contains most fonts, indexed by (gfxFontEntry*, style).
* It does not add a reference to the fonts it contains.
* When a font's refcount decreases to zero, instead of deleting it we
* add it to our expiration tracker.
* The expiration tracker tracks fonts with zero refcount. After a certain
* period of time, such fonts expire and are deleted.
*
* We're using 3 generations with a ten-second generation interval, so
* zero-refcount fonts will be deleted 20-30 seconds after their refcount
* goes to zero, if timer events fire in a timely manner.
*
* The font cache also handles timed expiration of cached ShapedWords
* for "persistent" fonts: it has a repeating timer, and notifies
* each cached font to "age" its shaped words. The words will be released
* by the fonts if they get aged three times without being re-used in the
* meantime.
*
* Note that the ShapedWord timeout is much larger than the font timeout,
* so that in the case of a short-lived font, we'll discard the gfxFont
* completely, with all its words, and avoid the cost of aging the words
* individually. That only happens with longer-lived fonts.
*/
struct FontCacheSizes {
FontCacheSizes()
: mFontInstances(0), mShapedWords(0)
{ }
size_t mFontInstances; // memory used by instances of gfxFont subclasses
size_t mShapedWords; // memory used by the per-font shapedWord caches
};
class gfxFontCache final : public nsExpirationTracker<gfxFont,3> {
public:
enum {
FONT_TIMEOUT_SECONDS = 10,
SHAPED_WORD_TIMEOUT_SECONDS = 60
};
gfxFontCache();
~gfxFontCache();
/*
* Get the global gfxFontCache. You must call Init() before
* calling this method --- the result will not be null.
*/
static gfxFontCache* GetCache() {
return gGlobalCache;
}
static nsresult Init();
// It's OK to call this even if Init() has not been called.
static void Shutdown();
// Look up a font in the cache. Returns an addrefed pointer, or null
// if there's nothing matching in the cache
already_AddRefed<gfxFont>
Lookup(const gfxFontEntry* aFontEntry,
const gfxFontStyle* aStyle,
const gfxCharacterMap* aUnicodeRangeMap = nullptr);
// We created a new font (presumably because Lookup returned null);
// put it in the cache. The font's refcount should be nonzero. It is
// allowable to add a new font even if there is one already in the
// cache with the same key; we'll forget about the old one.
void AddNew(gfxFont *aFont);
// The font's refcount has gone to zero; give ownership of it to
// the cache. We delete it if it's not acquired again after a certain
// amount of time.
void NotifyReleased(gfxFont *aFont);
// This gets called when the timeout has expired on a zero-refcount
// font; we just delete it.
virtual void NotifyExpired(gfxFont *aFont) override;
// Cleans out the hashtable and removes expired fonts waiting for cleanup.
// Other gfxFont objects may be still in use but they will be pushed
// into the expiration queues and removed.
void Flush() {
mFonts.Clear();
AgeAllGenerations();
}
void FlushShapedWordCaches();
void AddSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf,
FontCacheSizes* aSizes) const;
void AddSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf,
FontCacheSizes* aSizes) const;
protected:
class MemoryReporter final : public nsIMemoryReporter
{
~MemoryReporter() {}
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIMEMORYREPORTER
};
// Observer for notifications that the font cache cares about
class Observer final
: public nsIObserver
{
~Observer() {}
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
};
void DestroyFont(gfxFont *aFont);
static gfxFontCache *gGlobalCache;
struct Key {
const gfxFontEntry* mFontEntry;
const gfxFontStyle* mStyle;
const gfxCharacterMap* mUnicodeRangeMap;
Key(const gfxFontEntry* aFontEntry, const gfxFontStyle* aStyle,
const gfxCharacterMap* aUnicodeRangeMap)
: mFontEntry(aFontEntry), mStyle(aStyle),
mUnicodeRangeMap(aUnicodeRangeMap)
{}
};
class HashEntry : public PLDHashEntryHdr {
public:
typedef const Key& KeyType;
typedef const Key* KeyTypePointer;
// When constructing a new entry in the hashtable, we'll leave this
// blank. The caller of Put() will fill this in.
explicit HashEntry(KeyTypePointer aStr) : mFont(nullptr) { }
HashEntry(const HashEntry& toCopy) : mFont(toCopy.mFont) { }
~HashEntry() { }
bool KeyEquals(const KeyTypePointer aKey) const;
static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; }
static PLDHashNumber HashKey(const KeyTypePointer aKey) {
return mozilla::HashGeneric(aKey->mStyle->Hash(), aKey->mFontEntry,
aKey->mUnicodeRangeMap);
}
enum { ALLOW_MEMMOVE = true };
gfxFont* mFont;
};
nsTHashtable<HashEntry> mFonts;
static void WordCacheExpirationTimerCallback(nsITimer* aTimer, void* aCache);
nsCOMPtr<nsITimer> mWordCacheExpirationTimer;
};
class gfxTextPerfMetrics {
public:
struct TextCounts {
uint32_t numContentTextRuns;
uint32_t numChromeTextRuns;
uint32_t numChars;
uint32_t maxTextRunLen;
uint32_t wordCacheSpaceRules;
uint32_t wordCacheLong;
uint32_t wordCacheHit;
uint32_t wordCacheMiss;
uint32_t fallbackPrefs;
uint32_t fallbackSystem;
uint32_t textrunConst;
uint32_t textrunDestr;
uint32_t genericLookups;
};
uint32_t reflowCount;
// counts per reflow operation
TextCounts current;
// totals for the lifetime of a document
TextCounts cumulative;
gfxTextPerfMetrics() {
memset(this, 0, sizeof(gfxTextPerfMetrics));
}
// add current totals to cumulative ones
void Accumulate() {
if (current.numChars == 0) {
return;
}
cumulative.numContentTextRuns += current.numContentTextRuns;
cumulative.numChromeTextRuns += current.numChromeTextRuns;
cumulative.numChars += current.numChars;
if (current.maxTextRunLen > cumulative.maxTextRunLen) {
cumulative.maxTextRunLen = current.maxTextRunLen;
}
cumulative.wordCacheSpaceRules += current.wordCacheSpaceRules;
cumulative.wordCacheLong += current.wordCacheLong;
cumulative.wordCacheHit += current.wordCacheHit;
cumulative.wordCacheMiss += current.wordCacheMiss;
cumulative.fallbackPrefs += current.fallbackPrefs;
cumulative.fallbackSystem += current.fallbackSystem;
cumulative.textrunConst += current.textrunConst;
cumulative.textrunDestr += current.textrunDestr;
cumulative.genericLookups += current.genericLookups;
memset(¤t, 0, sizeof(current));
}
};
class gfxTextRunFactory {
NS_INLINE_DECL_REFCOUNTING(gfxTextRunFactory)
public:
typedef mozilla::gfx::DrawTarget DrawTarget;
// Flags in the mask 0xFFFF0000 are reserved for textrun clients
// Flags in the mask 0x0000F000 are reserved for per-platform fonts
// Flags in the mask 0x00000FFF are set by the textrun creator.
enum {
CACHE_TEXT_FLAGS = 0xF0000000,
USER_TEXT_FLAGS = 0x0FFF0000,
TEXTRUN_TEXT_FLAGS = 0x0000FFFF,
SETTABLE_FLAGS = CACHE_TEXT_FLAGS | USER_TEXT_FLAGS,
/**
* When set, the text string pointer used to create the text run
* is guaranteed to be available during the lifetime of the text run.
*/
TEXT_IS_PERSISTENT = 0x0001,
/**
* When set, the text is known to be all-ASCII (< 128).
*/
TEXT_IS_ASCII = 0x0002,
/**
* When set, the text is RTL.
*/
TEXT_IS_RTL = 0x0004,
/**
* When set, spacing is enabled and the textrun needs to call GetSpacing
* on the spacing provider.
*/
TEXT_ENABLE_SPACING = 0x0008,
/**
* When set, GetHyphenationBreaks may return true for some character
* positions, otherwise it will always return false for all characters.
*/
TEXT_ENABLE_HYPHEN_BREAKS = 0x0010,
/**
* When set, the text has no characters above 255 and it is stored
* in the textrun in 8-bit format.
*/
TEXT_IS_8BIT = 0x0020,
/**
* When set, the RunMetrics::mBoundingBox field will be initialized
* properly based on glyph extents, in particular, glyph extents that
* overflow the standard font-box (the box defined by the ascent, descent
* and advance width of the glyph). When not set, it may just be the
* standard font-box even if glyphs overflow.
*/
TEXT_NEED_BOUNDING_BOX = 0x0040,
/**
* When set, optional ligatures are disabled. Ligatures that are
* required for legible text should still be enabled.
*/
TEXT_DISABLE_OPTIONAL_LIGATURES = 0x0080,
/**
* When set, the textrun should favour speed of construction over
* quality. This may involve disabling ligatures and/or kerning or
* other effects.
*/
TEXT_OPTIMIZE_SPEED = 0x0100,
/**
* For internal use by the memory reporter when accounting for
* storage used by textruns.
* Because the reporter may visit each textrun multiple times while
* walking the frame trees and textrun cache, it needs to mark
* textruns that have been seen so as to avoid multiple-accounting.
*/
TEXT_RUN_SIZE_ACCOUNTED = 0x0200,
/**
* When set, the textrun should discard control characters instead of
* turning them into hexboxes.
*/
TEXT_HIDE_CONTROL_CHARACTERS = 0x0400,
/**
* Field for orientation of the textrun and glyphs within it.
* Possible values of the TEXT_ORIENT_MASK field:
* TEXT_ORIENT_HORIZONTAL
* TEXT_ORIENT_VERTICAL_UPRIGHT
* TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT
* TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT
* TEXT_ORIENT_VERTICAL_MIXED
* For all VERTICAL settings, the x and y coordinates of glyph
* positions are exchanged, so that simple advances are vertical.
*
* The MIXED value indicates vertical textRuns for which the CSS
* text-orientation property is 'mixed', but is never used for
* individual glyphRuns; it will be resolved to either UPRIGHT
* or SIDEWAYS_RIGHT according to the UTR50 properties of the
* characters, and separate glyphRuns created for the resulting
* glyph orientations.
*/
TEXT_ORIENT_MASK = 0xF000,
TEXT_ORIENT_HORIZONTAL = 0x0000,
TEXT_ORIENT_VERTICAL_UPRIGHT = 0x1000,
TEXT_ORIENT_VERTICAL_SIDEWAYS_RIGHT = 0x2000,
TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT = 0x4000,
TEXT_ORIENT_VERTICAL_MIXED = 0x8000,
/**
* nsTextFrameThebes sets these, but they're defined here rather than
* in nsTextFrameUtils.h because ShapedWord creation/caching also needs
* to check the _INCOMING flag
*/
TEXT_TRAILING_ARABICCHAR = 0x20000000,
/**
* When set, the previous character for this textrun was an Arabic
* character. This is used for the context detection necessary for
* bidi.numeral implementation.
*/
TEXT_INCOMING_ARABICCHAR = 0x40000000,
// Set if the textrun should use the OpenType 'math' script.
TEXT_USE_MATH_SCRIPT = 0x80000000,
TEXT_UNUSED_FLAGS = 0x10000000
};
/**
* This record contains all the parameters needed to initialize a textrun.
*/
struct Parameters {
// Shape text params suggesting where the textrun will be rendered
DrawTarget *mDrawTarget;
// Pointer to arbitrary user data (which should outlive the textrun)
void *mUserData;
// A description of which characters have been stripped from the original
// DOM string to produce the characters in the textrun. May be null
// if that information is not relevant.
gfxSkipChars *mSkipChars;
// A list of where linebreaks are currently placed in the textrun. May
// be null if mInitialBreakCount is zero.
uint32_t *mInitialBreaks;
uint32_t mInitialBreakCount;
// The ratio to use to convert device pixels to application layout units
int32_t mAppUnitsPerDevUnit;
};
protected:
// Protected destructor, to discourage deletion outside of Release():
virtual ~gfxTextRunFactory() {}
};
/**
* gfxFontShaper
*
* This class implements text shaping (character to glyph mapping and
* glyph layout). There is a gfxFontShaper subclass for each text layout
* technology (uniscribe, core text, harfbuzz,....) we support.
*
* The shaper is responsible for setting up glyph data in gfxTextRuns.
*
* A generic, platform-independent shaper relies only on the standard
* gfxFont interface and can work with any concrete subclass of gfxFont.
*
* Platform-specific implementations designed to interface to platform
* shaping APIs such as Uniscribe or CoreText may rely on features of a
* specific font subclass to access native font references
* (such as CTFont, HFONT, DWriteFont, etc).
*/
class gfxFontShaper {
public:
typedef mozilla::gfx::DrawTarget DrawTarget;
typedef mozilla::unicode::Script Script;
explicit gfxFontShaper(gfxFont *aFont)
: mFont(aFont)
{
NS_ASSERTION(aFont, "shaper requires a valid font!");
}
virtual ~gfxFontShaper() { }
// Shape a piece of text and store the resulting glyph data into
// aShapedText. Parameters aOffset/aLength indicate the range of
// aShapedText to be updated; aLength is also the length of aText.
virtual bool ShapeText(DrawTarget *aDrawTarget,
const char16_t *aText,
uint32_t aOffset,
uint32_t aLength,
Script aScript,
bool aVertical,
gfxShapedText *aShapedText) = 0;
gfxFont *GetFont() const { return mFont; }
static void
MergeFontFeatures(const gfxFontStyle *aStyle,
const nsTArray<gfxFontFeature>& aFontFeatures,
bool aDisableLigatures,
const nsAString& aFamilyName,
bool aAddSmallCaps,
void (*aHandleFeature)(const uint32_t&,
uint32_t&, void*),
void* aHandleFeatureData);
protected:
// Work out whether cairo will snap inter-glyph spacing to pixels.
static void GetRoundOffsetsToPixels(DrawTarget* aDrawTarget,
bool* aRoundX, bool* aRoundY);
// the font this shaper is working with. The font owns a UniquePtr reference
// to this object, and will destroy it before it dies. Thus, mFont will always
// be valid.
gfxFont* MOZ_NON_OWNING_REF mFont;
};
/*
* gfxShapedText is an abstract superclass for gfxShapedWord and gfxTextRun.
* These are objects that store a list of zero or more glyphs for each character.
* For each glyph we store the glyph ID, the advance, and possibly x/y-offsets.
* The idea is that a string is rendered by a loop that draws each glyph
* at its designated offset from the current point, then advances the current
* point by the glyph's advance in the direction of the textrun (LTR or RTL).
* Each glyph advance is always rounded to the nearest appunit; this ensures
* consistent results when dividing the text in a textrun into multiple text
* frames (frame boundaries are always aligned to appunits). We optimize
* for the case where a character has a single glyph and zero xoffset and yoffset,
* and the glyph ID and advance are in a reasonable range so we can pack all
* necessary data into 32 bits.
*
* gfxFontShaper can shape text into either a gfxShapedWord (cached by a gfxFont)
* or directly into a gfxTextRun (for cases where we want to shape textruns in
* their entirety rather than using cached words, because there may be layout
* features that depend on the inter-word spaces).
*/
class gfxShapedText
{
public:
typedef mozilla::unicode::Script Script;
gfxShapedText(uint32_t aLength, uint32_t aFlags,
int32_t aAppUnitsPerDevUnit)
: mLength(aLength)
, mFlags(aFlags)
, mAppUnitsPerDevUnit(aAppUnitsPerDevUnit)
{ }
virtual ~gfxShapedText() { }
/**
* This class records the information associated with a character in the
* input string. It's optimized for the case where there is one glyph
* representing that character alone.
*
* A character can have zero or more associated glyphs. Each glyph
* has an advance width and an x and y offset.
* A character may be the start of a cluster.
* A character may be the start of a ligature group.
* A character can be "missing", indicating that the system is unable
* to render the character.
*
* All characters in a ligature group conceptually share all the glyphs
* associated with the characters in a group.
*/
class CompressedGlyph {
public:
CompressedGlyph() { mValue = 0; }
enum {
// Indicates that a cluster and ligature group starts at this
// character; this character has a single glyph with a reasonable
// advance and zero offsets. A "reasonable" advance
// is one that fits in the available bits (currently 12) (specified
// in appunits).
FLAG_IS_SIMPLE_GLYPH = 0x80000000U,
// Indicates whether a linebreak is allowed before this character;
// this is a two-bit field that holds a FLAG_BREAK_TYPE_xxx value
// indicating the kind of linebreak (if any) allowed here.
FLAGS_CAN_BREAK_BEFORE = 0x60000000U,
FLAGS_CAN_BREAK_SHIFT = 29,
FLAG_BREAK_TYPE_NONE = 0,
FLAG_BREAK_TYPE_NORMAL = 1,
FLAG_BREAK_TYPE_HYPHEN = 2,
FLAG_CHAR_IS_SPACE = 0x10000000U,
// The advance is stored in appunits
ADVANCE_MASK = 0x0FFF0000U,
ADVANCE_SHIFT = 16,
GLYPH_MASK = 0x0000FFFFU,
// Non-simple glyphs may or may not have glyph data in the
// corresponding mDetailedGlyphs entry. They have the following
// flag bits:
// When NOT set, indicates that this character corresponds to a
// missing glyph and should be skipped (or possibly, render the character
// Unicode value in some special way). If there are glyphs,
// the mGlyphID is actually the UTF16 character code. The bit is
// inverted so we can memset the array to zero to indicate all missing.
FLAG_NOT_MISSING = 0x01,
FLAG_NOT_CLUSTER_START = 0x02,
FLAG_NOT_LIGATURE_GROUP_START = 0x04,
FLAG_CHAR_IS_TAB = 0x08,
FLAG_CHAR_IS_NEWLINE = 0x10,
// Per CSS Text Decoration Module Level 3, emphasis marks are not
// drawn for any character in Unicode categories Z*, Cc, Cf, and Cn
// which is not combined with any combining characters. This flag is
// set for all those characters except 0x20 whitespace.
FLAG_CHAR_NO_EMPHASIS_MARK = 0x20,
CHAR_TYPE_FLAGS_MASK = 0x38,
GLYPH_COUNT_MASK = 0x00FFFF00U,
GLYPH_COUNT_SHIFT = 8
};
// "Simple glyphs" have a simple glyph ID, simple advance and their
// x and y offsets are zero. Also the glyph extents do not overflow
// the font-box defined by the font ascent, descent and glyph advance width.
// These case is optimized to avoid storing DetailedGlyphs.
// Returns true if the glyph ID aGlyph fits into the compressed representation
static bool IsSimpleGlyphID(uint32_t aGlyph) {
return (aGlyph & GLYPH_MASK) == aGlyph;
}
// Returns true if the advance aAdvance fits into the compressed representation.
// aAdvance is in appunits.
static bool IsSimpleAdvance(uint32_t aAdvance) {
return (aAdvance & (ADVANCE_MASK >> ADVANCE_SHIFT)) == aAdvance;
}
bool IsSimpleGlyph() const { return (mValue & FLAG_IS_SIMPLE_GLYPH) != 0; }
uint32_t GetSimpleAdvance() const { return (mValue & ADVANCE_MASK) >> ADVANCE_SHIFT; }
uint32_t GetSimpleGlyph() const { return mValue & GLYPH_MASK; }
bool IsMissing() const { return (mValue & (FLAG_NOT_MISSING|FLAG_IS_SIMPLE_GLYPH)) == 0; }
bool IsClusterStart() const {
return (mValue & FLAG_IS_SIMPLE_GLYPH) || !(mValue & FLAG_NOT_CLUSTER_START);
}
bool IsLigatureGroupStart() const {
return (mValue & FLAG_IS_SIMPLE_GLYPH) || !(mValue & FLAG_NOT_LIGATURE_GROUP_START);
}
bool IsLigatureContinuation() const {
return (mValue & FLAG_IS_SIMPLE_GLYPH) == 0 &&
(mValue & (FLAG_NOT_LIGATURE_GROUP_START | FLAG_NOT_MISSING)) ==
(FLAG_NOT_LIGATURE_GROUP_START | FLAG_NOT_MISSING);
}
// Return true if the original character was a normal (breakable,
// trimmable) space (U+0020). Not true for other characters that
// may happen to map to the space glyph (U+00A0).
bool CharIsSpace() const {
return (mValue & FLAG_CHAR_IS_SPACE) != 0;
}
bool CharIsTab() const {
return !IsSimpleGlyph() && (mValue & FLAG_CHAR_IS_TAB) != 0;
}
bool CharIsNewline() const {
return !IsSimpleGlyph() && (mValue & FLAG_CHAR_IS_NEWLINE) != 0;
}
bool CharMayHaveEmphasisMark() const {
return !CharIsSpace() &&
(IsSimpleGlyph() || !(mValue & FLAG_CHAR_NO_EMPHASIS_MARK));
}
uint32_t CharTypeFlags() const {
return IsSimpleGlyph() ? 0 : (mValue & CHAR_TYPE_FLAGS_MASK);
}
void SetClusterStart(bool aIsClusterStart) {
NS_ASSERTION(!IsSimpleGlyph(),
"can't call SetClusterStart on simple glyphs");
if (aIsClusterStart) {
mValue &= ~FLAG_NOT_CLUSTER_START;
} else {
mValue |= FLAG_NOT_CLUSTER_START;
}
}
uint8_t CanBreakBefore() const {
return (mValue & FLAGS_CAN_BREAK_BEFORE) >> FLAGS_CAN_BREAK_SHIFT;
}
// Returns FLAGS_CAN_BREAK_BEFORE if the setting changed, 0 otherwise
uint32_t SetCanBreakBefore(uint8_t aCanBreakBefore) {
NS_ASSERTION(aCanBreakBefore <= 2,
"Bogus break-before value!");
uint32_t breakMask = (uint32_t(aCanBreakBefore) << FLAGS_CAN_BREAK_SHIFT);
uint32_t toggle = breakMask ^ (mValue & FLAGS_CAN_BREAK_BEFORE);
mValue ^= toggle;
return toggle;
}
CompressedGlyph& SetSimpleGlyph(uint32_t aAdvanceAppUnits, uint32_t aGlyph) {
NS_ASSERTION(IsSimpleAdvance(aAdvanceAppUnits), "Advance overflow");
NS_ASSERTION(IsSimpleGlyphID(aGlyph), "Glyph overflow");
NS_ASSERTION(!CharTypeFlags(), "Char type flags lost");
mValue = (mValue & (FLAGS_CAN_BREAK_BEFORE | FLAG_CHAR_IS_SPACE)) |
FLAG_IS_SIMPLE_GLYPH |
(aAdvanceAppUnits << ADVANCE_SHIFT) | aGlyph;
return *this;
}
CompressedGlyph& SetComplex(bool aClusterStart, bool aLigatureStart,
uint32_t aGlyphCount) {
mValue = (mValue & (FLAGS_CAN_BREAK_BEFORE | FLAG_CHAR_IS_SPACE)) |
FLAG_NOT_MISSING |
CharTypeFlags() |
(aClusterStart ? 0 : FLAG_NOT_CLUSTER_START) |
(aLigatureStart ? 0 : FLAG_NOT_LIGATURE_GROUP_START) |
(aGlyphCount << GLYPH_COUNT_SHIFT);
return *this;
}
/**
* Missing glyphs are treated as ligature group starts; don't mess with
* the cluster-start flag (see bugs 618870 and 619286).
*/
CompressedGlyph& SetMissing(uint32_t aGlyphCount) {
mValue = (mValue & (FLAGS_CAN_BREAK_BEFORE | FLAG_NOT_CLUSTER_START |
FLAG_CHAR_IS_SPACE)) |
CharTypeFlags() |
(aGlyphCount << GLYPH_COUNT_SHIFT);
return *this;
}
uint32_t GetGlyphCount() const {
NS_ASSERTION(!IsSimpleGlyph(), "Expected non-simple-glyph");
return (mValue & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT;
}
void SetIsSpace() {
mValue |= FLAG_CHAR_IS_SPACE;
}
void SetIsTab() {
NS_ASSERTION(!IsSimpleGlyph(), "Expected non-simple-glyph");
mValue |= FLAG_CHAR_IS_TAB;
}
void SetIsNewline() {
NS_ASSERTION(!IsSimpleGlyph(), "Expected non-simple-glyph");
mValue |= FLAG_CHAR_IS_NEWLINE;
}
void SetNoEmphasisMark() {
NS_ASSERTION(!IsSimpleGlyph(), "Expected non-simple-glyph");
mValue |= FLAG_CHAR_NO_EMPHASIS_MARK;
}
private:
uint32_t mValue;
};
// Accessor for the array of CompressedGlyph records, which will be in
// a different place in gfxShapedWord vs gfxTextRun
virtual CompressedGlyph *GetCharacterGlyphs() = 0;
/**
* When the glyphs for a character don't fit into a CompressedGlyph record
* in SimpleGlyph format, we use an array of DetailedGlyphs instead.
*/
struct DetailedGlyph {
/** The glyphID, or the Unicode character
* if this is a missing glyph */
uint32_t mGlyphID;
/** The advance, x-offset and y-offset of the glyph, in appunits
* mAdvance is in the text direction (RTL or LTR)
* mXOffset is always from left to right
* mYOffset is always from top to bottom */
int32_t mAdvance;
float mXOffset, mYOffset;
};
void SetGlyphs(uint32_t aCharIndex, CompressedGlyph aGlyph,
const DetailedGlyph *aGlyphs);
void SetMissingGlyph(uint32_t aIndex, uint32_t aChar, gfxFont *aFont);
void SetIsSpace(uint32_t aIndex) {
GetCharacterGlyphs()[aIndex].SetIsSpace();
}
bool HasDetailedGlyphs() const {
return mDetailedGlyphs != nullptr;
}
bool IsLigatureGroupStart(uint32_t aPos) {
NS_ASSERTION(aPos < GetLength(), "aPos out of range");
return GetCharacterGlyphs()[aPos].IsLigatureGroupStart();
}
// NOTE that this must not be called for a character offset that does
// not have any DetailedGlyph records; callers must have verified that
// GetCharacterGlyphs()[aCharIndex].GetGlyphCount() is greater than zero.
DetailedGlyph *GetDetailedGlyphs(uint32_t aCharIndex) {
NS_ASSERTION(GetCharacterGlyphs() && HasDetailedGlyphs() &&
!GetCharacterGlyphs()[aCharIndex].IsSimpleGlyph() &&
GetCharacterGlyphs()[aCharIndex].GetGlyphCount() > 0,
"invalid use of GetDetailedGlyphs; check the caller!");
return mDetailedGlyphs->Get(aCharIndex);
}
void AdjustAdvancesForSyntheticBold(float aSynBoldOffset,
uint32_t aOffset, uint32_t aLength);
// Mark clusters in the CompressedGlyph records, starting at aOffset,
// based on the Unicode properties of the text in aString.
// This is also responsible to set the IsSpace flag for space characters.
void SetupClusterBoundaries(uint32_t aOffset,
const char16_t *aString,
uint32_t aLength);
// In 8-bit text, there won't actually be any clusters, but we still need
// the space-marking functionality.
void SetupClusterBoundaries(uint32_t aOffset,
const uint8_t *aString,
uint32_t aLength);
uint32_t GetFlags() const {
return mFlags;
}
bool IsVertical() const {
return (GetFlags() & gfxTextRunFactory::TEXT_ORIENT_MASK) !=
gfxTextRunFactory::TEXT_ORIENT_HORIZONTAL;
}
bool UseCenterBaseline() const {
uint32_t orient = GetFlags() & gfxTextRunFactory::TEXT_ORIENT_MASK;
return orient == gfxTextRunFactory::TEXT_ORIENT_VERTICAL_MIXED ||
orient == gfxTextRunFactory::TEXT_ORIENT_VERTICAL_UPRIGHT;
}
bool IsRightToLeft() const {
return (GetFlags() & gfxTextRunFactory::TEXT_IS_RTL) != 0;
}
bool IsSidewaysLeft() const {
return (GetFlags() & gfxTextRunFactory::TEXT_ORIENT_MASK) ==
gfxTextRunFactory::TEXT_ORIENT_VERTICAL_SIDEWAYS_LEFT;
}
// Return true if the logical inline direction is reversed compared to
// normal physical coordinates (i.e. if it is leftwards or upwards)
bool IsInlineReversed() const {
return IsSidewaysLeft() != IsRightToLeft();
}
gfxFloat GetDirection() const {
return IsInlineReversed() ? -1.0f : 1.0f;
}
bool DisableLigatures() const {
return (GetFlags() &