blob: 9141e01b652e4fbaab31be6aff10e05807e388f2 [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/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.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_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_MACOSX)
#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";
// 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());
}
// 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:
struct TextLog {
TextLog() : glyph_count(0u), color(SK_ColorTRANSPARENT) {}
PointF origin;
size_t glyph_count;
std::vector<uint16_t> glyphs;
SkColor color;
};
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:
void DrawPosText(const SkPoint* pos,
const uint16_t* glyphs,
size_t glyph_count) override {
TextLog log_entry;
log_entry.glyph_count = glyph_count;
if (glyph_count > 0) {
log_entry.origin =
PointF(SkScalarToFloat(pos[0].x()), SkScalarToFloat(pos[0].y()));
for (size_t i = 1U; i < glyph_count; ++i) {
log_entry.origin.SetToMin(
PointF(SkScalarToFloat(pos[i].x()), SkScalarToFloat(pos[i].y())));
}
log_entry.glyphs = std::vector<uint16_t>(glyphs, glyphs + glyph_count);
}
log_entry.color =
test::RenderTextTestApi::GetRendererPaint(this).getColor();
text_log_.push_back(log_entry);
internal::SkiaTextRenderer::DrawPosText(pos, glyphs, glyph_count);
}
std::vector<TextLog> text_log_;
DISALLOW_COPY_AND_ASSIGN(TestSkiaTextRenderer);
};
// 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;
}
}
}
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(Range selection = {}) {
test_api_->DrawVisualText(renderer(), selection);
}
const internal::TextRunList* GetHarfBuzzRunList() const {
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() const {
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));
test_api()->EnsureLayout();
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);
}
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());
}
// Do not use this function to ensure layout. This is only used to run a
// subset of the EnsureLayout functionality and check intermediate state.
void EnsureLayoutRunList() { GetRenderText()->EnsureLayoutRunList(); }
Canvas* canvas() { return &canvas_; }
TestSkiaTextRenderer* renderer() { return &renderer_; }
test::RenderTextTestApi* test_api() { return test_api_.get(); }
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_;
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(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(WideToUTF16(L"\u0065\u0301"));
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, gfx::Range(1, 2));
render_text->ApplyStyle(TEXT_STYLE_UNDERLINE, true, gfx::Range(0, 1));
DrawVisualText();
// Ensures that the whole grapheme is drawn with the same style.
std::vector<TestSkiaTextRenderer::TextLog> text_log;
renderer()->GetTextLogAndReset(&text_log);
EXPECT_EQ(1u, text_log.size());
}
TEST_F(RenderTextTest, ApplyStyleMultipleGraphemes) {
RenderText* render_text = GetRenderText();
render_text->SetText(WideToUTF16(L"x\u0065\u0301x"));
// Apply the style in the middle of a grapheme.
gfx::Range range(2, 3);
render_text->ApplyStyle(TEXT_STYLE_ITALIC, true, range);
DrawVisualText();
EXPECT_TRUE(test_api()->styles()[TEXT_STYLE_ITALIC].EqualsForTesting(
{{0, false}, {2, true}, {3, false}}));
// Ensures that the style of the grapheme is the style at its first character.
std::vector<TestSkiaTextRenderer::TextLog> text_log;
renderer()->GetTextLogAndReset(&text_log);
ASSERT_EQ(2u, text_log.size());
EXPECT_EQ(2U, text_log[0].glyph_count);
EXPECT_EQ(1U, text_log[1].glyph_count);
}
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(WideToUTF16(L"\u0628"));
DrawVisualText();
std::vector<TestSkiaTextRenderer::TextLog> text_log;
renderer()->GetTextLogAndReset(&text_log);
ASSERT_EQ(1u, text_log.size());
ASSERT_EQ(1u, text_log[0].glyph_count);
uint16_t isolated_first_glyph = text_log[0].glyphs[0];
// Render a pair of glyphs (initial form and final form).
render_text->SetText(WideToUTF16(L"\u0628\u0645"));
DrawVisualText();
renderer()->GetTextLogAndReset(&text_log);
ASSERT_EQ(1u, text_log.size());
ASSERT_LE(2u, text_log[0].glyph_count);
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));
DrawVisualText();
renderer()->GetTextLogAndReset(&text_log);
ASSERT_EQ(2u, text_log.size());
ASSERT_LE(1u, text_log[0].glyph_count);
ASSERT_EQ(1u, text_log[1].glyph_count);
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(UTF8ToUTF16("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(UTF8ToUTF16("efg"));
EXPECT_EQ(render_text->GetDisplayText(), UTF8ToUTF16("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));
}
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 = UTF8ToUTF16("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 = UTF8ToUTF16("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, RevealObscuredText) {
const base::string16 seuss = UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(WideToUTF16(L"\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(WideToUTF16(L"\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.
base::i18n::UTF16CharIterator iter(&render_text->text());
while (!iter.end()) {
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]);
}
iter.Advance();
}
}
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;
};
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->SetText(WideToUTF16(param.text));
test_api()->EnsureLayout();
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]"},
{"joiners", L"1\u200C2\u200C3\u200C4", "[0->6]"},
{"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
};
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]"},
};
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);
TEST_F(RenderTextTest, ElidedText) {
// TODO(skanuj) : Add more test cases for following
// - RenderText styles.
// - Cross interaction of truncate, elide and obscure.
// - ElideText tests from text_elider.cc.
struct {
const wchar_t* text;
const wchar_t* display_text;
const bool elision_expected;
} cases[] = {
// Strings shorter than the elision width should be laid out in full.
{L"", L"", false},
{L"M", L"", false},
{L" . ", L" . ", false}, // a wide kWeak
{L"abc", L"abc", false}, // a wide kLtr
{L"\u05d0\u05d1\u05d2", L"\u05d0\u05d1\u05d2", false}, // a wide kRtl
{L"a\u05d0\u05d1", L"a\u05d0\u05d1", false}, // a wide kLtrRtl
{L"a\u05d1b", L"a\u05d1b", false}, // a wide kLtrRtlLtr
{L"\u05d0\u05d1a", L"\u05d0\u05d1a", false}, // a wide kRtlLtr
{L"\u05d0a\u05d1", L"\u05d0a\u05d1", false}, // a wide kRtlLtrRtl
// Strings as long as the elision width should be laid out in full.
{L"012ab", L"012ab", false},
// Long strings should be elided with an ellipsis appended at the end.
{L"012abc", L"012a\u2026", true},
{L"012ab\u05d0\u05d1", L"012a\u2026", true},
{L"012a\u05d1b", L"012a\u2026", true},
// No RLM marker added as digits (012) have weak directionality.
{L"01\u05d0\u05d1\u05d2", L"01\u05d0\u05d1\u2026", true},
// RLM marker added as "ab" have strong LTR directionality.
{L"ab\u05d0\u05d1\u05d2", L"ab\u05d0\u05d1\u2026\u200f", true},
// 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.
// Windows requires wide strings for \Unnnnnnnn universal character names.
{L"0123\U0001D11E\U0001D122", L"0123\U0001D11E\u2026", true},
// 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.
{L"0123\u0915\u093f\u0915\u0942", L"0123\u0915\u093f\u2026", true},
// 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.
{L"0\u05e9\u05bc\u05c1\u05b8", L"0\u05e9\u05bc\u05c1\u05b8", false},
{L"0\u05e9\u05bc\u05c1\u05b8", L"0\u2026\u200E", true},
{L"01\u05e9\u05bc\u05c1\u05b8", L"01\u2026\u200E", true},
{L"012\u05e9\u05bc\u05c1\u05b8", L"012\u2026\u200E", true},
// 𝄞 (U+1D11E, MUSICAL SYMBOL G CLEF) should be fully elided.
// Windows requires wide strings for \Unnnnnnnn universal character names.
{L"012\U0001D11E", L"012\u2026", true},
};
auto expected_render_text = std::make_unique<RenderTextHarfBuzz>();
expected_render_text->SetFontList(FontList("serif, Sans serif, 12px"));
expected_render_text->SetDisplayRect(Rect(0, 0, 9999, 100));
RenderText* render_text = GetRenderText();
render_text->SetFontList(FontList("serif, Sans serif, 12px"));
render_text->SetElideBehavior(ELIDE_TAIL);
for (size_t i = 0; i < base::size(cases); i++) {
SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "] '%ls'", i,
cases[i].text));
// Compute expected width
expected_render_text->SetText(WideToUTF16(cases[i].display_text));
int expected_width = expected_render_text->GetContentWidth();
base::string16 input = WideToUTF16(cases[i].text);
// Extend the input text to ensure that it is wider than the display_text,
// and so it will get elided.
if (cases[i].elision_expected)
input.append(UTF8ToUTF16(" MMMMMMMMMMM"));
render_text->SetText(input);
render_text->SetDisplayRect(Rect(0, 0, expected_width, 100));
EXPECT_EQ(input, render_text->text());
EXPECT_EQ(WideToUTF16(cases[i].display_text),
render_text->GetDisplayText());
expected_render_text->SetText(base::string16());
}
}
TEST_F(RenderTextTest, ElidedText_NoTrimWhitespace) {
const int kGlyphWidth = 10;
RenderText* render_text = GetRenderText();
gfx::test::RenderTextTestApi render_text_test_api(render_text);
render_text_test_api.SetGlyphWidth(kGlyphWidth);
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 wchar_t kInputString[] = L" foo";
const base::string16 input = WideToUTF16(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->SetFontList(FontList("serif, Sans serif, 12px"));
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->SetFontList(FontList("serif, Sans serif, 12px"));
render_text->SetElideBehavior(ELIDE_TAIL);
render_text->SetDisplayRect(
Rect(0, 0, expected_render_text->GetContentWidth(), 100));
render_text->SetObscured(true);
render_text->SetText(UTF8ToUTF16("abcdef"));
EXPECT_EQ(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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(UTF8ToUTF16("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));
render_text->GetStringSize();
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(UTF8ToUTF16("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;
}
}
} // namespace gfx
TEST_F(RenderTextTest, ElidedEmail) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("test@example.com"));
const Size size = render_text->GetStringSize();
const base::string16 long_email =
UTF8ToUTF16("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"0\u05e9\u05bc\u05c1\u05b8", L"0\u05e9\u05bc\u05c1\u05b8"},
{L"01\u05e9\u05bc\u05c1\u05b8", L"01\u05e9\u05bc\u2026"},
{L"012\u05e9\u05bc\u05c1\u05b8", L"012\u05e9\u2026"},
{L"0123\u05e9\u05bc\u05c1\u05b8", L"0123\u2026"},
{L"01234\u05e9\u05bc\u05c1\u05b8", L"0123\u2026"},
// Windows requires wide strings for \Unnnnnnnn universal character names.
{L"0123\U0001D11E", L"0123\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(UTF8ToUTF16("abcdef"));
EXPECT_EQ(UTF8ToUTF16("abcdef"), render_text->text());
EXPECT_EQ(GetObscuredString(3, 2, kEllipsisUTF16[0]),
render_text->GetDisplayText());
}
TEST_F(RenderTextTest, TruncatedCursorMovementLTR) {
RenderText* render_text = GetRenderText();
render_text->set_truncate_length(2);
render_text->SetText(UTF8ToUTF16("abcd"));
EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model());
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(SelectionModel(4, CURSOR_FORWARD), render_text->selection_model());
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model());
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
// The cursor hops over the ellipsis and elided text to the line end.
expected.push_back(SelectionModel(4, CURSOR_BACKWARD));
expected.push_back(SelectionModel(4, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_RIGHT);
expected.clear();
expected.push_back(SelectionModel(4, CURSOR_FORWARD));
// The cursor hops over the elided text to preceeding text.
expected.push_back(SelectionModel(1, CURSOR_FORWARD));
expected.push_back(SelectionModel(0, CURSOR_FORWARD));
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_LEFT);
}
TEST_F(RenderTextTest, TruncatedCursorMovementRTL) {
RenderText* render_text = GetRenderText();
render_text->set_truncate_length(2);
render_text->SetText(UTF8ToUTF16("\u05d0\u05d1\u05d2\u05d3"));
EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model());
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(SelectionModel(4, CURSOR_FORWARD), render_text->selection_model());
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(SelectionModel(0, CURSOR_BACKWARD), render_text->selection_model());
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
// The cursor hops over the ellipsis and elided text to the line end.
expected.push_back(SelectionModel(4, CURSOR_BACKWARD));
expected.push_back(SelectionModel(4, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_LEFT);
expected.clear();
expected.push_back(SelectionModel(4, CURSOR_FORWARD));
// The cursor hops over the elided text to preceeding text.
expected.push_back(SelectionModel(1, CURSOR_FORWARD));
expected.push_back(SelectionModel(0, CURSOR_FORWARD));
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_RIGHT);
}
TEST_F(RenderTextTest, MoveCursor_Character) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("123 456 789"));
std::vector<Range> expected;
// SELECTION_NONE.
render_text->SelectRange(Range(6));
// Move right twice.
expected.push_back(Range(7));
expected.push_back(Range(8));
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE, &expected);
// Move left twice.
expected.push_back(Range(7));
expected.push_back(Range(6));
RunMoveCursorTestAndClearExpectations(render_text, CHARACTER_BREAK,
CURSOR_LEFT, SELECTION_NONE, &expected);
// SELECTION_CARET.
render_text->SelectRange(Range(6));
expected.push_back(Range(6, 7));
// Move right.
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_CARET, &expected);
// Move left twice.
expected.push_back(Range(6));
expected.push_back(Range(6, 5));
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_LEFT, SELECTION_CARET, &expected);
// SELECTION_RETAIN.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 7));
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_RETAIN, &expected);
// Move left twice.
expected.push_back(Range(6));
expected.push_back(Range(6, 5));
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_LEFT, SELECTION_RETAIN, &expected);
// SELECTION_EXTEND.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 7));
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_EXTEND, &expected);
// Move left twice.
expected.push_back(Range(7, 6));
expected.push_back(Range(7, 5));
RunMoveCursorTestAndClearExpectations(
render_text, CHARACTER_BREAK, CURSOR_LEFT, SELECTION_EXTEND, &expected);
}
TEST_F(RenderTextTest, MoveCursor_Word) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("123 456 789"));
std::vector<Range> expected;
// SELECTION_NONE.
render_text->SelectRange(Range(6));
// Move left twice.
expected.push_back(Range(4));
expected.push_back(Range(0));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_NONE, &expected);
// Move right twice.
#if defined(OS_WIN) // Move word right includes space/punctuation.
expected.push_back(Range(4));
expected.push_back(Range(8));
#else // Non-Windows: move word right does NOT include space/punctuation.
expected.push_back(Range(3));
expected.push_back(Range(7));
#endif
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_NONE, &expected);
// SELECTION_CARET.
render_text->SelectRange(Range(6));
// Move left.
expected.push_back(Range(6, 4));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_CARET, &expected);
// Move right twice.
expected.push_back(Range(6));
#if defined(OS_WIN) // Select word right includes space/punctuation.
expected.push_back(Range(6, 8));
#else // Non-Windows: select word right does NOT include space/punctuation.
expected.push_back(Range(6, 7));
#endif
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// Move left.
expected.push_back(Range(6));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_CARET, &expected);
// SELECTION_RETAIN.
render_text->SelectRange(Range(6));
// Move left.
expected.push_back(Range(6, 4));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_RETAIN, &expected);
// Move right twice.
#if defined(OS_WIN) // Select word right includes space/punctuation.
expected.push_back(Range(6, 8));
#else // Non-Windows: select word right does NOT include space/punctuation.
expected.push_back(Range(6, 7));
#endif
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// Move left.
expected.push_back(Range(6, 8));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_RETAIN, &expected);
// SELECTION_EXTEND.
render_text->SelectRange(Range(6));
// Move left.
expected.push_back(Range(6, 4));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_EXTEND, &expected);
// Move right twice.
#if defined(OS_WIN) // Select word right includes space/punctuation.
expected.push_back(Range(4, 8));
#else // Non-Windows: select word right does NOT include space/punctuation.
expected.push_back(Range(4, 7));
#endif
expected.push_back(Range(4, 11));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
// Move left.
expected.push_back(Range(4, 8));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_EXTEND, &expected);
}
TEST_F(RenderTextTest, MoveCursor_Word_RTL) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("אבג דהו זחט"));
std::vector<Range> expected;
// SELECTION_NONE.
render_text->SelectRange(Range(6));
// Move right twice.
expected.push_back(Range(4));
expected.push_back(Range(0));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_NONE, &expected);
// Move left twice.
#if defined(OS_WIN) // Move word left includes space/punctuation.
expected.push_back(Range(4));
expected.push_back(Range(8));
#else // Non-Windows: move word left does NOT include space/punctuation.
expected.push_back(Range(3));
expected.push_back(Range(7));
#endif
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_NONE, &expected);
// SELECTION_CARET.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 4));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// Move left twice.
expected.push_back(Range(6));
#if defined(OS_WIN) // Select word left includes space/punctuation.
expected.push_back(Range(6, 8));
#else // Non-Windows: select word left does NOT include space/punctuation.
expected.push_back(Range(6, 7));
#endif
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_CARET, &expected);
// Move right.
expected.push_back(Range(6));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// SELECTION_RETAIN.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 4));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// Move left twice.
#if defined(OS_WIN) // Select word left includes space/punctuation.
expected.push_back(Range(6, 8));
#else // Non-Windows: select word left does NOT include space/punctuation.
expected.push_back(Range(6, 7));
#endif
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_RETAIN, &expected);
// Move right.
expected.push_back(Range(6, 8));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// SELECTION_EXTEND.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 4));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
// Move left twice.
#if defined(OS_WIN) // Select word left includes space/punctuation.
expected.push_back(Range(4, 8));
#else // Non-Windows: select word left does NOT include space/punctuation.
expected.push_back(Range(4, 7));
#endif
expected.push_back(Range(4, 11));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_LEFT,
SELECTION_EXTEND, &expected);
// Move right.
expected.push_back(Range(4, 8));
RunMoveCursorTestAndClearExpectations(render_text, WORD_BREAK, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
}
TEST_F(RenderTextTest, MoveCursor_Line) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("123 456 789"));
std::vector<Range> expected;
for (auto break_type : {LINE_BREAK, FIELD_BREAK}) {
// SELECTION_NONE.
render_text->SelectRange(Range(6));
// Move right twice.
expected.push_back(Range(11));
expected.push_back(Range(11));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_NONE, &expected);
// Move left twice.
expected.push_back(Range(0));
expected.push_back(Range(0));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_LEFT,
SELECTION_NONE, &expected);
// SELECTION_CARET.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// Move left twice.
expected.push_back(Range(6));
expected.push_back(Range(6, 0));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_LEFT,
SELECTION_CARET, &expected);
// Move right.
expected.push_back(Range(6));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// SELECTION_RETAIN.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// Move left twice.
expected.push_back(Range(6, 0));
expected.push_back(Range(6, 0));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_LEFT,
SELECTION_RETAIN, &expected);
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// SELECTION_EXTEND.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
// Move left twice.
expected.push_back(Range(11, 0));
expected.push_back(Range(11, 0));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_LEFT,
SELECTION_EXTEND, &expected);
// Move right.
expected.push_back(Range(0, 11));
RunMoveCursorTestAndClearExpectations(render_text, break_type, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
}
}
TEST_F(RenderTextTest, MoveCursor_UpDown) {
SetGlyphWidth(5);
RenderText* render_text = GetRenderText();
render_text->SetDisplayRect(Rect(45, 1000));
render_text->SetMultiline(true);
std::vector<size_t> expected_lines;
std::vector<Range> expected_range;
for (auto text :
{ASCIIToUTF16("123 456 123 456 "), UTF8ToUTF16("אבג דהו זחט זחט ")}) {
render_text->SetText(text);
EXPECT_EQ(2U, render_text->GetNumLines());
// SELECTION_NONE.
render_text->SelectRange(Range(0));
ResetCursorX();
// Move down twice.
expected_lines.push_back(1);
expected_lines.push_back(1);
RunMoveCursorTestAndClearExpectations(render_text, CHARACTER_BREAK,
CURSOR_DOWN, SELECTION_NONE,
&expected_lines);
// Move up twice.
expected_lines.push_back(0);
expected_lines.push_back(0);
RunMoveCursorTestAndClearExpectations(render_text, CHARACTER_BREAK,
CURSOR_UP, SELECTION_NONE,
&expected_lines);
// SELECTION_CARET.
render_text->SelectRange(Range(0));
ResetCursorX();
// Move down twice.
expected_range.push_back(Range(0, 8));
expected_range.push_back(Range(0, 16));
RunMoveCursorTestAndClearExpectations(render_text, CHARACTER_BREAK,
CURSOR_DOWN, SELECTION_CARET,
&expected_range);