blob: 1f7795b83a66dbbaca674bd05e6c652d9cd411a6 [file] [log] [blame]
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/render_text.h"
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <numeric>
#include "base/format_macros.h"
#include "base/i18n/break_iterator.h"
#include "base/i18n/char_iterator.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "cc/paint/paint_record.h"
#include "cc/paint/paint_recorder.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkFontStyle.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "ui/gfx/break_list.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/decorated_text.h"
#include "ui/gfx/font.h"
#include "ui/gfx/font_names_testing.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/range/range.h"
#include "ui/gfx/range/range_f.h"
#include "ui/gfx/render_text_harfbuzz.h"
#include "ui/gfx/render_text_test_api.h"
#include "ui/gfx/switches.h"
#include "ui/gfx/text_elider.h"
#include "ui/gfx/text_utils.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
#if defined(OS_APPLE)
#include "base/mac/mac_util.h"
#endif
using base::ASCIIToUTF16;
using base::UTF8ToUTF16;
using base::WideToUTF16;
namespace gfx {
namespace {
// Various weak, LTR, RTL, and Bidi string cases with three characters each.
const char kWeak[] = " . ";
const char kLtr[] = "abc";
const char kRtl[] = "\u05d0\u05d1\u05d2";
const char kLtrRtl[] = "a\u05d0\u05d1";
const char kLtrRtlLtr[] = "a\u05d1b";
const char kRtlLtr[] = "\u05d0\u05d1a";
const char kRtlLtrRtl[] = "\u05d0a\u05d1";
constexpr bool kUseWordWrap = true;
constexpr bool kUseObscuredText = true;
// Bitmasks based on gfx::TextStyle.
enum {
ITALIC_MASK = 1 << TEXT_STYLE_ITALIC,
STRIKE_MASK = 1 << TEXT_STYLE_STRIKE,
UNDERLINE_MASK = 1 << TEXT_STYLE_UNDERLINE,
};
using FontSpan = std::pair<Font, Range>;
bool IsFontsSmoothingEnabled() {
#if defined(OS_WIN)
BOOL antialiasing = TRUE;
BOOL result = SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &antialiasing, 0);
if (result == FALSE) {
ADD_FAILURE() << "Failed to retrieve font aliasing configuration.";
}
return antialiasing;
#else
return true;
#endif
}
// Checks whether |range| contains |index|. This is not the same as calling
// range.Contains(Range(index)), which returns true if |index| == |range.end()|.
bool IndexInRange(const Range& range, size_t index) {
return index >= range.start() && index < range.end();
}
base::string16 GetSelectedText(RenderText* render_text) {
return render_text->text().substr(render_text->selection().GetMin(),
render_text->selection().length());
}
// A test utility function to set the application default text direction.
void SetRTL(bool rtl) {
// Override the current locale/direction.
base::i18n::SetICUDefaultLocale(rtl ? "he" : "en");
EXPECT_EQ(rtl, base::i18n::IsRTL());
}
// Execute MoveCursor on the given |render_text| instance for the given
// arguments and verify the selected range matches |expected|. Also, clears the
// expectations.
void RunMoveCursorTestAndClearExpectations(RenderText* render_text,
BreakType break_type,
VisualCursorDirection direction,
SelectionBehavior selection_behavior,
std::vector<Range>* expected) {
for (size_t i = 0; i < expected->size(); ++i) {
SCOPED_TRACE(base::StringPrintf(
"BreakType-%d VisualCursorDirection-%d SelectionBehavior-%d Case-%d.",
break_type, direction, selection_behavior, static_cast<int>(i)));
render_text->MoveCursor(break_type, direction, selection_behavior);
EXPECT_EQ(expected->at(i), render_text->selection());
}
expected->clear();
}
// Execute MoveCursor on the given |render_text| instance for the given
// arguments and verify the line matches |expected|. Also, clears the
// expectations.
void RunMoveCursorTestAndClearExpectations(RenderText* render_text,
BreakType break_type,
VisualCursorDirection direction,
SelectionBehavior selection_behavior,
std::vector<size_t>* expected) {
int case_index = 0;
for (auto expected_line : *expected) {
SCOPED_TRACE(testing::Message()
<< "Text: " << render_text->text() << " BreakType: "
<< break_type << " VisualCursorDirection: " << direction
<< " SelectionBehavior: " << selection_behavior
<< " Case: " << case_index++);
render_text->MoveCursor(break_type, direction, selection_behavior);
EXPECT_EQ(expected_line, render_text->GetLineContainingCaret(
render_text->selection_model()));
}
expected->clear();
}
// Ensure cursor movement in the specified |direction| yields |expected| values.
void RunMoveCursorLeftRightTest(RenderText* render_text,
const std::vector<SelectionModel>& expected,
VisualCursorDirection direction) {
for (size_t i = 0; i < expected.size(); ++i) {
SCOPED_TRACE(base::StringPrintf("Going %s; expected value index %d.",
direction == CURSOR_LEFT ? "left" : "right", static_cast<int>(i)));
EXPECT_EQ(expected[i], render_text->selection_model());
render_text->MoveCursor(CHARACTER_BREAK, direction, SELECTION_NONE);
}
// Check that cursoring is clamped at the line edge.
EXPECT_EQ(expected.back(), render_text->selection_model());
// Check that it is the line edge.
render_text->MoveCursor(LINE_BREAK, direction, SELECTION_NONE);
EXPECT_EQ(expected.back(), render_text->selection_model());
}
// Creates a RangedAttribute instance for a single character range at the
// given |index| with the given |weight| and |style_mask|. |index| is the
// index of the character in the DecoratedText instance and |font_index| is
// used to retrieve the font used from |font_spans|.
DecoratedText::RangedAttribute CreateRangedAttribute(
const std::vector<FontSpan>& font_spans,
int index,
int font_index,
Font::Weight weight,
int style_mask) {
const auto iter = std::find_if(font_spans.cbegin(), font_spans.cend(),
[font_index](const FontSpan& span) {
return IndexInRange(span.second, font_index);
});
DCHECK(font_spans.end() != iter);
const Font& font = iter->first;
int font_style = Font::NORMAL;
if (style_mask & ITALIC_MASK)
font_style |= Font::ITALIC;
if (style_mask & UNDERLINE_MASK)
font_style |= Font::UNDERLINE;
const Font font_with_style = font.Derive(0, font_style, weight);
DecoratedText::RangedAttribute attributes(Range(index, index + 1),
font_with_style);
attributes.strike = style_mask & STRIKE_MASK;
return attributes;
}
// Verifies the given DecoratedText instances are equal by comparing the
// respective strings and attributes for each index. Note, corresponding
// ranged attributes from |expected| and |actual| can't be compared since the
// partition of |actual| into RangedAttributes will depend on the text runs
// generated.
void VerifyDecoratedWordsAreEqual(const DecoratedText& expected,
const DecoratedText& actual) {
ASSERT_EQ(expected.text, actual.text);
// Compare attributes for each index.
for (size_t i = 0; i < expected.text.length(); i++) {
SCOPED_TRACE(base::StringPrintf("Comparing index[%" PRIuS "]", i));
auto find_attribute_func = [i](const DecoratedText::RangedAttribute& attr) {
return IndexInRange(attr.range, i);
};
const auto expected_attr =
std::find_if(expected.attributes.begin(), expected.attributes.end(),
find_attribute_func);
const auto actual_attr =
std::find_if(actual.attributes.begin(), actual.attributes.end(),
find_attribute_func);
ASSERT_NE(expected.attributes.end(), expected_attr);
ASSERT_NE(actual.attributes.end(), actual_attr);
EXPECT_EQ(expected_attr->strike, actual_attr->strike);
EXPECT_EQ(expected_attr->font.GetFontName(),
actual_attr->font.GetFontName());
EXPECT_EQ(expected_attr->font.GetFontSize(),
actual_attr->font.GetFontSize());
EXPECT_EQ(expected_attr->font.GetWeight(), actual_attr->font.GetWeight());
EXPECT_EQ(expected_attr->font.GetStyle(), actual_attr->font.GetStyle());
}
}
// Helper method to return an obscured string of the given |length|, with the
// |reveal_index| filled with |reveal_char|.
base::string16 GetObscuredString(size_t length,
size_t reveal_index,
base::char16 reveal_char) {
std::vector<base::char16> arr(length, RenderText::kPasswordReplacementChar);
arr[reveal_index] = reveal_char;
return base::string16(arr.begin(), arr.end());
}
// Helper method to return an obscured string of the given |length|.
base::string16 GetObscuredString(size_t length) {
return base::string16(length, RenderText::kPasswordReplacementChar);
}
// Converts a vector of UTF8 literals into a vector of (UTF16) string16.
std::vector<base::string16> ToString16Vec(
const std::vector<const char*>& utf8_literals) {
std::vector<base::string16> vec;
for (auto* const literal : utf8_literals)
vec.push_back(UTF8ToUTF16(literal));
return vec;
}
// Returns the combined character range from all text runs on |line|.
Range LineCharRange(const internal::Line& line) {
if (line.segments.empty())
return Range();
Range ltr(line.segments.front().char_range.start(),
line.segments.back().char_range.end());
if (ltr.end() > ltr.start())
return ltr;
// For RTL, the order of segments is reversed, but the ranges are not.
return Range(line.segments.back().char_range.start(),
line.segments.front().char_range.end());
}
struct GlyphCountAndColor {
size_t glyph_count = 0;
SkColor color = SK_ColorBLACK;
};
class TextLog {
public:
TextLog(PointF origin, std::vector<uint16_t> glyphs, SkColor color)
: origin_(origin), glyphs_(glyphs), color_(color) {}
TextLog(const TextLog&) = default;
PointF origin() const { return origin_; }
SkColor color() const { return color_; }
const std::vector<uint16_t>& glyphs() const { return glyphs_; }
private:
const PointF origin_;
const std::vector<uint16_t> glyphs_;
const SkColor color_ = SK_ColorTRANSPARENT;
};
// The class which records the drawing operations so that the test case can
// verify where exactly the glyphs are drawn.
class TestSkiaTextRenderer : public internal::SkiaTextRenderer {
public:
explicit TestSkiaTextRenderer(Canvas* canvas)
: internal::SkiaTextRenderer(canvas) {}
~TestSkiaTextRenderer() override {}
void GetTextLogAndReset(std::vector<TextLog>* text_log) {
text_log_.swap(*text_log);
text_log_.clear();
}
private:
// internal::SkiaTextRenderer overrides:
void DrawPosText(const SkPoint* pos,
const uint16_t* glyphs,
size_t glyph_count) override {
if (glyph_count) {
PointF origin =
PointF(SkScalarToFloat(pos[0].x()), SkScalarToFloat(pos[0].y()));
for (size_t i = 1U; i < glyph_count; ++i) {
origin.SetToMin(
PointF(SkScalarToFloat(pos[i].x()), SkScalarToFloat(pos[i].y())));
}
std::vector<uint16_t> run_glyphs(glyphs, glyphs + glyph_count);
SkColor color =
test::RenderTextTestApi::GetRendererPaint(this).getColor();
text_log_.push_back(TextLog(origin, std::move(run_glyphs), color));
}
internal::SkiaTextRenderer::DrawPosText(pos, glyphs, glyph_count);
}
std::vector<TextLog> text_log_;
DISALLOW_COPY_AND_ASSIGN(TestSkiaTextRenderer);
};
class TestRenderTextCanvas : public SkCanvas {
public:
TestRenderTextCanvas(int width, int height) : SkCanvas(width, height) {}
// SkCanvas overrides:
void onDrawTextBlob(const SkTextBlob* blob,
SkScalar x,
SkScalar y,
const SkPaint& paint) override {
PointF origin = PointF(SkScalarToFloat(x), SkScalarToFloat(y));
std::vector<uint16_t> glyphs;
if (blob) {
SkTextBlob::Iter::Run run;
for (SkTextBlob::Iter it(*blob); it.next(&run);) {
auto run_glyphs =
base::span<const uint16_t>(run.fGlyphIndices, run.fGlyphCount);
glyphs.insert(glyphs.end(), run_glyphs.begin(), run_glyphs.end());
}
}
text_log_.push_back(TextLog(origin, std::move(glyphs), paint.getColor()));
SkCanvas::onDrawTextBlob(blob, x, y, paint);
}
void GetTextLogAndReset(std::vector<TextLog>* text_log) {
text_log_.swap(*text_log);
text_log_.clear();
}
const std::vector<TextLog>& text_log() const { return text_log_; }
private:
std::vector<TextLog> text_log_;
};
// Given a buffer to test against, this can be used to test various areas of the
// rectangular buffer against a specific color value.
class TestRectangleBuffer {
public:
TestRectangleBuffer(const char* string,
const SkColor* buffer,
uint32_t stride,
uint32_t row_count)
: string_(string),
buffer_(buffer),
stride_(stride),
row_count_(row_count) {}
// Test if any values in the rectangular area are anything other than |color|.
void EnsureSolidRect(SkColor color,
int left,
int top,
int width,
int height) const {
ASSERT_LT(top, row_count_) << string_;
ASSERT_LE(top + height, row_count_) << string_;
ASSERT_LT(left, stride_) << string_;
ASSERT_LE(left + width, stride_) << string_ << ", left " << left
<< ", width " << width << ", stride_ "
<< stride_;
for (int y = top; y < top + height; ++y) {
for (int x = left; x < left + width; ++x) {
SkColor buffer_color = buffer_[x + y * stride_];
EXPECT_EQ(color, buffer_color) << string_ << " at " << x << ", " << y;
}
}
}
// Test that the rect defined by |left|, |top|, |width| and |height| is filled
// with the same color.
void EnsureRectIsAllSameColor(int left,
int top,
int width,
int height) const {
SkColor buffer_color = buffer_[left + top * stride_];
EnsureSolidRect(buffer_color, left, top, width, height);
}
private:
const char* string_;
const SkColor* buffer_;
int stride_;
int row_count_;
DISALLOW_COPY_AND_ASSIGN(TestRectangleBuffer);
};
} // namespace
// Test fixture class used to run parameterized tests for all RenderText
// implementations.
class RenderTextTest : public testing::Test {
public:
RenderTextTest()
: task_environment_(
base::test::SingleThreadTaskEnvironment::MainThreadType::UI),
render_text_(std::make_unique<RenderTextHarfBuzz>()),
test_api_(new test::RenderTextTestApi(render_text_.get())),
renderer_(canvas()) {}
protected:
const cc::PaintFlags& GetRendererPaint() {
return test::RenderTextTestApi::GetRendererPaint(renderer());
}
const SkFont& GetRendererFont() {
return test::RenderTextTestApi::GetRendererFont(renderer());
}
void DrawVisualText(const std::vector<Range> selections = {}) {
test_api()->EnsureLayout();
test_api()->DrawVisualText(renderer(), selections);
renderer()->GetTextLogAndReset(&text_log_);
}
void Draw(bool select_all = false) {
constexpr int kCanvasWidth = 1200;
constexpr int kCanvasHeight = 400;
cc::PaintRecorder recorder;
Canvas canvas(recorder.beginRecording(kCanvasWidth, kCanvasHeight), 1.0f);
test_api_->Draw(&canvas, select_all);
sk_sp<cc::PaintRecord> record = recorder.finishRecordingAsPicture();
TestRenderTextCanvas test_canvas(kCanvasWidth, kCanvasHeight);
record->Playback(&test_canvas);
test_canvas.GetTextLogAndReset(&text_log_);
}
internal::TextRunList* GetHarfBuzzRunList() {
test_api()->EnsureLayout();
return test_api()->GetHarfBuzzRunList();
}
// For testing purposes, returns which fonts were chosen for which parts of
// the text by returning a vector of Font and Range pairs, where each range
// specifies the character range for which the corresponding font has been
// chosen.
std::vector<FontSpan> GetFontSpans() {
test_api()->EnsureLayout();
const internal::TextRunList* run_list = GetHarfBuzzRunList();
std::vector<FontSpan> spans;
std::transform(
run_list->runs().begin(), run_list->runs().end(),
std::back_inserter(spans), [this](const auto& run) {
return FontSpan(
run->font_params.font,
Range(test_api()->DisplayIndexToTextIndex(run->range.start()),
test_api()->DisplayIndexToTextIndex(run->range.end())));
});
return spans;
}
// Converts the current run list into a human-readable string. Can be used in
// test assertions for a readable expectation and failure message.
//
// The string shows the runs in visual order. Each run is enclosed in square
// brackets, and shows the begin and end inclusive logical character position,
// with an arrow indicating the direction of the run. Single-character runs
// just show the character position.
//
// For example, the the logical bidirectional string "abc+\u05d0\u05d1\u05d2"
// (visual string: "abc+אבג") yields "[0->2][3][6<-4]".
std::string GetRunListStructureString() {
test_api()->EnsureLayout();
const internal::TextRunList* run_list = GetHarfBuzzRunList();
std::string result;
for (size_t i = 0; i < run_list->size(); ++i) {
size_t logical_index = run_list->visual_to_logical(i);
const internal::TextRunHarfBuzz& run = *run_list->runs()[logical_index];
if (run.range.length() == 1) {
result.append(base::StringPrintf("[%d]", run.range.start()));
} else if (run.font_params.is_rtl) {
result.append(base::StringPrintf("[%d<-%d]", run.range.end() - 1,
run.range.start()));
} else {
result.append(base::StringPrintf("[%d->%d]", run.range.start(),
run.range.end() - 1));
}
}
return result;
}
// Returns a vector of text fragments corresponding to the current list of
// text runs.
std::vector<base::string16> GetRunListStrings() {
std::vector<base::string16> runs_as_text;
for (const auto& span : GetFontSpans()) {
runs_as_text.push_back(render_text_->text().substr(span.second.GetMin(),
span.second.length()));
}
return runs_as_text;
}
// Sets the text to |text|, then returns GetRunListStrings().
std::vector<base::string16> RunsFor(const base::string16& text) {
render_text_->SetText(text);
test_api()->EnsureLayout();
return GetRunListStrings();
}
void ResetRenderTextInstance() {
render_text_ = std::make_unique<RenderTextHarfBuzz>();
test_api_ = std::make_unique<test::RenderTextTestApi>(GetRenderText());
}
void ResetCursorX() { test_api()->reset_cached_cursor_x(); }
int GetLineContainingYCoord(float text_y) {
return test_api()->GetLineContainingYCoord(text_y);
}
RenderTextHarfBuzz* GetRenderText() { return render_text_.get(); }
Rect GetSubstringBoundsUnion(const Range& range) {
const std::vector<Rect> bounds = render_text_->GetSubstringBounds(range);
return std::accumulate(
bounds.begin(), bounds.end(), Rect(),
[](const Rect& a, const Rect& b) { return UnionRects(a, b); });
}
Rect GetSelectionBoundsUnion() {
return GetSubstringBoundsUnion(render_text_->selection());
}
// Checks left-to-right text, ensuring that the caret moves to the right as
// the cursor position increments through the logical text. Also ensures that
// each glyph is to the right of the prior glyph. RenderText automatically
// updates invalid cursor positions (eg. between a surrogate pair) to a valid
// neighbor, so the positions may be unchanged for some iterations. Invoking
// this in a test gives coverage of the sanity checks in functions such as
// TextRunHarfBuzz::GetGraphemeBounds() which rely on sensible glyph positions
// being provided by installed typefaces.
void CheckBoundsForCursorPositions() {
ASSERT_FALSE(render_text_->text().empty());
// Use a wide display rect to avoid scrolling.
render_text_->SetDisplayRect(gfx::Rect(0, 0, 1000, 50));
EXPECT_LT(render_text_->GetContentWidthF(),
render_text_->display_rect().width());
// Assume LTR for now.
int max_cursor_x = 0;
int max_glyph_x = 0, max_glyph_right = 0;
for (size_t i = 0; i <= render_text_->text().size(); ++i) {
render_text_->SetCursorPosition(i);
SCOPED_TRACE(testing::Message()
<< "Cursor position: " << i
<< " selection: " << render_text_->selection().ToString());
const gfx::Rect cursor_bounds = render_text_->GetUpdatedCursorBounds();
// The cursor should always be one pixel wide.
EXPECT_EQ(1, cursor_bounds.width());
EXPECT_LE(max_cursor_x, cursor_bounds.x());
max_cursor_x = cursor_bounds.x();
const gfx::Rect glyph_bounds =
render_text_->GetCursorBounds(render_text_->selection_model(), false);
EXPECT_LE(max_glyph_x, glyph_bounds.x());
EXPECT_LE(max_glyph_right, glyph_bounds.right());
max_glyph_x = glyph_bounds.x();
max_glyph_right = glyph_bounds.right();
}
}
void SetGlyphWidth(float test_width) {
test_api()->SetGlyphWidth(test_width);
}
void SetGlyphHeight(float test_height) {
test_api()->SetGlyphHeight(test_height);
}
bool ShapeRunWithFont(const base::string16& text,
const Font& font,
const FontRenderParams& render_params,
internal::TextRunHarfBuzz* run) {
internal::TextRunHarfBuzz::FontParams font_params = run->font_params;
font_params.ComputeRenderParamsFontSizeAndBaselineOffset();
font_params.SetRenderParamsRematchFont(font, render_params);
run->shape.missing_glyph_count = static_cast<size_t>(-1);
std::vector<internal::TextRunHarfBuzz*> runs = {run};
GetRenderText()->ShapeRunsWithFont(text, font_params, &runs);
return runs.empty();
}
int GetCursorYForTesting(int line_num = 0) {
return GetRenderText()->GetLineOffset(line_num).y() + 1;
}
size_t GetLineContainingCaret() {
return GetRenderText()->GetLineContainingCaret(
GetRenderText()->selection_model());
}
Canvas* canvas() { return &canvas_; }
TestSkiaTextRenderer* renderer() { return &renderer_; }
test::RenderTextTestApi* test_api() { return test_api_.get(); }
const test::RenderTextTestApi* test_api() const { return test_api_.get(); }
const std::vector<TextLog>& text_log() const { return text_log_; }
void ExpectTextLog(std::vector<GlyphCountAndColor> runs) {
EXPECT_EQ(runs.size(), text_log_.size());
const size_t min_size = std::min(runs.size(), text_log_.size());
for (size_t i = 0; i < min_size; ++i) {
SCOPED_TRACE(testing::Message()
<< "ExpectTextLog, run " << i << " of " << runs.size());
EXPECT_EQ(runs[i].color, text_log_[i].color());
EXPECT_EQ(runs[i].glyph_count, text_log_[i].glyphs().size());
}
}
private:
// Needed to bypass DCHECK in GetFallbackFont.
base::test::SingleThreadTaskEnvironment task_environment_;
std::unique_ptr<RenderTextHarfBuzz> render_text_;
std::unique_ptr<test::RenderTextTestApi> test_api_;
std::vector<TextLog> text_log_;
Canvas canvas_;
TestSkiaTextRenderer renderer_;
DISALLOW_COPY_AND_ASSIGN(RenderTextTest);
};
TEST_F(RenderTextTest, DefaultStyles) {
// Check the default styles applied to new instances and adjusted text.
RenderText* render_text = GetRenderText();
EXPECT_TRUE(render_text->text().empty());
const char* const cases[] = {kWeak, kLtr, "Hello", kRtl, "", ""};
for (size_t i = 0; i < base::size(cases); ++i) {
EXPECT_TRUE(test_api()->colors().EqualsValueForTesting(SK_ColorBLACK));
EXPECT_TRUE(test_api()->baselines().EqualsValueForTesting(NORMAL_BASELINE));
EXPECT_TRUE(test_api()->font_size_overrides().EqualsValueForTesting(0));
for (size_t style = 0; style < static_cast<int>(TEXT_STYLE_COUNT); ++style)
EXPECT_TRUE(test_api()->styles()[style].EqualsValueForTesting(false));
render_text->SetText(UTF8ToUTF16(cases[i]));
}
}
TEST_F(RenderTextTest, SetStyles) {
// Ensure custom default styles persist across setting and clearing text.
RenderText* render_text = GetRenderText();
const SkColor color = SK_ColorRED;
render_text->SetColor(color);
render_text->SetBaselineStyle(SUPERSCRIPT);
render_text->SetWeight(Font::Weight::BOLD);
render_text->SetStyle(TEXT_STYLE_UNDERLINE, false);
const char* const cases[] = {kWeak, kLtr, "Hello", kRtl, "", ""};
for (size_t i = 0; i < base::size(cases); ++i) {
EXPECT_TRUE(test_api()->colors().EqualsValueForTesting(color));
EXPECT_TRUE(test_api()->baselines().EqualsValueForTesting(SUPERSCRIPT));
EXPECT_TRUE(
test_api()->weights().EqualsValueForTesting(Font::Weight::BOLD));
EXPECT_TRUE(
test_api()->styles()[TEXT_STYLE_UNDERLINE].EqualsValueForTesting(
false));
render_text->SetText(UTF8ToUTF16(cases[i]));
// Ensure custom default styles can be applied after text has been set.
if (i == 1)
render_text->SetStyle(TEXT_STYLE_STRIKE, true);
if (i >= 1)
EXPECT_TRUE(
test_api()->styles()[TEXT_STYLE_STRIKE].EqualsValueForTesting(true));
}
}
TEST_F(RenderTextTest, ApplyStyles) {
RenderText* render_text = GetRenderText();
render_text->SetText(ASCIIToUTF16("012345678"));
constexpr int kTestFontSizeOverride = 20;
// Apply a ranged color and style and check the resulting breaks.
render_text->ApplyColor(SK_ColorRED, Range(1, 4));
render_text->ApplyBaselineStyle(SUPERIOR, Range(2, 4));
render_text->ApplyWeight(Font::Weight::BOLD, Range(2, 5));
render_text->ApplyFontSizeOverride(kTestFontSizeOverride, Range(5, 7));
EXPECT_TRUE(test_api()->colors().EqualsForTesting(
{{0, SK_ColorBLACK}, {1, SK_ColorRED}, {4, SK_ColorBLACK}}));
EXPECT_TRUE(test_api()->baselines().EqualsForTesting(
{{0, NORMAL_BASELINE}, {2, SUPERIOR}, {4, NORMAL_BASELINE}}));
EXPECT_TRUE(test_api()->font_size_overrides().EqualsForTesting(
{{0, 0}, {5, kTestFontSizeOverride}, {7, 0}}));
EXPECT_TRUE(
test_api()->weights().EqualsForTesting({{0, Font::Weight::NORMAL},
{2, Font::Weight::BOLD},
{5, Font::Weight::NORMAL}}));
// Ensure that setting a value overrides the ranged values.
render_text->SetColor(SK_ColorBLUE);
EXPECT_TRUE(test_api()->colors().EqualsValueForTesting(SK_ColorBLUE));
render_text->SetBaselineStyle(SUBSCRIPT);
EXPECT_TRUE(test_api()->baselines().EqualsValueForTesting(SUBSCRIPT));
render_text->SetWeight(Font::Weight::NORMAL);
EXPECT_TRUE(
test_api()->weights().EqualsValueForTesting(Font::Weight::NORMAL));
// Apply a value over the text end and check the resulting breaks (INT_MAX
// should be used instead of the text length for the range end)
const size_t text_length = render_text->text().length();
render_text->ApplyColor(SK_ColorRED, Range(0, text_length));
render_text->ApplyBaselineStyle(SUPERIOR, Range(0, text_length));
render_text->ApplyWeight(Font::Weight::BOLD, Range(2, text_length));
EXPECT_TRUE(test_api()->colors().EqualsForTesting({{0, SK_ColorRED}}));
EXPECT_TRUE(test_api()->baselines().EqualsForTesting({{0, SUPERIOR}}));
EXPECT_TRUE(test_api()->weights().EqualsForTesting(
{{0, Font::Weight::NORMAL}, {2, Font::Weight::BOLD}}));
// Ensure ranged values adjust to accommodate text length changes.
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, Range(0, 2));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, Range(3, 6));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, Range(7, text_length));
std::vector<std::pair<size_t, bool>> expected_italic = {
{0, true}, {2, false}, {3, true}, {6, false}, {7, true}};
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
expected_italic));
// Changing the text should clear any breaks except for the first one.
render_text->SetText(ASCIIToUTF16("0123456"));
expected_italic.resize(1);
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
expected_italic));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, false, Range(2, 4));
render_text->SetText(ASCIIToUTF16("012345678"));
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
expected_italic));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, false, Range(0, 1));
render_text->SetText(ASCIIToUTF16("0123456"));
expected_italic.begin()->second = false;
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
expected_italic));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, Range(2, 4));
render_text->SetText(ASCIIToUTF16("012345678"));
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
expected_italic));
// Styles mid-grapheme should work. Style of first character of the grapheme
// is used.
render_text->SetText(UTF8ToUTF16("0\u0915\u093f1\u0915\u093f2"));
render_text->ApplyStyle(TEXT_STYLE_UNDERLINE, true, Range(2, 5));
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_UNDERLINE].EqualsForTesting(
{{0, false}, {2, true}, {5, false}}));
}
TEST_F(RenderTextTest, ApplyStyleSurrogatePair) {
RenderText* render_text = GetRenderText();
render_text->SetText(WideToUTF16(L"x\U0001F601x"));
// Apply the style in the middle of a surrogate pair. The style should be
// applied to the whole range of the codepoint.
gfx::Range range(2, 3);
render_text->ApplyWeight(gfx::Font::Weight::BOLD, range);
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, range);
render_text->ApplyColor(SK_ColorRED, range);
render_text->Draw(canvas());
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
{{0, false}, {2, true}, {3, false}}));
EXPECT_TRUE(test_api()->colors().EqualsForTesting(
{{0, SK_ColorBLACK}, {2, SK_ColorRED}, {3, SK_ColorBLACK}}));
EXPECT_TRUE(
test_api()->weights().EqualsForTesting({{0, Font::Weight::NORMAL},
{2, Font::Weight::BOLD},
{3, Font::Weight::NORMAL}}));
}
TEST_F(RenderTextTest, ApplyStyleGrapheme) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("\u0065\u0301"));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, gfx::Range(1, 2));
render_text->ApplyStyle(TEXT_STYLE_UNDERLINE, true, gfx::Range(0, 1));
Draw();
// Ensures that the whole grapheme is drawn with the same style.
ExpectTextLog({{1}});
}
TEST_F(RenderTextTest, ApplyStyleMultipleGraphemes) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("xx\u0065\u0301x"));
// Apply the style in the middle of a grapheme.
gfx::Range range(1, 3);
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, range);
Draw();
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
{{0, false}, {1, true}, {3, false}}));
// Ensures that the style of the grapheme is the style at its first character.
ExpectTextLog({{1}, {2}, {1}});
}
TEST_F(RenderTextTest, ApplyColorSurrogatePair) {
RenderText* render_text = GetRenderText();
render_text->SetText(WideToUTF16(L"x\U0001F601x"));
render_text->ApplyColor(SK_ColorRED, Range(2, 3));
Draw();
// Ensures that the color is not applied since it is in the middle of a
// surrogate pair.
// There is three runs since the codepoints are not in the same script.
ExpectTextLog({{1}, {1}, {1}});
// Obscure the text should renders characters with the same colors.
render_text->SetObscured(true);
Draw();
ExpectTextLog({{3}});
}
TEST_F(RenderTextTest, ApplyColorLongEmoji) {
// A long emoji sequence.
static const wchar_t kLongEmoji[] = L"\U0001F468\u200D\u2708\uFE0F";
RenderText* render_text = GetRenderText();
render_text->SetText(WideToUTF16(kLongEmoji));
render_text->AppendText(WideToUTF16(kLongEmoji));
render_text->AppendText(WideToUTF16(kLongEmoji));
render_text->ApplyColor(SK_ColorRED, Range(0, 2));
render_text->ApplyColor(SK_ColorBLUE, Range(8, 13));
Draw();
// Ensures that the color of the emoji is the color at its first character.
ASSERT_EQ(3u, text_log().size());
EXPECT_EQ(SK_ColorRED, text_log()[0].color());
EXPECT_EQ(SK_ColorBLACK, text_log()[1].color());
EXPECT_EQ(SK_ColorBLUE, text_log()[2].color());
// Reset the color.
render_text->SetColor(SK_ColorBLACK);
Draw();
// The amount of glyphs depend on the font. If the font supports the emoji,
// the amount of glyph is 1, otherwise it vary.
ASSERT_EQ(1u, text_log().size());
EXPECT_EQ(SK_ColorBLACK, text_log()[0].color());
}
TEST_F(RenderTextTest, ApplyColorObscuredEmoji) {
RenderText* render_text = GetRenderText();
render_text->SetText(WideToUTF16(L"\U0001F628\U0001F628\U0001F628"));
render_text->ApplyColor(SK_ColorRED, Range(0, 2));
render_text->ApplyColor(SK_ColorBLUE, Range(4, 5));
const std::vector<GlyphCountAndColor> kExpectedTextLog =
{{1, SK_ColorRED}, {1, SK_ColorBLACK}, {1, SK_ColorBLUE}};
// Ensures that colors are applied.
Draw();
ExpectTextLog(kExpectedTextLog);
// Obscure the text.
render_text->SetObscured(true);
// The obscured text (layout text) no longer contains surrogate pairs.
EXPECT_EQ(render_text->text().size(), 2 * test_api()->GetLayoutText().size());
// Obscured text should give the same colors.
Draw();
ExpectTextLog(kExpectedTextLog);
for (size_t i = 0; i < render_text->text().size(); ++i) {
render_text->RenderText::SetObscuredRevealIndex(i);
// Revealed codepoints should give the same colors.
Draw();
ExpectTextLog(kExpectedTextLog);
}
}
TEST_F(RenderTextTest, ApplyColorArabicDiacritics) {
// Render an Arabic character with two diacritics. The color should be taken
// from the base character.
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("\u0628\u0651\u0650"));
render_text->ApplyColor(SK_ColorRED, Range(0, 1));
render_text->ApplyColor(SK_ColorBLACK, Range(1, 2));
render_text->ApplyColor(SK_ColorBLUE, Range(2, 3));
Draw();
ASSERT_EQ(1u, text_log().size());
EXPECT_EQ(SK_ColorRED, text_log()[0].color());
}
TEST_F(RenderTextTest, ApplyColorArabicLigature) {
// In Arabic, letters of each word join together whenever possible. During
// the shaping pass of the font, characters will take their joining form:
// Isolated, Initial, Medial or Final.
// Render the isolated form of the first glyph.
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("\u0628"));
Draw();
ASSERT_EQ(1u, text_log().size());
ASSERT_EQ(1u, text_log()[0].glyphs().size());
uint16_t isolated_first_glyph = text_log()[0].glyphs()[0];
// Render a pair of glyphs (initial form and final form).
render_text->SetText(UTF8ToUTF16("\u0628\u0645"));
Draw();
ASSERT_EQ(1u, text_log().size());
ASSERT_LE(2u, text_log()[0].glyphs().size());
uint16_t initial_first_glyph = text_log()[0].glyphs()[0];
uint16_t final_second_glyph = text_log()[0].glyphs()[1];
// A ligature is applied between glyphs and the two glyphs (isolated and
// initial form) are displayed differently.
EXPECT_NE(isolated_first_glyph, initial_first_glyph);
// Ensures that both characters didn't merge in a single glyph.
EXPECT_NE(initial_first_glyph, final_second_glyph);
// Applying color should not break the ligature.
// see: https://w3c.github.io/alreq/#h_styling_individual_letters
render_text->ApplyColor(SK_ColorRED, Range(0, 1));
render_text->ApplyColor(SK_ColorBLACK, Range(1, 2));
Draw();
ASSERT_EQ(2u, text_log().size());
ASSERT_LE(1u, text_log()[0].glyphs().size());
ASSERT_EQ(1u, text_log()[1].glyphs().size());
uint16_t colored_first_glyph = text_log()[1].glyphs()[0];
uint16_t colored_second_glyph = text_log()[0].glyphs()[0];
// Glyphs should be the same with and without color.
EXPECT_EQ(initial_first_glyph, colored_first_glyph);
EXPECT_EQ(final_second_glyph, colored_second_glyph);
// Colors should be applied.
EXPECT_EQ(SK_ColorRED, text_log()[0].color());
EXPECT_EQ(SK_ColorBLACK, text_log()[1].color());
}
TEST_F(RenderTextTest, AppendTextKeepsStyles) {
RenderText* render_text = GetRenderText();
// Setup basic functionality.
render_text->SetText(ASCIIToUTF16("abcd"));
render_text->ApplyColor(SK_ColorRED, Range(0, 1));
render_text->ApplyBaselineStyle(SUPERSCRIPT, Range(1, 2));
render_text->ApplyStyle(TEXT_STYLE_UNDERLINE, true, Range(2, 3));
render_text->ApplyFontSizeOverride(20, Range(3, 4));
// Verify basic functionality.
const std::vector<std::pair<size_t, SkColor>> expected_color = {
{0, SK_ColorRED}, {1, SK_ColorBLACK}};
EXPECT_TRUE(test_api()->colors().EqualsForTesting(expected_color));
const std::vector<std::pair<size_t, BaselineStyle>> expected_baseline = {
{0, NORMAL_BASELINE}, {1, SUPERSCRIPT}, {2, NORMAL_BASELINE}};
EXPECT_TRUE(test_api()->baselines().EqualsForTesting(expected_baseline));
const std::vector<std::pair<size_t, bool>> expected_style = {
{0, false}, {2, true}, {3, false}};
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_UNDERLINE].EqualsForTesting(
expected_style));
const std::vector<std::pair<size_t, int>> expected_font_size = {{0, 0},
{3, 20}};
EXPECT_TRUE(
test_api()->font_size_overrides().EqualsForTesting(expected_font_size));
// Ensure AppendText maintains current text styles.
render_text->AppendText(ASCIIToUTF16("efg"));
EXPECT_EQ(render_text->GetDisplayText(), ASCIIToUTF16("abcdefg"));
EXPECT_TRUE(test_api()->colors().EqualsForTesting(expected_color));
EXPECT_TRUE(test_api()->baselines().EqualsForTesting(expected_baseline));
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_UNDERLINE].EqualsForTesting(
expected_style));
EXPECT_TRUE(
test_api()->font_size_overrides().EqualsForTesting(expected_font_size));
}
TEST_F(RenderTextTest, SetSelection) {
RenderText* render_text = GetRenderText();
render_text->set_selection_color(SK_ColorRED);
render_text->SetText(ASCIIToUTF16("abcdef"));
render_text->set_focused(true);
// Single selection
render_text->SetSelection(
{{{4, 100}}, LogicalCursorDirection::CURSOR_FORWARD});
Draw();
ExpectTextLog({{4}, {2, SK_ColorRED}});
// Multiple selections
render_text->SetSelection(
{{{0, 1}, {4, 100}}, LogicalCursorDirection::CURSOR_FORWARD});
Draw();
ExpectTextLog({{1, SK_ColorRED}, {3}, {2, SK_ColorRED}});
render_text->ClearSelection();
Draw();
ExpectTextLog({{6}});
}
TEST_F(RenderTextTest, SelectRangeColored) {
RenderText* render_text = GetRenderText();
render_text->SetText(ASCIIToUTF16("abcdef"));
render_text->SetColor(SK_ColorBLACK);
render_text->set_selection_color(SK_ColorRED);
render_text->set_focused(true);
render_text->SelectRange(Range(0, 1));
Draw();
ExpectTextLog({{1, SK_ColorRED}, {5, SK_ColorBLACK}});
render_text->SelectRange(Range(1, 3));
Draw();
ExpectTextLog({{1, SK_ColorBLACK}, {2, SK_ColorRED}, {3, SK_ColorBLACK}});
render_text->ClearSelection();
Draw();
ExpectTextLog({{6}});
}
// Tests that when a selection is made and the selection background is
// translucent, the selection renders properly. See crbug.com/1134440.
TEST_F(RenderTextTest, SelectWithTranslucentBackground) {
constexpr float kGlyphWidth = 5.5f;
constexpr Size kCanvasSize(300, 50);
constexpr SkColor kTranslucentBlue = SkColorSetARGB(0x7F, 0x00, 0x00, 0xFF);
const char* kTestString{"A B C D"};
SkBitmap bitmap;
bitmap.allocPixels(
SkImageInfo::MakeN32Premul(kCanvasSize.width(), kCanvasSize.height()));
cc::SkiaPaintCanvas paint_canvas(bitmap);
Canvas canvas(&paint_canvas, 1.0f);
paint_canvas.clear(SK_ColorWHITE);
SetGlyphWidth(kGlyphWidth);
RenderText* render_text = GetRenderText();
render_text->set_selection_background_focused_color(kTranslucentBlue);
render_text->set_focused(true);
render_text->SetText(UTF8ToUTF16(kTestString));
render_text->SelectRange(Range(0, 7));
const Rect text_rect = Rect(render_text->GetStringSize());
render_text->SetDisplayRect(text_rect);
render_text->Draw(&canvas);
const uint32_t* buffer = static_cast<const uint32_t*>(bitmap.getPixels());
ASSERT_NE(nullptr, buffer);
TestRectangleBuffer rect_buffer(kTestString, buffer, kCanvasSize.width(),
kCanvasSize.height());
// This whole slice should be the same color and opacity.
rect_buffer.EnsureRectIsAllSameColor(0, 0, text_rect.width() - 1, 1);
}
TEST_F(RenderTextTest, SelectRangeColoredGrapheme) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("x\u0065\u0301y"));
render_text->SetColor(SK_ColorBLACK);
render_text->set_selection_color(SK_ColorRED);
render_text->set_focused(true);
render_text->SelectRange(Range(0, 1));
Draw();
ExpectTextLog({{1, SK_ColorRED}, {2, SK_ColorBLACK}});
render_text->SelectRange(Range(1, 2));
Draw();
ExpectTextLog({{1, SK_ColorBLACK}, {1, SK_ColorRED}, {1, SK_ColorBLACK}});
render_text->SelectRange(Range(2, 3));
Draw();
ExpectTextLog({{1, SK_ColorBLACK}, {1, SK_ColorRED}, {1, SK_ColorBLACK}});
render_text->SelectRange(Range(2, 4));
Draw();
ExpectTextLog({{1, SK_ColorBLACK}, {2, SK_ColorRED}});
}
TEST_F(RenderTextTest, SelectRangeMultiple) {
RenderText* render_text = GetRenderText();
render_text->set_selection_color(SK_ColorRED);
render_text->SetText(ASCIIToUTF16("abcdef"));
render_text->set_focused(true);
// Multiple selections
render_text->SelectRange(Range(0, 1));
render_text->SelectRange(Range(4, 2), false);
Draw();
ExpectTextLog({{1, SK_ColorRED}, {1}, {2, SK_ColorRED}, {2}});
// Setting a primary selection should override secondary selections
render_text->SelectRange(Range(5, 6));
Draw();
ExpectTextLog({{5}, {1, SK_ColorRED}});
render_text->ClearSelection();
Draw();
ExpectTextLog({{6}});
}
TEST_F(RenderTextTest, SetCompositionRangeColored) {
RenderText* render_text = GetRenderText();
render_text->SetText(ASCIIToUTF16("abcdef"));
render_text->SetCompositionRange(Range(0, 1));
Draw();
ExpectTextLog({{1}, {5}});
render_text->SetCompositionRange(Range(1, 3));
Draw();
ExpectTextLog({{1}, {2}, {3}});
render_text->SetCompositionRange(Range::InvalidRange());
Draw();
ExpectTextLog({{6}});
}
TEST_F(RenderTextTest, SetCompositionRangeColoredGrapheme) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("x\u0065\u0301y"));
render_text->SetCompositionRange(Range(0, 1));
Draw();
ExpectTextLog({{1}, {2}});
render_text->SetCompositionRange(Range(2, 3));
Draw();
ExpectTextLog({{3}});
render_text->SetCompositionRange(Range(2, 4));
Draw();
ExpectTextLog({{2}, {1}});
}
void TestVisualCursorMotionInObscuredField(
RenderText* render_text,
const base::string16& text,
SelectionBehavior selection_behavior) {
const bool select = selection_behavior != SELECTION_NONE;
ASSERT_TRUE(render_text->obscured());
render_text->SetText(text);
int len = text.length();
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, selection_behavior);
EXPECT_EQ(SelectionModel(Range(select ? 0 : len, len), CURSOR_FORWARD),
render_text->selection_model());
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, selection_behavior);
EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model());
for (int j = 1; j <= len; ++j) {
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, selection_behavior);
EXPECT_EQ(SelectionModel(Range(select ? 0 : j, j), CURSOR_BACKWARD),
render_text->selection_model());
}
for (int j = len - 1; j >= 0; --j) {
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, selection_behavior);
EXPECT_EQ(SelectionModel(Range(select ? 0 : j, j), CURSOR_FORWARD),
render_text->selection_model());
}
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, selection_behavior);
EXPECT_EQ(SelectionModel(Range(select ? 0 : len, len), CURSOR_FORWARD),
render_text->selection_model());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, selection_behavior);
EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model());
}
TEST_F(RenderTextTest, ObscuredText) {
const base::string16 seuss = ASCIIToUTF16("hop on pop");
const base::string16 no_seuss = GetObscuredString(seuss.length());
RenderText* render_text = GetRenderText();
// GetDisplayText() returns a string filled with
// RenderText::kPasswordReplacementChar when the obscured bit is set.
render_text->SetText(seuss);
render_text->SetObscured(true);
EXPECT_EQ(seuss, render_text->text());
EXPECT_EQ(no_seuss, render_text->GetDisplayText());
render_text->SetObscured(false);
EXPECT_EQ(seuss, render_text->text());
EXPECT_EQ(seuss, render_text->GetDisplayText());
render_text->SetObscured(true);
// Surrogate pairs are counted as one code point.
const base::char16 invalid_surrogates[] = {0xDC00, 0xD800, 0};
render_text->SetText(invalid_surrogates);
EXPECT_EQ(GetObscuredString(2), render_text->GetDisplayText());
const base::char16 valid_surrogates[] = {0xD800, 0xDC00, 0};
render_text->SetText(valid_surrogates);
EXPECT_EQ(GetObscuredString(1), render_text->GetDisplayText());
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(2U, render_text->cursor_position());
// Test index conversion and cursor validity with a valid surrogate pair.
// Text contains "u+D800 u+DC00" and display text contains "u+2022".
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U));
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U));
EXPECT_EQ(1U, test_api()->TextIndexToDisplayIndex(2U));
EXPECT_EQ(0U, test_api()->DisplayIndexToTextIndex(0U));
EXPECT_EQ(2U, test_api()->DisplayIndexToTextIndex(1U));
EXPECT_TRUE(render_text->IsValidCursorIndex(0U));
EXPECT_FALSE(render_text->IsValidCursorIndex(1U));
EXPECT_TRUE(render_text->IsValidCursorIndex(2U));
// FindCursorPosition() should not return positions between a surrogate pair.
render_text->SetDisplayRect(Rect(0, 0, 20, 20));
const int cursor_y = GetCursorYForTesting();
EXPECT_EQ(render_text->FindCursorPosition(Point(0, cursor_y)).caret_pos(),
0U);
EXPECT_EQ(render_text->FindCursorPosition(Point(20, cursor_y)).caret_pos(),
2U);
for (int x = -1; x <= 20; ++x) {
SelectionModel selection =
render_text->FindCursorPosition(Point(x, cursor_y));
EXPECT_TRUE(selection.caret_pos() == 0U || selection.caret_pos() == 2U);
}
// GetCursorSpan() should yield the entire string bounds for text index 0.
EXPECT_EQ(render_text->GetStringSize().width(),
std::ceil(render_text->GetCursorSpan({0, 2}).length()));
// Cursoring is independent of underlying characters when text is obscured.
const char* const texts[] = {
kWeak, kLtr, kLtrRtl, kLtrRtlLtr, kRtl, kRtlLtr, kRtlLtrRtl,
"hop on pop", // Check LTR word boundaries.
"\u05d0\u05d1 \u05d0\u05d2 \u05d1\u05d2", // Check RTL word boundaries.
};
for (size_t i = 0; i < base::size(texts); ++i) {
base::string16 text = UTF8ToUTF16(texts[i]);
TestVisualCursorMotionInObscuredField(render_text, text, SELECTION_NONE);
TestVisualCursorMotionInObscuredField(render_text, text, SELECTION_RETAIN);
}
}
TEST_F(RenderTextTest, ObscuredTextMultiline) {
const base::string16 test = ASCIIToUTF16("a\nbc\ndef");
RenderText* render_text = GetRenderText();
render_text->SetText(test);
render_text->SetObscured(true);
render_text->SetMultiline(true);
// Newlines should be kept in multiline mode.
base::string16 display_text = render_text->GetDisplayText();
EXPECT_EQ(display_text[1], '\n');
EXPECT_EQ(display_text[4], '\n');
}
TEST_F(RenderTextTest, ObscuredTextMultilineNewline) {
const base::string16 test = ASCIIToUTF16("\r\r\n");
RenderText* render_text = GetRenderText();
render_text->SetText(test);
render_text->SetObscured(true);
render_text->SetMultiline(true);
// Newlines should be kept in multiline mode.
base::string16 display_text = render_text->GetDisplayText();
EXPECT_EQ(display_text[0], '\r');
EXPECT_EQ(display_text[1], '\r');
EXPECT_EQ(display_text[2], '\n');
}
TEST_F(RenderTextTest, RevealObscuredText) {
const base::string16 seuss = ASCIIToUTF16("hop on pop");
const base::string16 no_seuss = GetObscuredString(seuss.length());
RenderText* render_text = GetRenderText();
render_text->SetText(seuss);
render_text->SetObscured(true);
EXPECT_EQ(seuss, render_text->text());
EXPECT_EQ(no_seuss, render_text->GetDisplayText());
// Valid reveal index and new revealed index clears previous one.
render_text->RenderText::SetObscuredRevealIndex(0);
EXPECT_EQ(GetObscuredString(seuss.length(), 0, 'h'),
render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(1);
EXPECT_EQ(GetObscuredString(seuss.length(), 1, 'o'),
render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(2);
EXPECT_EQ(GetObscuredString(seuss.length(), 2, 'p'),
render_text->GetDisplayText());
// Invalid reveal index.
render_text->RenderText::SetObscuredRevealIndex(-1);
EXPECT_EQ(no_seuss, render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(seuss.length() + 1);
EXPECT_EQ(no_seuss, render_text->GetDisplayText());
// SetObscured clears the revealed index.
render_text->RenderText::SetObscuredRevealIndex(0);
EXPECT_EQ(GetObscuredString(seuss.length(), 0, 'h'),
render_text->GetDisplayText());
render_text->SetObscured(false);
EXPECT_EQ(seuss, render_text->GetDisplayText());
render_text->SetObscured(true);
EXPECT_EQ(no_seuss, render_text->GetDisplayText());
// SetText clears the revealed index.
render_text->SetText(ASCIIToUTF16("new"));
EXPECT_EQ(GetObscuredString(3), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(2);
EXPECT_EQ(GetObscuredString(3, 2, 'w'), render_text->GetDisplayText());
render_text->SetText(ASCIIToUTF16("new longer"));
EXPECT_EQ(GetObscuredString(10), render_text->GetDisplayText());
// Text with invalid surrogates (surrogates low 0xDC00 and high 0xD800).
// Invalid surrogates are replaced by replacement character (e.g. 0xFFFD).
const base::char16 invalid_surrogates[] = {0xDC00, 0xD800, 'h', 'o', 'p', 0};
render_text->SetText(invalid_surrogates);
EXPECT_EQ(GetObscuredString(5), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(0);
EXPECT_EQ(GetObscuredString(5, 0, 0xFFFD), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(1);
EXPECT_EQ(GetObscuredString(5, 1, 0xFFFD), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(2);
EXPECT_EQ(GetObscuredString(5, 2, 'h'), render_text->GetDisplayText());
// Text with valid surrogates before and after the reveal index.
const base::char16 valid_surrogates[] =
{0xD800, 0xDC00, 'h', 'o', 'p', 0xD800, 0xDC00, 0};
render_text->SetText(valid_surrogates);
EXPECT_EQ(GetObscuredString(5), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(0);
const base::char16 valid_expect_0_and_1[] = {
0xD800,
0xDC00,
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar,
0};
EXPECT_EQ(valid_expect_0_and_1, render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(1);
EXPECT_EQ(valid_expect_0_and_1, render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(2);
EXPECT_EQ(GetObscuredString(5, 1, 'h'), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(5);
const base::char16 valid_expect_5_and_6[] = {
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar,
0xD800,
0xDC00,
0};
EXPECT_EQ(valid_expect_5_and_6, render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(6);
EXPECT_EQ(valid_expect_5_and_6, render_text->GetDisplayText());
}
TEST_F(RenderTextTest, ObscuredEmoji) {
// Ensures text itemization doesn't crash on obscured multi-char glyphs.
RenderText* render_text = GetRenderText();
render_text->SetObscured(true);
// Test U+1F601 😁 "Grinning face with smiling eyes", followed by 'y'.
// Windows requires wide strings for \Unnnnnnnn universal character names.
render_text->SetText(WideToUTF16(L"\U0001F601y"));
render_text->Draw(canvas());
// Emoji codepoints are replaced by bullets (e.g. "\u2022\u2022").
EXPECT_EQ(UTF8ToUTF16("\u2022\u2022"), render_text->GetDisplayText());
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U));
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U));
EXPECT_EQ(1U, test_api()->TextIndexToDisplayIndex(2U));
EXPECT_EQ(0U, test_api()->DisplayIndexToTextIndex(0U));
EXPECT_EQ(2U, test_api()->DisplayIndexToTextIndex(1U));
// Out of bound accesses.
EXPECT_EQ(2U, test_api()->TextIndexToDisplayIndex(3U));
EXPECT_EQ(3U, test_api()->DisplayIndexToTextIndex(2U));
// Test two U+1F4F7 📷 "Camera" characters in a row.
// Windows requires wide strings for \Unnnnnnnn universal character names.
render_text->SetText(WideToUTF16(L"\U0001F4F7\U0001F4F7"));
render_text->Draw(canvas());
// Emoji codepoints are replaced by bullets (e.g. "\u2022\u2022").
EXPECT_EQ(UTF8ToUTF16("\u2022\u2022"), render_text->GetDisplayText());
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U));
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U));
EXPECT_EQ(1U, test_api()->TextIndexToDisplayIndex(2U));
EXPECT_EQ(1U, test_api()->TextIndexToDisplayIndex(3U));
EXPECT_EQ(0U, test_api()->DisplayIndexToTextIndex(0U));
EXPECT_EQ(2U, test_api()->DisplayIndexToTextIndex(1U));
// Reveal the first emoji.
render_text->SetObscuredRevealIndex(0);
render_text->Draw(canvas());
EXPECT_EQ(WideToUTF16(L"\U0001F4F7\u2022"), render_text->GetDisplayText());
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U));
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(1U));
EXPECT_EQ(2U, test_api()->TextIndexToDisplayIndex(2U));
EXPECT_EQ(2U, test_api()->TextIndexToDisplayIndex(3U));
EXPECT_EQ(0U, test_api()->DisplayIndexToTextIndex(0U));
EXPECT_EQ(0U, test_api()->DisplayIndexToTextIndex(1U));
EXPECT_EQ(2U, test_api()->DisplayIndexToTextIndex(2U));
}
TEST_F(RenderTextTest, ObscuredEmojiRevealed) {
RenderText* render_text = GetRenderText();
base::string16 text = WideToUTF16(L"123\U0001F4F7\U0001F4F7x\U0001F601-");
for (size_t i = 0; i < text.length(); ++i) {
render_text->SetText(text);
render_text->SetObscured(true);
render_text->SetObscuredRevealIndex(i);
render_text->Draw(canvas());
}
}
struct TextIndexConversionCase {
const char* test_name;
const wchar_t* text;
};
using TextIndexConversionParam =
std::tuple<TextIndexConversionCase, bool, size_t>;
class RenderTextTestWithTextIndexConversionCase
: public RenderTextTest,
public ::testing::WithParamInterface<TextIndexConversionParam> {
public:
static std::string ParamInfoToString(
::testing::TestParamInfo<TextIndexConversionParam> param_info) {
TextIndexConversionCase param = std::get<0>(param_info.param);
bool obscured = std::get<1>(param_info.param);
size_t reveal_index = std::get<2>(param_info.param);
return base::StringPrintf("%s%s%zu", param.test_name,
(obscured ? "Obscured" : ""), reveal_index);
}
};
TEST_P(RenderTextTestWithTextIndexConversionCase, TextIndexConversion) {
TextIndexConversionCase param = std::get<0>(GetParam());
bool obscured = std::get<1>(GetParam());
size_t reveal_index = std::get<2>(GetParam());
RenderText* render_text = GetRenderText();
render_text->SetText(WideToUTF16(param.text));
render_text->SetObscured(obscured);
render_text->SetObscuredRevealIndex(reveal_index);
render_text->Draw(canvas());
base::string16 text = render_text->text();
base::string16 display_text = render_text->GetDisplayText();
// Adjust reveal_index to point to the beginning of the surrogate pair, if
// needed.
U16_SET_CP_START(text.c_str(), 0, reveal_index);
// Validate that codepoints still match.
for (base::i18n::UTF16CharIterator iter(render_text->text()); !iter.end();
iter.Advance()) {
size_t text_index = iter.array_pos();
size_t display_index = test_api()->TextIndexToDisplayIndex(text_index);
EXPECT_EQ(text_index, test_api()->DisplayIndexToTextIndex(display_index));
if (obscured && reveal_index != text_index) {
EXPECT_EQ(display_text[display_index],
RenderText::kPasswordReplacementChar);
} else {
EXPECT_EQ(display_text[display_index], text[text_index]);
}
}
}
const TextIndexConversionCase kTextIndexConversionCases[] = {
{"simple", L"abc"},
{"simple_obscured1", L"abc"},
{"simple_obscured2", L"abc"},
{"emoji_asc", L"\U0001F6281234"},
{"emoji_asc_obscured0", L"\U0001F6281234"},
{"emoji_asc_obscured2", L"\U0001F6281234"},
{"picto_title", L"x☛"},
{"simple_mixed", L"aaڭڭcc"},
{"simple_rtl", L"أسكي"},
};
// Validate that conversion text and between display text indexes are consistent
// even when text obscured and reveal character features are used.
INSTANTIATE_TEST_SUITE_P(
ItemizeTextToRunsConversion,
RenderTextTestWithTextIndexConversionCase,
::testing::Combine(::testing::ValuesIn(kTextIndexConversionCases),
testing::Values(false, true),
testing::Values(0, 1, 4)),
RenderTextTestWithTextIndexConversionCase::ParamInfoToString);
struct RunListCase {
const char* test_name;
const wchar_t* text;
const char* expected;
const bool multiline = false;
};
class RenderTextTestWithRunListCase
: public RenderTextTest,
public ::testing::WithParamInterface<RunListCase> {
public:
static std::string ParamInfoToString(
::testing::TestParamInfo<RunListCase> param_info) {
return param_info.param.test_name;
}
};
TEST_P(RenderTextTestWithRunListCase, ItemizeTextToRuns) {
RunListCase param = GetParam();
RenderTextHarfBuzz* render_text = GetRenderText();
render_text->SetMultiline(param.multiline);
render_text->SetText(WideToUTF16(param.text));
EXPECT_EQ(param.expected, GetRunListStructureString());
}
const RunListCase kBasicsRunListCases[] = {
{"simpleLTR", L"abc", "[0->2]"},
{"simpleRTL", L"ښڛڜ", "[2<-0]"},
{"asc_arb", L"abcښڛڜdef", "[0->2][5<-3][6->8]"},
{"asc_dev_asc", L"abcऔकखdefڜ", "[0->2][3->5][6->8][9]"},
{"phone", L"1-(800)-xxx-xxxx", "[0][1][2][3->5][6][7][8->10][11][12->15]"},
{"dev_ZWS", L"क\u200Bख", "[0][1][2]"},
{"numeric", L"1 2 3 4", "[0][1][2][3][4][5][6]"},
{"joiners1", L"1\u200C2\u200C3\u200C4", "[0->6]"},
{"joiners2", L"\u060F\u200C\u060F", "[0->2]"},
{"combining_accents1", L"a\u0300e\u0301", "[0->3]"},
{"combining_accents2", L"\u0065\u0308\u0435\u0308", "[0->1][2->3]"},
{"picto_title", L"☞☛test☚☜", "[0->1][2->5][6->7]"},
{"picto_LTR", L"☺☺☺!", "[0->2][3]"},
{"picto_RTL", L"☺☺☺ښ", "[3][2<-0]"},
{"paren_picto", L"(☾☹☽)", "[0][1][2][3][4]"},
{"emoji_asc", L"\U0001F6281234",
"[0->1][2->5]"}, // http://crbug.com/530021
{"emoji_title", L"▶Feel goods",
"[0][1->4][5][6->10]"}, // http://crbug.com/278913
{"jap_paren1", L"ぬ「シ」ほ",
"[0][1][2][3][4]"}, // http://crbug.com/396776
{"jap_paren2", L"國哲(c)1",
"[0->1][2][3][4][5]"}, // http://crbug.com/125792
{"newline1", L"\n\n", "[0->1]"},
{"newline2", L"\r\n\r\n", "[0->3]"},
{"newline3", L"\r\r\n", "[0->2]"},
{"multiline_newline1", L"\n\n", "[0][1]", true},
{"multiline_newline2", L"\r\n\r\n", "[0->1][2->3]", true},
{"multiline_newline3", L"\r\r\n", "[0][1->2]", true},
};
INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsBasics,
RenderTextTestWithRunListCase,
::testing::ValuesIn(kBasicsRunListCases),
RenderTextTestWithRunListCase::ParamInfoToString);
// see 'Unicode Bidirectional Algorithm': http://unicode.org/reports/tr9/
const RunListCase kBidiRunListCases[] = {
{"simple_ltr", L"ascii", "[0->4]"},
{"simple_rtl", L"أسكي", "[3<-0]"},
{"simple_mixed", L"aaڭڭcc", "[0->1][3<-2][4->5]"},
{"simple_mixed_LRE", L"\u202Aaaڭڭcc\u202C", "[0][1->2][4<-3][5->6][7]"},
{"simple_mixed_RLE", L"\u202Baaڭڭcc\u202C", "[7][5->6][4<-3][0][1->2]"},
{"sequence_RLE", L"\u202Baa\u202C\u202Bbb\u202C",
"[7][0][1->2][3->4][5->6]"},
{"simple_mixed_LRI", L"\u2066aaڭڭcc\u2069", "[0][1->2][4<-3][5->6][7]"},
{"simple_mixed_RLI", L"\u2067aaڭڭcc\u2069", "[0][5->6][4<-3][1->2][7]"},
{"sequence_RLI", L"\u2067aa\u2069\u2067bb\u2069",
"[0][1->2][3->4][5->6][7]"},
{"override_ltr_RLO", L"\u202Eaaa\u202C", "[4][3<-1][0]"},
{"override_rtl_LRO", L"\u202Dڭڭڭ\u202C", "[0][1->3][4]"},
{"neutral_strong_ltr", L"a!!a", "[0][1->2][3]"},
{"neutral_strong_rtl", L"ڭ!!ڭ", "[3][2<-1][0]"},
{"neutral_strong_both", L"a a ڭ ڭ", "[0][1][2][3][6][5][4]"},
{"neutral_strong_both_RLE", L"\u202Ba a ڭ ڭ\u202C",
"[8][7][6][5][4][0][1][2][3]"},
{"weak_numbers", L"one ڭ222ڭ", "[0->2][3][8][5->7][4]"},
{"not_weak_letters", L"one ڭabcڭ", "[0->2][3][4][5->7][8]"},
{"weak_arabic_numbers", L"one ڭ١٢٣ڭ", "[0->2][3][8][5->7][4]"},
{"neutral_LRM_pre", L"\u200E\u2026\u2026", "[0->2]"},
{"neutral_LRM_post", L"\u2026\u2026\u200E", "[0->2]"},
{"neutral_RLM_pre", L"\u200F\u2026\u2026", "[2<-0]"},
{"neutral_RLM_post", L"\u2026\u2026\u200F", "[2<-0]"},
{"brackets_ltr", L"aa(ڭڭ)\u2026\u2026", "[0->1][2][4<-3][5][6->7]"},
{"brackets_rtl", L"ڭڭ(aa)\u2026\u2026", "[7<-6][5][3->4][2][1<-0]"},
{"mixed_with_punct", L"aa \"ڭڭ!\", aa",
"[0->1][2][3][5<-4][6->8][9][10->11]"},
{"mixed_with_punct_RLI", L"aa \"\u2067ڭڭ!\u2069\", aa",
"[0->1][2][3][4][7][6<-5][8][9->10][11][12->13]"},
{"mixed_with_punct_RLM", L"aa \"ڭڭ!\u200F\", aa",
"[0->1][2][3][7][6][5<-4][8->9][10][11->12]"},
};
INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsBidi,
RenderTextTestWithRunListCase,
::testing::ValuesIn(kBidiRunListCases),
RenderTextTestWithRunListCase::ParamInfoToString);
const RunListCase kBracketsRunListCases[] = {
{"matched_parens", L"(a)", "[0][1][2]"},
{"double_matched_parens", L"((a))", "[0->1][2][3->4]"},
{"double_matched_parens2", L"((aaa))", "[0->1][2->4][5->6]"},
{"square_brackets", L"[...]x", "[0][1->3][4][5]"},
{"curly_brackets", L"{}x{}", "[0->1][2][3->4]"},
{"style_brackets", L"\u300c...\u300dx", "[0][1->3][4][5]"},
{"tibetan_brackets", L"\u0f3a\u0f3b\u0f20\u0f20\u0f3c\u0f3d",
"[0->1][2->3][4->5]"},
{"angle_brackets", L"\u3008\u3007\u3007\u3009", "[0][1->2][3]"},
{"double_angle_brackets", L"\u300A\u3007\u3007\u300B", "[0][1->2][3]"},
{"corner_angle_brackets", L"\u300C\u3007\u3007\u300D", "[0][1->2][3]"},
{"fullwidth_parens", L"\uff08\uff01\uff09", "[0][1][2]"},
};
INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsBrackets,
RenderTextTestWithRunListCase,
::testing::ValuesIn(kBracketsRunListCases),
RenderTextTestWithRunListCase::ParamInfoToString);
// Test cases to ensure the extraction of script extensions are taken into
// account while performing the text itemization.
// See table 7 from http://www.unicode.org/reports/tr24/tr24-29.html
const RunListCase kScriptExtensionRunListCases[] = {
{"implicit_com_inherited", L"a\u0301", "[0->1]"},
{"explicit_lat", L"\u0061d", "[0->1]"},
{"explicit_inherited_lat", L"x\u0363d", "[0->2]"},
{"explicit_inherited_dev", L"क\u1CD1क", "[0->2]"},
{"multi_explicit_hira", L"は\u30FCz", "[0->1][2]"},
{"multi_explicit_kana", L"ハ\u30FCz", "[0->1][2]"},
{"multi_explicit_lat", L"a\u30FCz", "[0][1][2]"},
{"multi_explicit_impl_dev", L"क\u1CD0z", "[0->1][2]"},
{"multi_explicit_expl_dev", L"क\u096Fz", "[0->1][2]"},
};
INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsScriptExtension,
RenderTextTestWithRunListCase,
::testing::ValuesIn(kScriptExtensionRunListCases),
RenderTextTestWithRunListCase::ParamInfoToString);
// Test cases to ensure ItemizeTextToRuns is splitting text based on unicode
// script (intersection of script extensions).
// See ScriptExtensions.txt and Scripts.txt from
// http://www.unicode.org/reports/tr24/tr24-29.html
const RunListCase kScriptsRunListCases[] = {
{"lat", L"abc", "[0->2]"},
{"lat_diac", L"e\u0308f", "[0->2]"},
// Indic Fraction codepoints have large set of script extensions.
{"indic_fraction", L"\uA830\uA832\uA834\uA835", "[0->3]"},
// Devanagari Danda codepoints have large set of script extensions.
{"dev_danda", L"\u0964\u0965", "[0->1]"},
// Combining Diacritical Marks (inherited) should only merge with preceding.
{"diac_lat", L"\u0308fg", "[0][1->2]"},
{"diac_dev", L"क\u0308f", "[0->1][2]"},
// ZWJW has the inherited script.
{"lat_ZWNJ", L"ab\u200Ccd", "[0->4]"},
{"dev_ZWNJ", L"क\u200Cक", "[0->2]"},
{"lat_dev_ZWNJ", L"a\u200Cक", "[0->1][2]"},
// Invalid codepoints.
{"invalid_cp", L"\uFFFE", "[0]"},
{"invalid_cps", L"\uFFFE\uFFFF", "[0->1]"},
{"unknown", L"a\u243Fb", "[0][1][2]"},
// Codepoints from different code block should be in same run when part of
// the same script.
{"blocks_lat", L"aɒɠƉĚÑ", "[0->5]"},
{"blocks_lat_paren", L"([_!_])", "[0->1][2->4][5->6]"},
{"blocks_lat_sub", L"ₐₑaeꬱ", "[0->4]"},
{"blocks_lat_smallcap", L"ꟺM", "[0->1]"},
{"blocks_lat_small_letter", L"ᶓᶍᶓᴔᴟ", "[0->4]"},
{"blocks_lat_acc", L"eéěĕȩɇḕẻếⱻꞫ", "[0->10]"},
{"blocks_com", L"⟦ℳ¥¾⟾⁸⟧Ⓔ", "[0][1][2->3][4][5][6][7]"},
// Latin script.
{"latin_numbers", L"a1b2c3", "[0][1][2][3][4][5]"},
{"latin_puncts1", L"a,b,c.", "[0][1][2][3][4][5]"},
{"latin_puncts2", L"aa,bb,cc!!", "[0->1][2][3->4][5][6->7][8->9]"},
{"latin_diac_multi", L"a\u0300e\u0352i", "[0->4]"},
// Common script.
{"common_tm", L"•bug™", "[0][1->3][4]"},
{"common_copyright", L"chromium©", "[0->7][8]"},
{"common_math1", L"ℳ: ¬ƒ(x)=½×¾", "[0][1][2][3][4][5][6][7][8][9->11]"},
{"common_math2", L"𝟏×𝟑", "[0->1][2][3->4]"},
{"common_numbers", L"🄀𝟭𝟐⒓¹²", "[0->1][2->5][6][7->8]"},
{"common_puncts", L",.\u0083!", "[0->1][2][3]"},
// Arabic script.
{"arabic", L"\u0633\u069b\u0763\u077f\u08A2\uFB53", "[5<-0]"},
{"arabic_lat", L"\u0633\u069b\u0763\u077f\u08A2\uFB53abc", "[6->8][5<-0]"},
{"arabic_word_ligatures", L"\uFDFD\uFDF3", "[1<-0]"},
{"arabic_diac", L"\u069D\u0300", "[1<-0]"},
{"arabic_diac_lat", L"\u069D\u0300abc", "[2->4][1<-0]"},
{"arabic_diac_lat2", L"abc\u069D\u0300abc", "[0->2][4<-3][5->7]"},
{"arabic_lyd", L"\U00010935\U00010930\u06B0\u06B1", "[5<-4][3<-0]"},
{"arabic_numbers", L"12\u06D034", "[3->4][2][0->1]"},
{"arabic_letters", L"ab\u06D0cd", "[0->1][2][3->4]"},
{"arabic_mixed", L"a1\u06D02d", "[0][1][3][2][4]"},
{"arabic_coptic1", L"\u06D0\U000102E2\u2CB2", "[1->3][0]"},
{"arabic_coptic2", L"\u2CB2\U000102E2\u06D0", "[0->2][3]"},
// Devanagari script.
{"devanagari1", L"ञटठडढणतथ", "[0->7]"},
{"devanagari2", L"ढ꣸ꣴ", "[0->2]"},
{"devanagari_vowels", L"\u0915\u093F\u0915\u094C", "[0->3]"},
{"devanagari_consonants", L"\u0915\u094D\u0937", "[0->2]"},
// Ethiopic script.
{"ethiopic", L"መጩጪᎅⶹⶼꬣꬦ", "[0->7]"},
{"ethiopic_numbers", L"1ቨቤ2", "[0][1->2][3]"},
{"ethiopic_mixed1", L"abቨቤ12", "[0->1][2->3][4->5]"},
{"ethiopic_mixed2", L"a1ቨቤb2", "[0][1][2->3][4][5]"},
// Georgian script.
{"georgian1", L"ႼႽႾႿჀჁჂჳჴჵ", "[0->9]"},
{"georgian2", L"ლⴊⴅ", "[0->2]"},
{"georgian_numbers", L"1ლⴊⴅ2", "[0][1->3][4]"},
{"georgian_mixed", L"a1ლⴊⴅb2", "[0][1][2->4][5][6]"},
// Telugu script.
{"telugu_lat", L"aaఉయ!", "[0->1][2->3][4]"},
{"telugu_numbers", L"123౦౧౨456౩౪౫", "[0->2][3->5][6->8][9->11]"},
{"telugu_puncts", L"కురుచ, చిఱుత, చేరువ, చెఱువు!",
"[0->4][5][6][7->11][12][13][14->18][19][20][21->26][27]"},
// Control Pictures.
{"control_pictures", L"␑␒␓␔␕␖␗␘␙␚␛", "[0->10]"},
{"control_pictures_rewrite", L"␑\t␛", "[0->2]"},
// Unicode art.
{"unicode_emoticon1", L"(▀̿ĺ̯▀̿ ̿)", "[0][1->2][3->4][5->6][7->8][9]"},
{"unicode_emoticon2", L"▀̿̿Ĺ̯̿▀̿ ", "[0->2][3->5][6->7][8]"},
{"unicode_emoticon3", L"( ͡° ͜ʖ ͡°)", "[0][1->2][3][4->5][6][7->8][9][10]"},
{"unicode_emoticon4", L"✩·͙*̩̩͙˚̩̥̩̥( ͡ᵔ ͜ʖ ͡ᵔ )*̩̩͙✩·͙˚̩̥̩̥.",
"[0][1->2][3->6][7->11][12][13->14][15][16->17][18][19->20][21][22][23]["
"24->27][28][29->30][31->35][36]"},
{"unicode_emoticon5", L"ヽ(͡◕ ͜ʖ ͡◕)ノ",
"[0][1->2][3][4->5][6][7->8][9][10][11]"},
{"unicode_art1", L"꧁༒✧ Great ✧༒꧂", "[0][1][2][3][4->8][9][10][11][12]"},
{"unicode_art2", L"t͎e͎s͎t͎", "[0->7]"},
// Combining diacritical sequences.
{"unicode_diac1", L"\u2123\u0336", "[0->1]"},
{"unicode_diac2", L"\u273c\u0325", "[0->1]"},
{"unicode_diac3", L"\u2580\u033f", "[0->1]"},
{"unicode_diac4", L"\u2022\u0325\u0329", "[0->2]"},
{"unicode_diac5", L"\u2022\u0325", "[0->1]"},
{"unicode_diac6", L"\u00b7\u0359\u0325", "[0->2]"},
{"unicode_diac7", L"\u2027\u0329\u0325", "[0->2]"},
{"unicode_diac8", L"\u0332\u0305\u03c1", "[0->1][2]"},
};
INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsScripts,
RenderTextTestWithRunListCase,
::testing::ValuesIn(kScriptsRunListCases),
RenderTextTestWithRunListCase::ParamInfoToString);
// Test cases to ensure ItemizeTextToRuns is splitting emoji correctly.
// see: http://www.unicode.org/reports/tr51
// see: http://www.unicode.org/emoji/charts/full-emoji-list.html
const RunListCase kEmojiRunListCases[] = {
// Samples from
// https://www.unicode.org/Public/emoji/12.0/emoji-data.txt
{"number_sign", L"\u0023", "[0]"},
{"keyboard", L"\u2328", "[0]"},
{"aries", L"\u2648", "[0]"},
{"candle", L"\U0001F56F", "[0->1]"},
{"anchor", L"\u2693", "[0]"},
{"grinning_face", L"\U0001F600", "[0->1]"},
{"face_with_monocle", L"\U0001F9D0", "[0->1]"},
{"light_skin_tone", L"\U0001F3FB", "[0->1]"},
{"index_pointing_up", L"\u261D", "[0]"},
{"horse_racing", L"\U0001F3C7", "[0->1]"},
{"kiss", L"\U0001F48F", "[0->1]"},
{"couple_with_heart", L"\U0001F491", "[0->1]"},
{"people_wrestling", L"\U0001F93C", "[0->1]"},
{"eject_button", L"\u23CF", "[0]"},
// Samples from
// https://unicode.org/Public/emoji/12.0/emoji-sequences.txt
{"watch", L"\u231A", "[0]"},
{"cross_mark", L"\u274C", "[0]"},
{"copyright", L"\u00A9\uFE0F", "[0->1]"},
{"stop_button", L"\u23F9\uFE0F", "[0->1]"},
{"passenger_ship", L"\U0001F6F3\uFE0F", "[0->2]"},
{"keycap_star", L"\u002A\uFE0F\u20E3", "[0->2]"},
{"keycap_6", L"\u0036\uFE0F\u20E3", "[0->2]"},
{"flag_andorra", L"\U0001F1E6\U0001F1E9", "[0->3]"},
{"flag_egypt", L"\U0001F1EA\U0001F1EC", "[0->3]"},
{"flag_england",
L"\U0001F3F4\U000E0067\U000E0062\U000E0065\U000E006E\U000E0067\U000E007F",
"[0->13]"},
{"index_up_light", L"\u261D\U0001F3FB", "[0->2]"},
{"person_bouncing_ball_light", L"\u26F9\U0001F3FC", "[0->2]"},
{"victory_hand_med_light", L"\u270C\U0001F3FC", "[0->2]"},
{"horse_racing_med_dark", L"\U0001F3C7\U0001F3FE", "[0->3]"},
{"woman_man_hands_light", L"\U0001F46B\U0001F3FB", "[0->3]"},
{"person_haircut_med_light", L"\U0001F487\U0001F3FC", "[0->3]"},
{"pinching_hand_light", L"\U0001F90F\U0001F3FB", "[0->3]"},
{"love_you_light", L"\U0001F91F\U0001F3FB", "[0->3]"},
{"leg_dark", L"\U0001F9B5\U0001F3FF", "[0->3]"},
// Samples from
// https://unicode.org/Public/emoji/12.0/emoji-variation-sequences.txt
{"number_sign_text", L"\u0023\uFE0E", "[0->1]"},
{"number_sign_emoji", L"\u0023\uFE0F", "[0->1]"},
{"digit_eight_text", L"\u0038\uFE0E", "[0->1]"},
{"digit_eight_emoji", L"\u0038\uFE0F", "[0->1]"},
{"up_down_arrow_text", L"\u2195\uFE0E", "[0->1]"},
{"up_down_arrow_emoji", L"\u2195\uFE0F", "[0->1]"},
{"stopwatch_text", L"\u23F1\uFE0E", "[0->1]"},
{"stopwatch_emoji", L"\u23F1\uFE0F", "[0->1]"},
{"thermometer_text", L"\U0001F321\uFE0E", "[0->2]"},
{"thermometer_emoji", L"\U0001F321\uFE0F", "[0->2]"},
{"thumbs_up_text", L"\U0001F44D\uFE0E", "[0->2]"},
{"thumbs_up_emoji", L"\U0001F44D\uFE0F", "[0->2]"},
{"hole_text", L"\U0001F573\uFE0E", "[0->2]"},
{"hole_emoji", L"\U0001F573\uFE0F", "[0->2]"},
// Samples from
// https://unicode.org/Public/emoji/12.0/emoji-zwj-sequences.txt
{"couple_man_man", L"\U0001F468\u200D\u2764\uFE0F\u200D\U0001F468",
"[0->7]"},
{"kiss_man_man",
L"\U0001F468\u200D\u2764\uFE0F\u200D\U0001F48B\u200D\U0001F468",
"[0->10]"},
{"family_man_woman_girl_boy",
L"\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466", "[0->10]"},
{"men_hands_dark_medium",
L"\U0001F468\U0001F3FF\u200D\U0001F91D\u200D\U0001F468\U0001F3FD",
"[0->11]"},
{"people_hands_dark",
L"\U0001F9D1\U0001F3FF\u200D\U0001F91D\u200D\U0001F9D1\U0001F3FF",
"[0->11]"},
{"man_pilot", L"\U0001F468\u200D\u2708\uFE0F", "[0->4]"},
{"man_scientist", L"\U0001F468\u200D\U0001F52C", "[0->4]"},
{"man_mechanic_light", L"\U0001F468\U0001F3FB\u200D\U0001F527", "[0->6]"},
{"man_judge_medium", L"\U0001F468\U0001F3FD\u200D\u2696\uFE0F", "[0->6]"},
{"woman_cane_dark", L"\U0001F469\U0001F3FF\u200D\U0001F9AF", "[0->6]"},
{"woman_ball_light", L"\u26F9\U0001F3FB\u200D\u2640\uFE0F", "[0->5]"},
{"woman_running", L"\U0001F3C3\u200D\u2640\uFE0F", "[0->4]"},
{"woman_running_dark", L"\U0001F3C3\U0001F3FF\u200D\u2640\uFE0F", "[0->6]"},
{"woman_turban", L"\U0001F473\u200D\u2640\uFE0F", "[0->4]"},
{"woman_detective", L"\U0001F575\uFE0F\u200D\u2640\uFE0F", "[0->5]"},
{"man_facepalming", L"\U0001F926\u200D\u2642\uFE0F", "[0->4]"},
{"man_red_hair", L"\U0001F468\u200D\U0001F9B0", "[0->4]"},
{"man_medium_curly", L"\U0001F468\U0001F3FD\u200D\U0001F9B1", "[0->6]"},
{"woman_dark_white_hair", L"\U0001F469\U0001F3FF\u200D\U0001F9B3",
"[0->6]"},
{"rainbow_flag", L"\U0001F3F3\uFE0F\u200D\U0001F308", "[0->5]"},
{"pirate_flag", L"\U0001F3F4\u200D\u2620\uFE0F", "[0->4]"},
{"service_dog", L"\U0001F415\u200D\U0001F9BA", "[0->4]"},
{"eye_bubble", L"\U0001F441\uFE0F\u200D\U0001F5E8\uFE0F", "[0->6]"},
};
INSTANTIATE_TEST_SUITE_P(ItemizeTextToRunsEmoji,
RenderTextTestWithRunListCase,
::testing::ValuesIn(kEmojiRunListCases),
RenderTextTestWithRunListCase::ParamInfoToString);
struct ElideTextCase {
const char* test_name;
const wchar_t* text;
const wchar_t* display_text;
};
class RenderTextTestWithElideTextCase
: public RenderTextTest,
public ::testing::WithParamInterface<ElideTextCase> {
public:
static std::string ParamInfoToString(
::testing::TestParamInfo<ElideTextCase> param_info) {
return param_info.param.test_name;
}
};
TEST_P(RenderTextTestWithElideTextCase, ElideText) {
// This test requires glyphs to be the same width.
constexpr int kGlyphWidth = 10;
SetGlyphWidth(kGlyphWidth);
ElideTextCase param = GetParam();
const base::string16 text = WideToUTF16(param.text);
const base::string16 display_text = WideToUTF16(param.display_text);
// Retrieve the display_text width without eliding.
RenderTextHarfBuzz* render_text = GetRenderText();
render_text->SetText(display_text);
const int expected_width = render_text->GetContentWidth();
// Set the text and the eliding behavior.
render_text->SetText(text);
render_text->SetDisplayRect(
Rect(0, 0, expected_width + kGlyphWidth / 2, 100));
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetWhitespaceElision(false);
const int elided_width = render_text->GetContentWidth();
EXPECT_EQ(text, render_text->text());
EXPECT_EQ(display_text, render_text->GetDisplayText());
EXPECT_EQ(elided_width, expected_width);
}
const ElideTextCase kElideTailTextCases[] = {
{"empty", L"", L""},
{"letter_m_tail0", L"M", L""},
{"letter_m_tail1", L"M", L"M"},
{"letter_weak_3", L" . ", L" . "},
{"letter_weak_2", L" . ", L" \u2026"},
{"no_eliding", L"012ab", L"012ab"},
{"ltr_3", L"abc", L"abc"},
{"ltr_2", L"abc", L"a\u2026"},
{"ltr_1", L"abc", L"\u2026"},
{"ltr_0", L"abc", L""},
{"rtl_3", L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2"},
{"rtl_2", L"\u05d0\u05d1\u05d2", L"\u05d0\u2026"},
{"rtl_1", L"\u05d0\u05d1\u05d2", L"\u2026"},
{"rtl_0", L"\u05d0\u05d1\u05d2", L""},
{"ltr_rtl_5", L"abc\u05d0\u05d1\u05d2", L"abc\u05d0\u2026\x200F"},
{"ltr_rtl_4", L"abc\u05d0\u05d1\u05d2", L"abc\u2026"},
{"ltr_rtl_3", L"abc\u05d0\u05d1\u05d2", L"ab\u2026"},
{"rtl_ltr_5", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2a\u2026\x200E"},
{"rtl_ltr_4", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u05d2\u2026"},
{"rtl_ltr_3", L"\u05d0\u05d1\u05d2abc", L"\u05d0\u05d1\u2026"},
{"bidi_1", L"012a\u05d1b\u05d1c", L"012a\u2026"},
{"bidi_2", L"012a\u05d1b\u05d1c", L"012a\u05d1\u2026\x200F"},
{"bidi_3", L"012a\u05d1b\u05d1c", L"012a\u05d1b\u2026\x200F"},
// No RLM marker added as digits (012) have weak directionality.
{"no_rlm", L"01\u05d0\u05d1\u05d2", L"01\u05d0\u2026"},
// RLM marker added as "ab" have strong LTR directionality.
{"with_rlm", L"ab\u05d0\u05d1\u05d2cd", L"ab\u05d0\u05d1\u2026\u200f"},
// Test surrogate pairs. The first pair 𝄞 'MUSICAL SYMBOL G CLEF' U+1D11E
// should be kept, and the second pair 𝄢 'MUSICAL SYMBOL F CLEF' U+1D122
// should be removed. No surrogate pair should be partially elided.
{"surrogate", L"0123\U0001D11E\U0001D122x", L"0123\U0001D11E\u2026"},
// Test combining character sequences. U+0915 U+093F forms a compound
// glyph, as does U+0915 U+0942. The first should be kept; the second
// removed. No combining sequence should be partially elided.
{"combining", L"0123\u0915\u093f\u0915\u0942456",
L"0123\u0915\u093f\u2026"},
// U+05E9 U+05BC U+05C1 U+05B8 forms a four-character compound glyph.
// It should be either fully elided, or not elided at all. If completely
// elided, an LTR Mark (U+200E) should be added.
{"grapheme1", L"0\u05e9\u05bc\u05c1\u05b8", L"0\u05e9\u05bc\u05c1\u05b8"},
{"grapheme2", L"0\u05e9\u05bc\u05c1\u05b8abc", L"0\u2026\u200E"},
{"grapheme3", L"01\u05e9\u05bc\u05c1\u05b8abc", L"01\u2026\u200E"},
{"grapheme4", L"012\u05e9\u05bc\u05c1\u05b8abc", L"012\u2026\u200E"},
// 𝄞 (U+1D11E, MUSICAL SYMBOL G CLEF) should be fully elided.
{"emoji", L"012\U0001D11Ex", L"012\u2026"},
};
INSTANTIATE_TEST_SUITE_P(ElideTail,
RenderTextTestWithElideTextCase,
::testing::ValuesIn(kElideTailTextCases),
RenderTextTestWithElideTextCase::ParamInfoToString);
TEST_F(RenderTextTest, ElidedText_NoTrimWhitespace) {
// This test requires glyphs to be the same width.
constexpr int kGlyphWidth = 10;
SetGlyphWidth(kGlyphWidth);
RenderText* render_text = GetRenderText();
gfx::test::RenderTextTestApi render_text_test_api(render_text);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetWhitespaceElision(false);
// Pick a sufficiently long string that's mostly whitespace.
// Tail-eliding this with whitespace elision turned off should look like:
// [ ...]
// and not like:
// [... ]
constexpr char kInputString[] = " foo";
const base::string16 input = ASCIIToUTF16(kInputString);
render_text->SetText(input);
// Choose a width based on being able to display 12 characters (one of which
// will be the trailing ellipsis).
constexpr int kDesiredChars = 12;
constexpr int kRequiredWidth = (kDesiredChars + 0.5f) * kGlyphWidth;
render_text->SetDisplayRect(Rect(0, 0, kRequiredWidth, 100));
// Verify this doesn't change the full text.
EXPECT_EQ(input, render_text->text());
// Verify that the string is truncated to |kDesiredChars| with the ellipsis.
const base::string16 result = render_text->GetDisplayText();
const base::string16 expected =
input.substr(0, kDesiredChars - 1) + kEllipsisUTF16[0];
EXPECT_EQ(expected, result);
}
TEST_F(RenderTextTest, ElidedObscuredText) {
auto expected_render_text = std::make_unique<RenderTextHarfBuzz>();
expected_render_text->SetDisplayRect(Rect(0, 0, 9999, 100));
const base::char16 elided_obscured_text[] = {
RenderText::kPasswordReplacementChar,
RenderText::kPasswordReplacementChar, kEllipsisUTF16[0], 0};
expected_render_text->SetText(elided_obscured_text);
RenderText* render_text = GetRenderText();
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(
Rect(0, 0, expected_render_text->GetContentWidth(), 100));
render_text->SetObscured(true);
render_text->SetText(ASCIIToUTF16("abcdef"));
EXPECT_EQ(ASCIIToUTF16("abcdef"), render_text->text());
EXPECT_EQ(elided_obscured_text, render_text->GetDisplayText());
}
TEST_F(RenderTextTest, MultilineElide) {
RenderText* render_text = GetRenderText();
base::string16 input_text;
// Aim for 3 lines of text.
for (int i = 0; i < 20; ++i)
input_text.append(ASCIIToUTF16("hello world "));
render_text->SetText(input_text);
// Apply a style that tweaks the layout to make sure elision is calculated
// with these styles. This can expose a behavior in layout where text is
// slightly different width. This must be done after |SetText()|.
render_text->ApplyWeight(Font::Weight::BOLD, Range(1, 20));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, Range(1, 20));
render_text->SetMultiline(true);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetMaxLines(3);
const Size size = render_text->GetStringSize();
// Fit in 3 lines. (If we knew the width of a word, we could
// anticipate word wrap better.)
render_text->SetDisplayRect(Rect((size.width() + 96) / 3, 0));
// Trigger rendering.
render_text->GetStringSize();
EXPECT_EQ(input_text, render_text->GetDisplayText());
base::string16 actual_text;
// Try widening the space gradually, one pixel at a time, trying
// to trigger a failure in layout. There was an issue where, right at
// the edge of a word getting truncated, the estimate would be wrong
// and it would wrap instead.
for (int i = (size.width() - 12) / 3; i < (size.width() + 30) / 3; ++i) {
render_text->SetDisplayRect(Rect(i, 0));
// Trigger rendering.
render_text->GetStringSize();
actual_text = render_text->GetDisplayText();
EXPECT_LT(actual_text.size(), input_text.size());
EXPECT_EQ(actual_text, input_text.substr(0, actual_text.size() - 1) +
base::string16(kEllipsisUTF16));
EXPECT_EQ(3U, render_text->GetNumLines());
}
// Now remove line restriction.
render_text->SetMaxLines(0);
render_text->GetStringSize();
EXPECT_EQ(input_text, render_text->GetDisplayText());
// And put it back.
render_text->SetMaxLines(3);
render_text->GetStringSize();
EXPECT_LT(actual_text.size(), input_text.size());
EXPECT_EQ(actual_text, input_text.substr(0, actual_text.size() - 1) +
base::string16(kEllipsisUTF16));
}
TEST_F(RenderTextTest, MultilineElideWrap) {
RenderText* render_text = GetRenderText();
base::string16 input_text;
for (int i = 0; i < 20; ++i)
input_text.append(ASCIIToUTF16("hello world "));
render_text->SetText(input_text);
render_text->SetMultiline(true);
render_text->SetMaxLines(3);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(Rect(30, 0));
// ELIDE_LONG_WORDS doesn't make sense in multiline, and triggers assertion
// failure.
const WordWrapBehavior wrap_behaviors[] = {
IGNORE_LONG_WORDS, TRUNCATE_LONG_WORDS, WRAP_LONG_WORDS};
for (auto wrap_behavior : wrap_behaviors) {
render_text->SetWordWrapBehavior(wrap_behavior);
render_text->GetStringSize();
base::string16 actual_text = render_text->GetDisplayText();
EXPECT_LE(actual_text.size(), input_text.size());
EXPECT_EQ(actual_text, input_text.substr(0, actual_text.size() - 1) +
base::string16(kEllipsisUTF16));
EXPECT_LE(render_text->GetNumLines(), 3U);
}
}
// TODO(crbug.com/866720): The current implementation of eliding is not aware
// of text styles. The elide text algorithm doesn't take into account the style
// properties when eliding the text. This lead to incorrect text size when the
// styles are applied.
TEST_F(RenderTextTest, DISABLED_MultilineElideWrapWithStyle) {
RenderText* render_text = GetRenderText();
base::string16 input_text;
for (int i = 0; i < 20; ++i)
input_text.append(ASCIIToUTF16("hello world "));
render_text->SetText(input_text);
render_text->ApplyWeight(Font::Weight::BOLD, Range(1, 20));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, Range(1, 20));
render_text->SetMultiline(true);
render_text->SetMaxLines(3);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(Rect(30, 0));
// ELIDE_LONG_WORDS doesn't make sense in multiline, and triggers assertion
// failure.
const WordWrapBehavior wrap_behaviors[] = {
IGNORE_LONG_WORDS, TRUNCATE_LONG_WORDS, WRAP_LONG_WORDS};
for (auto wrap_behavior : wrap_behaviors) {
render_text->SetWordWrapBehavior(wrap_behavior);
render_text->GetStringSize();
base::string16 actual_text = render_text->GetDisplayText();
EXPECT_LE(actual_text.size(), input_text.size());
EXPECT_EQ(actual_text, input_text.substr(0, actual_text.size() - 1) +
base::string16(kEllipsisUTF16));
EXPECT_LE(render_text->GetNumLines(), 3U);
}
}
TEST_F(RenderTextTest, MultilineElideWrapStress) {
RenderText* render_text = GetRenderText();
base::string16 input_text;
for (int i = 0; i < 20; ++i)
input_text.append(ASCIIToUTF16("hello world "));
render_text->SetText(input_text);
render_text->SetMultiline(true);
render_text->SetMaxLines(3);
render_text->SetElideBehavior(ELIDE_TAIL);
// ELIDE_LONG_WORDS doesn't make sense in multiline, and triggers assertion
// failure.
const WordWrapBehavior wrap_behaviors[] = {
IGNORE_LONG_WORDS, TRUNCATE_LONG_WORDS, WRAP_LONG_WORDS};
for (auto wrap_behavior : wrap_behaviors) {
for (int i = 1; i < 60; ++i) {
SCOPED_TRACE(base::StringPrintf(
"MultilineElideWrapStress wrap_behavior = %d, width = %d",
wrap_behavior, i));
render_text->SetDisplayRect(Rect(i, 0));
render_text->SetWordWrapBehavior(wrap_behavior);
render_text->GetStringSize();
base::string16 actual_text = render_text->GetDisplayText();
EXPECT_LE(actual_text.size(), input_text.size());
EXPECT_LE(render_text->GetNumLines(), 3U);
}
}
}
// TODO(crbug.com/866720): The current implementation of eliding is not aware
// of text styles. The elide text algorithm doesn't take into account the style
// properties when eliding the text. This lead to incorrect text size when the
// styles are applied.
TEST_F(RenderTextTest, DISABLED_MultilineElideWrapStressWithStyle) {
RenderText* render_text = GetRenderText();
base::string16 input_text;
for (int i = 0; i < 20; ++i)
input_text.append(ASCIIToUTF16("hello world "));
render_text->SetText(input_text);
render_text->ApplyWeight(Font::Weight::BOLD, Range(1, 20));
render_text->SetMultiline(true);
render_text->SetMaxLines(3);
render_text->SetElideBehavior(ELIDE_TAIL);
// ELIDE_LONG_WORDS doesn't make sense in multiline, and triggers assertion
// failure.
const WordWrapBehavior wrap_behaviors[] = {
IGNORE_LONG_WORDS, TRUNCATE_LONG_WORDS, WRAP_LONG_WORDS};
for (auto wrap_behavior : wrap_behaviors) {
for (int i = 1; i < 60; ++i) {
SCOPED_TRACE(base::StringPrintf(
"MultilineElideWrapStress wrap_behavior = %d, width = %d",
wrap_behavior, i));
render_text->SetDisplayRect(Rect(i, 0));
render_text->SetWordWrapBehavior(wrap_behavior);
render_text->GetStringSize();
base::string16 actual_text = render_text->GetDisplayText();
EXPECT_LE(actual_text.size(), input_text.size());
EXPECT_LE(render_text->GetNumLines(), 3U);
}
}
}
TEST_F(RenderTextTest, MultilineElideRTL) {
RenderText* render_text = GetRenderText();
SetGlyphWidth(5);
base::string16 input_text(UTF8ToUTF16("זהו המסר של ההודעה"));
render_text->SetText(input_text);
render_text->SetCursorEnabled(false);
render_text->SetMultiline(true);
render_text->SetMaxLines(1);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(Rect(45, 0));
render_text->GetStringSize();
EXPECT_EQ(render_text->GetDisplayText(),
input_text.substr(0, 8) + base::string16(kEllipsisUTF16));
EXPECT_EQ(render_text->GetNumLines(), 1U);
}
TEST_F(RenderTextTest, MultilineElideBiDi) {
RenderText* render_text = GetRenderText();
SetGlyphWidth(5);
base::string16 input_text(UTF8ToUTF16("אa\nbcdבגדהefg\nhו"));
render_text->SetText(input_text);
render_text->SetCursorEnabled(false);
render_text->SetMultiline(true);
render_text->SetMaxLines(2);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(Rect(30, 0));
test_api()->EnsureLayout();
EXPECT_EQ(render_text->GetDisplayText(),
UTF8ToUTF16("אa\nbcdבג") + base::string16(kEllipsisUTF16));
EXPECT_EQ(render_text->GetNumLines(), 2U);
}
TEST_F(RenderTextTest, MultilineElideLinebreak) {
RenderText* render_text = GetRenderText();
SetGlyphWidth(5);
base::string16 input_text(ASCIIToUTF16("hello\nworld"));
render_text->SetText(input_text);
render_text->SetCursorEnabled(false);
render_text->SetMultiline(true);
render_text->SetMaxLines(1);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(Rect(100, 0));
render_text->GetStringSize();
EXPECT_EQ(render_text->GetDisplayText(),
input_text.substr(0, 5) + base::string16(kEllipsisUTF16));
EXPECT_EQ(render_text->GetNumLines(), 1U);
}
TEST_F(RenderTextTest, ElidedStyledTextRtl) {
static const char* kInputTexts[] = {
"http://ar.wikipedia.com/فحص",
"testحص,",
"حص,test",
"…",
"…test",
"test…",
"حص,test…",
"ٱ",
"\uFEFF", // BOM: Byte Order Marker
"…\u200F", // Right to left marker.
};
for (const auto* raw_text : kInputTexts) {
SCOPED_TRACE(
base::StringPrintf("ElidedStyledTextRtl text = %s", raw_text));
base::string16 input_text(UTF8ToUTF16(raw_text));
RenderText* render_text = GetRenderText();
render_text->SetText(input_text);
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetStyle(TEXT_STYLE_STRIKE, true);
render_text->SetDirectionalityMode(DIRECTIONALITY_FORCE_LTR);
constexpr int kMaxContentWidth = 2000;
for (int i = 0; i < kMaxContentWidth; ++i) {
SCOPED_TRACE(base::StringPrintf("ElidedStyledTextRtl width = %d", i));
render_text->SetDisplayRect(Rect(i, 20));
render_text->GetStringSize();
base::string16 display_text = render_text->GetDisplayText();
EXPECT_LE(display_text.size(), input_text.size());
// Every size of content width was tried.
if (display_text == input_text)
break;
}
}
}
TEST_F(RenderTextTest, ElidedEmail) {
RenderText* render_text = GetRenderText();
render_text->SetText(ASCIIToUTF16("test@example.com"));
const Size size = render_text->GetStringSize();
const base::string16 long_email =
ASCIIToUTF16("longemailaddresstest@example.com");
render_text->SetText(long_email);
render_text->SetElideBehavior(ELIDE_EMAIL);
render_text->SetDisplayRect(Rect(size));
EXPECT_GE(size.width(), render_text->GetStringSize().width());
EXPECT_GT(long_email.size(), render_text->GetDisplayText().size());
}
TEST_F(RenderTextTest, TruncatedText) {
struct {
const wchar_t* text;
const wchar_t* display_text;
} cases[] = {
// Strings shorter than the truncation length should be laid out in full.
{L"", L""},
{L" . ", L" . "}, // a wide kWeak
{L"abc", L"abc"}, // a wide kLtr
{L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2"}, // a wide kRtl
{L"a\u05d0\u05d1", L"a\u05d0\u05d1"}, // a wide kLtrRtl
{L"a\u05d1b", L"a\u05d1b"}, // a wide kLtrRtlLtr
{L"\u05d0\u05d1a", L"\u05d0\u05d1a"}, // a wide kRtlLtr
{L"\u05d0a\u05d1", L"\u05d0a\u05d1"}, // a wide kRtlLtrRtl
{L"01234", L"01234"},
// Long strings should be truncated with an ellipsis appended at the end.
{L"012345", L"0123\u2026"},
{L"012 . ", L"012 \u2026"},
{L"012abc", L"012a\u2026"},
{L"012a\u05d0\u05d1", L"012a\u2026"},
{L"012a\u05d1b", L"012a\u2026"},
{L"012\u05d0\u05d1\u05d2", L"012\u05d0\u2026"},
{L"012\u05d0\u05d1a", L"012\u05d0\u2026"},
{L"012\u05d0a\u05d1", L"012\u05d0\u2026"},
// Surrogate pairs should be truncated reasonably enough.
{L"0123\u0915\u093f", L"0123\u2026"},
{L"\u05e9\u05bc\u05c1\u05b8", L"\u05e9\u05bc\u05c1\u05b8"},
{L"0\u05e9\u05bc\u05c1\u05b8", L"0\u05e9\u05bc\u05c1\u05b8"},
{L"01\u05e9\u05bc\u05c1\u05b8", L"01\u2026"},
{L"012\u05e9\u05bc\u05c1\u05b8", L"012\u2026"},
// Codepoint U+0001D11E is using 2x 16-bit characters.
{L"0\U0001D11Eaaa", L"0\U0001D11Ea\u2026"},
{L"01\U0001D11Eaaa", L"01\U0001D11E\u2026"},
{L"012\U0001D11Eaaa", L"012\u2026"},
{L"0123\U0001D11Eaaa", L"0123\u2026"},
{L"01234\U0001D11Eaaa", L"0123\u2026"},
// Combining codepoint should stay together.
// (Letter 'e' U+0065 and acute accent U+0301).
{L"0e\u0301aaa", L"0e\u0301a\u2026"},
{L"01e\u0301aaa", L"01e\u0301\u2026"},
{L"012e\u0301aaa", L"012\u2026"},
// Emoji 'keycap letter 6'.
{L"\u0036\uFE0F\u20E3aaa", L"\u0036\uFE0F\u20E3a\u2026"},
{L"0\u0036\uFE0F\u20E3aaa", L"0\u0036\uFE0F\u20E3\u2026"},
{L"01\u0036\uFE0F\u20E3aaa", L"01\u2026"},
// Emoji 'pilot'.
{L"\U0001F468\u200D\u2708\uFE0F", L"\U0001F468\u200D\u2708\uFE0F"},
{L"\U0001F468\u200D\u2708\uFE0F0", L"\u2026"},
{L"0\U0001F468\u200D\u2708\uFE0F", L"0\u2026"},
};
RenderText* render_text = GetRenderText();
render_text->set_truncate_length(5);
for (size_t i = 0; i < base::size(cases); i++) {
render_text->SetText(WideToUTF16(cases[i].text));
EXPECT_EQ(WideToUTF16(cases[i].text), render_text->text());
EXPECT_EQ(WideToUTF16(cases[i].display_text), render_text->GetDisplayText())
<< "For case " << i << ": " << cases[i].text;
}
}
TEST_F(RenderTextTest, TruncatedObscuredText) {
RenderText* render_text = GetRenderText();
render_text->set_truncate_length(3);
render_text->SetObscured(true);
render_text->SetText(ASCIIToUTF16("abcdef"));
EXPECT_EQ(ASCIIToUTF16("abcdef"), render_text->text());
EXPECT_EQ(GetObscuredString(3, 2, kEllipsisUTF16[0]),
render_text->GetDisplayText());
}
TEST_F(RenderTextTest, TruncatedObscuredTextWithGraphemes) {