Add font features (such as tabular numbers) as an option in text styles (flutter/engine#8823)

Fixes https://github.com/flutter/flutter/issues/31691
This commit is contained in:
Jason Simmons
2019-05-21 16:47:57 -07:00
committed by GitHub
parent 99fa9d5c3a
commit 869c92a3d7
13 changed files with 351 additions and 15 deletions

View File

@@ -1060,6 +1060,8 @@ FILE: ../../../flutter/third_party/txt/src/txt/font_asset_provider.cc
FILE: ../../../flutter/third_party/txt/src/txt/font_asset_provider.h
FILE: ../../../flutter/third_party/txt/src/txt/font_collection.cc
FILE: ../../../flutter/third_party/txt/src/txt/font_collection.h
FILE: ../../../flutter/third_party/txt/src/txt/font_features.cc
FILE: ../../../flutter/third_party/txt/src/txt/font_features.h
FILE: ../../../flutter/third_party/txt/src/txt/font_skia.cc
FILE: ../../../flutter/third_party/txt/src/txt/font_skia.h
FILE: ../../../flutter/third_party/txt/src/txt/font_style.h

View File

@@ -15,6 +15,11 @@ class _Logger {
static void _printString(String s) native 'Logger_PrintString';
}
// If we actually run on big endian machines, we'll need to do something smarter
// here. We don't use [Endian.Host] because it's not a compile-time
// constant and can't propagate into the set/get calls.
const Endian _kFakeHostEndian = Endian.little;
// A service protocol extension to schedule a frame to be rendered into the
// window.
Future<developer.ServiceExtensionResponse> _scheduleFrame(

View File

@@ -1019,11 +1019,6 @@ enum Clip {
antiAliasWithSaveLayer,
}
// If we actually run on big endian machines, we'll need to do something smarter
// here. We don't use [Endian.Host] because it's not a compile-time
// constant and can't propagate into the set/get calls.
const Endian _kFakeHostEndian = Endian.little;
// Indicates that the image should not be resized in this dimension.
//
// Used by [instantiateImageCodec] as a magical value to disable resizing

View File

@@ -102,6 +102,145 @@ class FontWeight {
}
}
/// A feature tag and value that affect the selection of glyphs in a font.
class FontFeature {
/// Creates a [FontFeature] object, which can be added to a [TextStyle] to
/// change how the engine selects glyphs when rendering text.
///
/// `feature` is the four-character tag that identifies the feature.
/// These tags are specified by font formats such as OpenType.
///
/// `value` is the value that the feature will be set to. The behavior
/// of the value depends on the specific feature. Many features are
/// flags whose value can be 1 (when enabled) or 0 (when disabled).
///
/// See <https://docs.microsoft.com/en-us/typography/opentype/spec/featuretags>
const FontFeature(this.feature, [ this.value = 1 ]) : assert(feature != null), assert(feature.length == 4), assert(value != null), assert(value >= 0);
/// Create a [FontFeature] object that enables the feature with the given tag.
const FontFeature.enable(String feature) : this(feature, 1);
/// Create a [FontFeature] object that disables the feature with the given tag.
const FontFeature.disable(String feature) : this(feature, 0);
/// Randomize the alternate forms used in text.
///
/// For example, this can be used with suitably-prepared handwriting fonts to
/// vary the forms used for each character, so that, for instance, the word
/// "cross-section" would be rendered with two different "c"s, two different "o"s,
/// and three different "s"s.
///
/// See also:
///
/// * <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#rand>
const FontFeature.randomize() : feature = 'rand', value = 1;
/// Select a stylistic set.
///
/// Fonts may have up to 20 stylistic sets, numbered 1 through 20.
///
/// See also:
///
/// * <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#ssxx>
factory FontFeature.stylisticSet(int value) {
assert(value >= 1);
assert(value <= 20);
return FontFeature('ss${value.toString().padLeft(2, "0")}');
}
/// Use the slashed zero.
///
/// Some fonts contain both a circular zero and a zero with a slash. This
/// enables the use of the latter form.
///
/// This is overridden by [FontFeature.oldstyleFigures].
///
/// See also:
///
/// * <https://docs.microsoft.com/en-us/typography/opentype/spec/features_uz#zero>
const FontFeature.slashedZero() : feature = 'zero', value = 1;
/// Use oldstyle figures.
///
/// Some fonts have variants of the figures (e.g. the digit 9) that, when
/// this feature is enabled, render with descenders under the baseline instead
/// of being entirely above the baseline.
///
/// This overrides [FontFeature.slashedZero].
///
/// See also:
///
/// * <https://docs.microsoft.com/en-us/typography/opentype/spec/features_ko#onum>
const FontFeature.oldstyleFigures() : feature = 'onum', value = 1;
/// Use proportional (varying width) figures.
///
/// For fonts that have both proportional and tabular (monospace) figures,
/// this enables the proportional figures.
///
/// This is mutually exclusive with [FontFeature.tabularFigures].
///
/// The default behavior varies from font to font.
///
/// See also:
///
/// * <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#pnum>
const FontFeature.proportionalFigures() : feature = 'pnum', value = 1;
/// Use tabular (monospace) figures.
///
/// For fonts that have both proportional (varying width) and tabular figures,
/// this enables the tabular figures.
///
/// This is mutually exclusive with [FontFeature.proportionalFigures].
///
/// The default behavior varies from font to font.
///
/// See also:
///
/// * <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#tnum>
const FontFeature.tabularFigures() : feature = 'tnum', value = 1;
/// The tag that identifies the effect of this feature. Must consist of 4
/// ASCII characters (typically lowercase letters).
///
/// See <https://docs.microsoft.com/en-us/typography/opentype/spec/featuretags>
final String feature;
/// The value assigned to this feature.
///
/// Must be a positive integer. Many features are Boolean values that accept
/// values of either 0 (feature is disabled) or 1 (feature is enabled).
final int value;
static const int _kEncodedSize = 8;
void _encode(ByteData byteData) {
assert(feature.codeUnits.every((int c) => c >= 0x20 && c <= 0x7F));
for (int i = 0; i < 4; i++) {
byteData.setUint8(i, feature.codeUnitAt(i));
}
byteData.setInt32(4, value, _kFakeHostEndian);
}
@override
bool operator ==(dynamic other) {
if (identical(this, other))
return true;
if (other.runtimeType != runtimeType)
return false;
final FontFeature typedOther = other;
return feature == typedOther.feature
&& value == typedOther.value;
}
@override
int get hashCode => hashValues(feature, value);
@override
String toString() => 'FontFeature($feature, $value)';
}
/// Whether and how to align text horizontally.
// The order of this enum must match the order of the values in RenderStyleConstants.h's ETextAlign.
enum TextAlign {
@@ -281,7 +420,8 @@ Int32List _encodeTextStyle(
Locale locale,
Paint background,
Paint foreground,
List<Shadow> shadows
List<Shadow> shadows,
List<FontFeature> fontFeatures,
) {
final Int32List result = Int32List(8);
if (color != null) {
@@ -351,6 +491,10 @@ Int32List _encodeTextStyle(
result[0] |= 1 << 17;
// Passed separately to native.
}
if (fontFeatures != null) {
result[0] |= 1 << 18;
// Passed separately to native.
}
return result;
}
@@ -387,6 +531,7 @@ class TextStyle {
/// * `locale`: The locale used to select region-specific glyphs.
/// * `background`: The paint drawn as a background for the text.
/// * `foreground`: The paint used to draw the text. If this is specified, `color` must be null.
/// * `fontFeatures`: The font features that should be applied to the text.
TextStyle({
Color color,
TextDecoration decoration,
@@ -406,6 +551,7 @@ class TextStyle {
Paint background,
Paint foreground,
List<Shadow> shadows,
List<FontFeature> fontFeatures,
}) : assert(color == null || foreground == null,
'Cannot provide both a color and a foreground\n'
'The color argument is just a shorthand for "foreground: Paint()..color = color".'
@@ -429,6 +575,7 @@ class TextStyle {
background,
foreground,
shadows,
fontFeatures,
),
_fontFamily = fontFamily ?? '',
_fontFamilyFallback = fontFamilyFallback,
@@ -440,7 +587,8 @@ class TextStyle {
_locale = locale,
_background = background,
_foreground = foreground,
_shadows = shadows;
_shadows = shadows,
_fontFeatures = fontFeatures;
final Int32List _encoded;
final String _fontFamily;
@@ -454,6 +602,7 @@ class TextStyle {
final Paint _background;
final Paint _foreground;
final List<Shadow> _shadows;
final List<FontFeature> _fontFeatures;
@override
bool operator ==(dynamic other) {
@@ -480,11 +629,13 @@ class TextStyle {
return false;
if (!_listEquals<String>(_fontFamilyFallback, typedOther._fontFamilyFallback))
return false;
if (!_listEquals<FontFeature>(_fontFeatures, typedOther._fontFeatures))
return false;
return true;
}
@override
int get hashCode => hashValues(hashList(_encoded), _fontFamily, _fontFamilyFallback, _fontSize, _letterSpacing, _wordSpacing, _height, _locale, _background, _foreground, _shadows, _decorationThickness);
int get hashCode => hashValues(hashList(_encoded), _fontFamily, _fontFamilyFallback, _fontSize, _letterSpacing, _wordSpacing, _height, _locale, _background, _foreground, hashList(_shadows), _decorationThickness, hashList(_fontFeatures));
@override
String toString() {
@@ -510,7 +661,8 @@ class TextStyle {
'locale: ${ _encoded[0] & 0x04000 == 0x04000 ? _locale : "unspecified"}, '
'background: ${ _encoded[0] & 0x08000 == 0x08000 ? _background : "unspecified"}, '
'foreground: ${ _encoded[0] & 0x10000 == 0x10000 ? _foreground : "unspecified"}, '
'shadows: ${ _encoded[0] & 0x20000 == 0x20000 ? _shadows : "unspecified"}'
'shadows: ${ _encoded[0] & 0x20000 == 0x20000 ? _shadows : "unspecified"}, '
'fontFeatures: ${ _encoded[0] & 0x40000 == 0x40000 ? _fontFeatures : "unspecified"}'
')';
}
}
@@ -1461,7 +1613,18 @@ class ParagraphBuilder extends NativeFieldWrapperClass2 {
if (style._fontFamily != null)
fullFontFamilies.add(style._fontFamily);
if (style._fontFamilyFallback != null)
fullFontFamilies.addAll(style._fontFamilyFallback);
fullFontFamilies.addAll(style._fontFamilyFallback);
ByteData encodedFontFeatures;
if (style._fontFeatures != null) {
encodedFontFeatures = ByteData(style._fontFeatures.length * FontFeature._kEncodedSize);
int byteOffset = 0;
for (FontFeature feature in style._fontFeatures) {
feature._encode(ByteData.view(encodedFontFeatures.buffer, byteOffset, FontFeature._kEncodedSize));
byteOffset += FontFeature._kEncodedSize;
}
}
_pushStyle(
style._encoded,
fullFontFamilies,
@@ -1475,7 +1638,8 @@ class ParagraphBuilder extends NativeFieldWrapperClass2 {
style._background?._data,
style._foreground?._objects,
style._foreground?._data,
Shadow._encodeShadows(style._shadows)
Shadow._encodeShadows(style._shadows),
encodedFontFeatures,
);
}
@@ -1492,7 +1656,8 @@ class ParagraphBuilder extends NativeFieldWrapperClass2 {
ByteData backgroundData,
List<dynamic> foregroundObjects,
ByteData foregroundData,
ByteData shadowsData
ByteData shadowsData,
ByteData fontFeaturesData,
) native 'ParagraphBuilder_pushStyle';
static String _encodeLocale(Locale locale) => locale?.toString() ?? '';

View File

@@ -46,6 +46,7 @@ const int tsLocaleIndex = 14;
const int tsBackgroundIndex = 15;
const int tsForegroundIndex = 16;
const int tsTextShadowsIndex = 17;
const int tsFontFeaturesIndex = 18;
const int tsColorMask = 1 << tsColorIndex;
const int tsTextDecorationMask = 1 << tsTextDecorationIndex;
@@ -64,6 +65,7 @@ const int tsLocaleMask = 1 << tsLocaleIndex;
const int tsBackgroundMask = 1 << tsBackgroundIndex;
const int tsForegroundMask = 1 << tsForegroundIndex;
const int tsTextShadowsMask = 1 << tsTextShadowsIndex;
const int tsFontFeaturesMask = 1 << tsFontFeaturesIndex;
// ParagraphStyle
@@ -101,6 +103,10 @@ constexpr uint32_t kXOffset = 1;
constexpr uint32_t kYOffset = 2;
constexpr uint32_t kBlurOffset = 3;
// FontFeature decoding
constexpr uint32_t kBytesPerFontFeature = 8;
constexpr uint32_t kFontFeatureTagLength = 4;
// Strut decoding
const int sFontWeightIndex = 0;
const int sFontStyleIndex = 1;
@@ -303,6 +309,24 @@ void decodeTextShadows(Dart_Handle shadows_data,
}
}
void decodeFontFeatures(Dart_Handle font_features_data,
txt::FontFeatures& font_features) {
tonic::DartByteData byte_data(font_features_data);
FML_CHECK(byte_data.length_in_bytes() % kBytesPerFontFeature == 0);
size_t feature_count = byte_data.length_in_bytes() / kBytesPerFontFeature;
for (size_t feature_index = 0; feature_index < feature_count;
++feature_index) {
size_t feature_offset = feature_index * kBytesPerFontFeature;
const char* feature_bytes =
static_cast<const char*>(byte_data.data()) + feature_offset;
std::string tag(feature_bytes, kFontFeatureTagLength);
int32_t value = *(reinterpret_cast<const int32_t*>(feature_bytes +
kFontFeatureTagLength));
font_features.SetFeature(tag, value);
}
}
void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
const std::vector<std::string>& fontFamilies,
double fontSize,
@@ -315,7 +339,8 @@ void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
Dart_Handle background_data,
Dart_Handle foreground_objects,
Dart_Handle foreground_data,
Dart_Handle shadows_data) {
Dart_Handle shadows_data,
Dart_Handle font_features_data) {
FML_DCHECK(encoded.num_elements() == 8);
int32_t mask = encoded[0];
@@ -405,6 +430,10 @@ void ParagraphBuilder::pushStyle(tonic::Int32List& encoded,
fontFamilies.end());
}
if (mask & tsFontFeaturesMask) {
decodeFontFeatures(font_features_data, style.font_features);
}
m_paragraphBuilder->PushStyle(style);
}

View File

@@ -49,7 +49,8 @@ class ParagraphBuilder : public RefCountedDartWrappable<ParagraphBuilder> {
Dart_Handle background_data,
Dart_Handle foreground_objects,
Dart_Handle foreground_data,
Dart_Handle shadows_data);
Dart_Handle shadows_data,
Dart_Handle font_features_data);
void pop();

View File

@@ -81,6 +81,8 @@ source_set("txt") {
"src/txt/font_asset_provider.h",
"src/txt/font_collection.cc",
"src/txt/font_collection.h",
"src/txt/font_features.cc",
"src/txt/font_features.h",
"src/txt/font_skia.cc",
"src/txt/font_skia.h",
"src/txt/font_style.h",

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2019 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "font_features.h"
#include <sstream>
namespace txt {
void FontFeatures::SetFeature(std::string tag, int value) {
feature_map_[tag] = value;
}
std::string FontFeatures::GetFeatureSettings() const {
if (feature_map_.empty())
return "";
std::ostringstream stream;
for (auto kv : feature_map_) {
if (stream.tellp()) {
stream << ',';
}
stream << kv.first << '=' << kv.second;
}
return stream.str();
}
} // namespace txt

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIB_TXT_SRC_FONT_FEATURES_H_
#define LIB_TXT_SRC_FONT_FEATURES_H_
#include <map>
#include <string>
#include <vector>
namespace txt {
// Feature tags that can be applied in a text style to control how a font
// selects glyphs.
class FontFeatures {
public:
void SetFeature(std::string tag, int value);
std::string GetFeatureSettings() const;
private:
std::map<std::string, int> feature_map_;
};
} // namespace txt
#endif // LIB_TXT_SRC_FONT_FEATURE_H_

View File

@@ -163,6 +163,7 @@ void GetFontAndMinikinPaint(const TextStyle& style,
// between same text content with different runs composing it, however, it
// also produces more accurate layouts.
paint->paintFlags |= minikin::LinearTextFlag;
paint->fontFeatureSettings = style.font_features.GetFeatureSettings();
}
void FindWords(const std::vector<uint16_t>& text,

View File

@@ -120,7 +120,7 @@ class Paragraph {
return start == other.start && end == other.end;
}
T width() { return end - start; }
T width() const { return end - start; }
void Shift(T delta) {
start += delta;
@@ -238,6 +238,7 @@ class Paragraph {
FRIEND_TEST(ParagraphTest, SimpleShadow);
FRIEND_TEST(ParagraphTest, ComplexShadow);
FRIEND_TEST(ParagraphTest, FontFallbackParagraph);
FRIEND_TEST(ParagraphTest, FontFeaturesParagraph);
// Starting data to layout.
std::vector<uint16_t> text_;

View File

@@ -20,6 +20,7 @@
#include <string>
#include <vector>
#include "font_features.h"
#include "font_style.h"
#include "font_weight.h"
#include "text_baseline.h"
@@ -58,6 +59,7 @@ class TextStyle {
// An ordered list of shadows where the first shadow will be drawn first (at
// the bottom).
std::vector<TextShadow> text_shadows;
FontFeatures font_features;
TextStyle();

View File

@@ -3627,4 +3627,54 @@ TEST_F(ParagraphTest, DISABLE_ON_WINDOWS(StrutForceParagraph)) {
ASSERT_TRUE(Snapshot());
}
TEST_F(ParagraphTest, FontFeaturesParagraph) {
const char* text = "12ab\n";
auto icu_text = icu::UnicodeString::fromUTF8(text);
std::u16string u16_text(icu_text.getBuffer(),
icu_text.getBuffer() + icu_text.length());
txt::ParagraphStyle paragraph_style;
txt::ParagraphBuilder builder(paragraph_style, GetTestFontCollection());
txt::TextStyle text_style;
text_style.font_families = std::vector<std::string>(1, "Roboto");
text_style.color = SK_ColorBLACK;
text_style.font_features.SetFeature("tnum", 1);
builder.PushStyle(text_style);
builder.AddText(u16_text);
text_style.font_features.SetFeature("tnum", 0);
text_style.font_features.SetFeature("pnum", 1);
builder.PushStyle(text_style);
builder.AddText(u16_text);
builder.Pop();
builder.Pop();
auto paragraph = builder.Build();
paragraph->Layout(GetTestCanvasWidth());
paragraph->Paint(GetCanvas(), 10.0, 15.0);
ASSERT_EQ(paragraph->glyph_lines_.size(), 3ull);
// Tabular numbers should have equal widths.
const txt::Paragraph::GlyphLine& tnum_line = paragraph->glyph_lines_[0];
ASSERT_EQ(tnum_line.positions.size(), 4ull);
EXPECT_FLOAT_EQ(tnum_line.positions[0].x_pos.width(),
tnum_line.positions[1].x_pos.width());
// Proportional numbers should have variable widths.
const txt::Paragraph::GlyphLine& pnum_line = paragraph->glyph_lines_[1];
ASSERT_EQ(pnum_line.positions.size(), 4ull);
EXPECT_NE(pnum_line.positions[0].x_pos.width(),
pnum_line.positions[1].x_pos.width());
// Alphabetic characters should be unaffected.
EXPECT_FLOAT_EQ(tnum_line.positions[2].x_pos.width(),
pnum_line.positions[2].x_pos.width());
ASSERT_TRUE(Snapshot());
}
} // namespace txt