blob: c8957cfb53725d9925a5f693aec89fbefee2f0cf [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/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/scoped_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_utils.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#include "ui/gfx/platform_font_win.h"
#endif
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
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,
};
// 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();
}
// 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<RenderText::FontSpan>& font_spans,
int index,
int font_index,
Font::Weight weight,
int style_mask) {
const auto iter =
std::find_if(font_spans.begin(), font_spans.end(),
[font_index](const RenderText::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;
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.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()
: scoped_task_environment_(
base::test::ScopedTaskEnvironment::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() { test_api_->DrawVisualText(renderer()); }
const internal::TextRunList* GetHarfBuzzRunList() const {
return test_api_->GetHarfBuzzRunList();
}
// 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() const {
std::vector<base::string16> runs_as_text;
const std::vector<RenderText::FontSpan> spans =
render_text_->GetFontSpansForTesting();
for (const auto& span : spans) {
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_.reset(new test::RenderTextTestApi(GetRenderText()));
}
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.SetFontAndRenderParams(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;
}
// 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::ScopedTaskEnvironment scoped_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 shouldn't be changed mid-grapheme.
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}, {1, true}, {6, false}}));
}
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.
EXPECT_EQ(0U, test_api()->TextIndexToDisplayIndex(0U));
EXPECT_EQ(1U, 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(),
static_cast<int>(render_text->GetCursorSpan({0, 1}).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, 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.
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, 0xDC00), render_text->GetDisplayText());
render_text->RenderText::SetObscuredRevealIndex(1);
EXPECT_EQ(GetObscuredString(5, 1, 0xD800), 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());
// 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());
}
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, 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, 0x2026, 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());
const base::char16 kEllipsisUTF16[] = {0x2026, 0};
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->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));
const base::char16 kEllipsisUTF16[] = {0x2026, 0};
base::string16 actual_text;
// 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();
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);
// TODO(crbug.com/866720): with the line about ApplyWeight() uncommented, when
// |i| (the width of display rect) is 23, there would be actually 4 lines
// rendered, more than the max lines setting. It could be that ellipsis is
// wrapped to the 4th line due to different word segmentation from the
// original text.
// render_text->ApplyWeight(Font::Weight::BOLD, Range(1, 20));
render_text->SetMultiline(true);
render_text->SetMaxLines(3);
render_text->SetElideBehavior(ELIDE_TAIL);
base::string16 actual_text;
// 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();
actual_text = render_text->GetDisplayText();
EXPECT_LE(actual_text.size(), input_text.size());
EXPECT_LE(render_text->GetNumLines(), 3U);
}
}
}
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, 0x2026), 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;
// SELECTION_NONE.
render_text->SelectRange(Range(6));
// Move right twice.
expected.push_back(Range(11));
expected.push_back(Range(11));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_NONE, &expected);
// Move left twice.
expected.push_back(Range(0));
expected.push_back(Range(0));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_LEFT,
SELECTION_NONE, &expected);
// SELECTION_CARET.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// Move left twice.
expected.push_back(Range(6));
expected.push_back(Range(6, 0));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_LEFT,
SELECTION_CARET, &expected);
// Move right.
expected.push_back(Range(6));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_CARET, &expected);
// SELECTION_RETAIN.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// Move left twice.
expected.push_back(Range(6, 0));
expected.push_back(Range(6, 0));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_LEFT,
SELECTION_RETAIN, &expected);
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_RETAIN, &expected);
// SELECTION_EXTEND.
render_text->SelectRange(Range(6));
// Move right.
expected.push_back(Range(6, 11));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
// Move left twice.
expected.push_back(Range(11, 0));
expected.push_back(Range(11, 0));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_LEFT,
SELECTION_EXTEND, &expected);
// Move right.
expected.push_back(Range(0, 11));
RunMoveCursorTestAndClearExpectations(render_text, LINE_BREAK, CURSOR_RIGHT,
SELECTION_EXTEND, &expected);
}
TEST_F(RenderTextTest, GetDisplayTextDirection) {
struct {
const char* text;
const base::i18n::TextDirection text_direction;
} cases[] = {
// Blank strings and those with no/weak directionality default to LTR.
{"", base::i18n::LEFT_TO_RIGHT},
{kWeak, base::i18n::LEFT_TO_RIGHT},
// Strings that begin with strong LTR characters.
{kLtr, base::i18n::LEFT_TO_RIGHT},
{kLtrRtl, base::i18n::LEFT_TO_RIGHT},
{kLtrRtlLtr, base::i18n::LEFT_TO_RIGHT},
// Strings that begin with strong RTL characters.
{kRtl, base::i18n::RIGHT_TO_LEFT},
{kRtlLtr, base::i18n::RIGHT_TO_LEFT},
{kRtlLtrRtl, base::i18n::RIGHT_TO_LEFT},
};
RenderText* render_text = GetRenderText();
const bool was_rtl = base::i18n::IsRTL();
for (size_t i = 0; i < 2; ++i) {
// Toggle the application default text direction (to try each direction).
SetRTL(!base::i18n::IsRTL());
const base::i18n::TextDirection ui_direction = base::i18n::IsRTL() ?
base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT;
// Ensure that directionality modes yield the correct text directions.
for (size_t j = 0; j < base::size(cases); j++) {
render_text->SetText(UTF8ToUTF16(cases[j].text));
render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_TEXT);
EXPECT_EQ(render_text->GetDisplayTextDirection(),cases[j].text_direction);
render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_UI);
EXPECT_EQ(render_text->GetDisplayTextDirection(), ui_direction);
render_text->SetDirectionalityMode(DIRECTIONALITY_FORCE_LTR);
EXPECT_EQ(render_text->GetDisplayTextDirection(),
base::i18n::LEFT_TO_RIGHT);
render_text->SetDirectionalityMode(DIRECTIONALITY_FORCE_RTL);
EXPECT_EQ(render_text->GetDisplayTextDirection(),
base::i18n::RIGHT_TO_LEFT);
render_text->SetDirectionalityMode(DIRECTIONALITY_AS_URL);
EXPECT_EQ(render_text->GetDisplayTextDirection(),
base::i18n::LEFT_TO_RIGHT);
}
}
EXPECT_EQ(was_rtl, base::i18n::IsRTL());
// Ensure that text changes update the direction for DIRECTIONALITY_FROM_TEXT.
render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_TEXT);
render_text->SetText(UTF8ToUTF16(kLtr));
EXPECT_EQ(render_text->GetDisplayTextDirection(), base::i18n::LEFT_TO_RIGHT);
render_text->SetText(UTF8ToUTF16(kRtl));
EXPECT_EQ(render_text->GetDisplayTextDirection(), base::i18n::RIGHT_TO_LEFT);
}
TEST_F(RenderTextTest, MoveCursorLeftRightInLtr) {
RenderText* render_text = GetRenderText();
// Pure LTR.
render_text->SetText(UTF8ToUTF16("abc"));
// |expected| saves the expected SelectionModel when moving cursor from left
// to right.
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
expected.push_back(SelectionModel(2, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_RIGHT);
expected.clear();
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
expected.push_back(SelectionModel(2, CURSOR_FORWARD));
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, MoveCursorLeftRightInLtrRtl) {
RenderText* render_text = GetRenderText();
// LTR-RTL
render_text->SetText(UTF8ToUTF16("abc\u05d0\u05d1\u05d2"));
// The last one is the expected END position.
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
expected.push_back(SelectionModel(2, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_BACKWARD));
expected.push_back(SelectionModel(5, CURSOR_FORWARD));
expected.push_back(SelectionModel(4, CURSOR_FORWARD));
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
expected.push_back(SelectionModel(6, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_RIGHT);
expected.clear();
expected.push_back(SelectionModel(6, CURSOR_FORWARD));
expected.push_back(SelectionModel(4, CURSOR_BACKWARD));
expected.push_back(SelectionModel(5, CURSOR_BACKWARD));
expected.push_back(SelectionModel(6, CURSOR_BACKWARD));
expected.push_back(SelectionModel(2, CURSOR_FORWARD));
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, MoveCursorLeftRightInLtrRtlLtr) {
RenderText* render_text = GetRenderText();
// LTR-RTL-LTR.
render_text->SetText(UTF8ToUTF16("a\u05d1b"));
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_FORWARD));
expected.push_back(SelectionModel(3, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_RIGHT);
expected.clear();
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
expected.push_back(SelectionModel(2, CURSOR_FORWARD));
expected.push_back(SelectionModel(2, CURSOR_BACKWARD));
expected.push_back(SelectionModel(0, CURSOR_FORWARD));
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_LEFT);
}
TEST_F(RenderTextTest, MoveCursorLeftRightInRtl) {
RenderText* render_text = GetRenderText();
// Pure RTL.
render_text->SetText(UTF8ToUTF16("\u05d0\u05d1\u05d2"));
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
expected.push_back(SelectionModel(2, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_LEFT);
expected.clear();
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
expected.push_back(SelectionModel(2, CURSOR_FORWARD));
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, MoveCursorLeftRightInRtlLtr) {
RenderText* render_text = GetRenderText();
// RTL-LTR
render_text->SetText(UTF8ToUTF16("\u05d0\u05d1\u05d2abc"));
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
expected.push_back(SelectionModel(2, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_BACKWARD));
expected.push_back(SelectionModel(5, CURSOR_FORWARD));
expected.push_back(SelectionModel(4, CURSOR_FORWARD));
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
expected.push_back(SelectionModel(6, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_LEFT);
expected.clear();
expected.push_back(SelectionModel(6, CURSOR_FORWARD));
expected.push_back(SelectionModel(4, CURSOR_BACKWARD));
expected.push_back(SelectionModel(5, CURSOR_BACKWARD));
expected.push_back(SelectionModel(6, CURSOR_BACKWARD));
expected.push_back(SelectionModel(2, CURSOR_FORWARD));
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, MoveCursorLeftRightInRtlLtrRtl) {
RenderText* render_text = GetRenderText();
// RTL-LTR-RTL.
render_text->SetText(UTF8ToUTF16("\u05d0a\u05d1"));
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
std::vector<SelectionModel> expected;
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_BACKWARD));
expected.push_back(SelectionModel(1, CURSOR_FORWARD));
expected.push_back(SelectionModel(3, CURSOR_BACKWARD));
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_LEFT);
expected.clear();
expected.push_back(SelectionModel(3, CURSOR_FORWARD));
expected.push_back(SelectionModel(2, CURSOR_FORWARD));
expected.push_back(SelectionModel(2, CURSOR_BACKWARD));
expected.push_back(SelectionModel(0, CURSOR_FORWARD));
expected.push_back(SelectionModel(0, CURSOR_BACKWARD));
RunMoveCursorLeftRightTest(render_text, expected, CURSOR_RIGHT);
}
TEST_F(RenderTextTest, MoveCursorLeftRight_ComplexScript) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("\u0915\u093f\u0915\u094d\u0915"));
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(2U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(4U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(5U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(5U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(4U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(2U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
}
TEST_F(RenderTextTest, MoveCursorLeftRight_MeiryoUILigatures) {
RenderText* render_text = GetRenderText();
// Meiryo UI uses single-glyph ligatures for 'ff' and 'ffi', but each letter
// (code point) has unique bounds, so mid-glyph cursoring should be possible.
render_text->SetFontList(FontList("Meiryo UI, 12px"));
render_text->SetText(UTF8ToUTF16("ff ffi"));
render_text->SetDisplayRect(gfx::Rect(100, 100));
test_api()->EnsureLayout();
EXPECT_EQ(0U, render_text->cursor_position());
gfx::Rect last_selection_bounds = GetSelectionBoundsUnion();
for (size_t i = 0; i < render_text->text().length(); ++i) {
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_RETAIN);
EXPECT_EQ(i + 1, render_text->cursor_position());
// Verify the selection bounds also increase and that the correct bounds are
// returned even when the grapheme boundary lies within a glyph.
const gfx::Rect selection_bounds = GetSelectionBoundsUnion();
EXPECT_GT(selection_bounds.right(), last_selection_bounds.right());
EXPECT_EQ(selection_bounds.x(), last_selection_bounds.x());
last_selection_bounds = selection_bounds;
}
EXPECT_EQ(6U, render_text->cursor_position());
}
TEST_F(RenderTextTest, GraphemePositions) {
// LTR कि (DEVANAGARI KA with VOWEL I) (2-char grapheme), LTR abc, and LTR कि.
const base::string16 kText1 = WideToUTF16(L"\u0915\u093fabc\u0915\u093f");
// LTR ab, LTR कि (DEVANAGARI KA with VOWEL I) (2-char grapheme), LTR cd.
const base::string16 kText2 = UTF8ToUTF16("ab\u0915\u093fcd");
// LTR ab, 𝄞 'MUSICAL SYMBOL G CLEF' U+1D11E (surrogate pair), LTR cd.
// Windows requires wide strings for \Unnnnnnnn universal character names.
const base::string16 kText3 = WideToUTF16(L"ab\U0001D11Ecd");
struct {
base::string16 text;
size_t index;
size_t expected_previous;
size_t expected_next;
} cases[] = {
{ base::string16(), 0, 0, 0 },
{ base::string16(), 1, 0, 0 },
{ base::string16(), 50, 0, 0 },
{ kText1, 0, 0, 2 },
{ kText1, 1, 0, 2 },
{ kText1, 2, 0, 3 },
{ kText1, 3, 2, 4 },
{ kText1, 4, 3, 5 },
{ kText1, 5, 4, 7 },
{ kText1, 6, 5, 7 },
{ kText1, 7, 5, 7 },
{ kText1, 8, 7, 7 },
{ kText1, 50, 7, 7 },
{ kText2, 0, 0, 1 },
{ kText2, 1, 0, 2 },
{ kText2, 2, 1, 4 },
{ kText2, 3, 2, 4 },
{ kText2, 4, 2, 5 },
{ kText2, 5, 4, 6 },
{ kText2, 6, 5, 6 },
{ kText2, 7, 6, 6 },
{ kText2, 50, 6, 6 },
{ kText3, 0, 0, 1 },
{ kText3, 1, 0, 2 },
{ kText3, 2, 1, 4 },
{ kText3, 3, 2, 4 },
{ kText3, 4, 2, 5 },
{ kText3, 5, 4, 6 },
{ kText3, 6, 5, 6 },
{ kText3, 7, 6, 6 },
{ kText3, 50, 6, 6 },
};
RenderText* render_text = GetRenderText();
for (size_t i = 0; i < base::size(cases); i++) {
SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "]", i));
render_text->SetText(cases[i].text);
size_t next = render_text->IndexOfAdjacentGrapheme(cases[i].index,
CURSOR_FORWARD);
EXPECT_EQ(cases[i].expected_next, next);
EXPECT_TRUE(render_text->IsValidCursorIndex(next));
size_t previous = render_text->IndexOfAdjacentGrapheme(cases[i].index,
CURSOR_BACKWARD);
EXPECT_EQ(cases[i].expected_previous, previous);
EXPECT_TRUE(render_text->IsValidCursorIndex(previous));
}
}
TEST_F(RenderTextTest, MidGraphemeSelectionBounds) {
// Test that selection bounds may be set amid multi-character graphemes.
const base::string16 kHindi = UTF8ToUTF16("\u0915\u093f");
const base::string16 kThai = UTF8ToUTF16("\u0e08\u0e33");
const base::string16 cases[] = { kHindi, kThai };
RenderText* render_text = GetRenderText();
render_text->SetDisplayRect(Rect(100, 1000));
for (size_t i = 0; i < base::size(cases); i++) {
SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "]", i));
render_text->SetText(cases[i]);
EXPECT_TRUE(render_text->IsValidLogicalIndex(1));
EXPECT_FALSE(render_text->IsValidCursorIndex(1));
EXPECT_TRUE(render_text->SelectRange(Range(2, 1)));
EXPECT_EQ(Range(2, 1), render_text->selection());
EXPECT_EQ(1U, render_text->cursor_position());
// Verify that the selection bounds extend over the entire grapheme, even if
// the selection is set amid the grapheme.
test_api()->EnsureLayout();
const gfx::Rect mid_grapheme_bounds = GetSelectionBoundsUnion();
render_text->SelectAll(false);
EXPECT_EQ(GetSelectionBoundsUnion(), mid_grapheme_bounds);
// Although selection bounds may be set within a multi-character grapheme,
// cursor movement (e.g. via arrow key) should avoid those indices.
EXPECT_TRUE(render_text->SelectRange(Range(2, 1)));
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(2U, render_text->cursor_position());
}
}
TEST_F(RenderTextTest, FindCursorPosition) {
const char* kTestStrings[] = {kLtrRtl, kLtrRtlLtr, kRtlLtr, kRtlLtrRtl};
RenderText* render_text = GetRenderText();
render_text->SetDisplayRect(Rect(0, 0, 100, 20));
for (size_t i = 0; i < base::size(kTestStrings); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
render_text->SetText(UTF8ToUTF16(kTestStrings[i]));
for (size_t j = 0; j < render_text->text().length(); ++j) {
const Range range(render_text->GetCursorSpan(Range(j, j + 1)));
// Test a point just inside the leading edge of the glyph bounds.
int x = range.is_reversed() ? range.GetMax() - 1 : range.GetMin() + 1;
EXPECT_EQ(
j, render_text->FindCursorPosition(Point(x, GetCursorYForTesting()))
.caret_pos());
}
}
}
// Tests that FindCursorPosition behaves correctly for multi-line text.
TEST_F(RenderTextTest, FindCursorPositionMultiline) {
const char* kTestStrings[] = {"abc def",
"\u05d0\u05d1\u05d2 \u05d3\u05d4\u05d5"};
SetGlyphWidth(5);
RenderText* render_text = GetRenderText();
render_text->SetDisplayRect(Rect(25, 1000));
render_text->SetMultiline(true);
for (size_t i = 0; i < base::size(kTestStrings); i++) {
render_text->SetText(UTF8ToUTF16(kTestStrings[i]));
test_api()->EnsureLayout();
EXPECT_EQ(2u, test_api()->lines().size());
const bool is_ltr =
render_text->GetDisplayTextDirection() == base::i18n::LEFT_TO_RIGHT;
for (size_t j = 0; j < render_text->text().length(); ++j) {
SCOPED_TRACE(base::StringPrintf(
"Testing index %" PRIuS " for case %" PRIuS "", j, i));
render_text->SelectRange(Range(j, j + 1));
// Test a point inside the leading edge of the glyph bounds.
const Rect bounds = GetSelectionBoundsUnion();
const Point cursor_position(is_ltr ? bounds.x() + 1 : bounds.right() - 1,
bounds.y() + 1);
const SelectionModel model =
render_text->FindCursorPosition(cursor_position);
EXPECT_EQ(j, model.caret_pos());
EXPECT_EQ(CURSOR_FORWARD, model.caret_affinity());
}
}
}
// Ensure FindCursorPosition returns positions only at valid grapheme
// boundaries.
TEST_F(RenderTextTest, FindCursorPosition_GraphemeBoundaries) {
struct {
base::string16 text;
std::set<size_t> expected_cursor_positions;
} cases[] = {
// LTR कि (DEVANAGARI KA with VOWEL I) (2-char grapheme), LTR abc, LTR कि.
{UTF8ToUTF16("\u0915\u093fabc\u0915\u093f"), {0, 2, 3, 4, 5, 7}},
// LTR ab, LTR कि (DEVANAGARI KA with VOWEL I) (2-char grapheme), LTR cd.
{UTF8ToUTF16("ab\u0915\u093fcd"), {0, 1, 2, 4, 5, 6}},
// LTR ab, surrogate pair composed of two 16 bit characters, LTR cd.
// Windows requires wide strings for \Unnnnnnnn universal character names.
{WideToUTF16(L"ab\U0001D11Ecd"), {0, 1, 2, 4, 5, 6}}};
RenderText* render_text = GetRenderText();
render_text->SetDisplayRect(gfx::Rect(100, 30));
for (size_t i = 0; i < base::size(cases); i++) {
SCOPED_TRACE(base::StringPrintf("Testing case %" PRIuS "", i));
render_text->SetText(cases[i].text);
test_api()->EnsureLayout();
std::set<size_t> obtained_cursor_positions;
size_t cursor_y = GetCursorYForTesting();
for (int x = -5; x < 105; x++)
obtained_cursor_positions.insert(
render_text->FindCursorPosition(gfx::Point(x, cursor_y)).caret_pos());
EXPECT_EQ(cases[i].expected_cursor_positions, obtained_cursor_positions);
}
}
TEST_F(RenderTextTest, EdgeSelectionModels) {
// Simple Latin text.
const base::string16 kLatin = UTF8ToUTF16("abc");
// LTR कि (DEVANAGARI KA with VOWEL I).
const base::string16 kLTRGrapheme = UTF8ToUTF16("\u0915\u093f");
// LTR कि (DEVANAGARI KA with VOWEL I), LTR a, LTR कि.
const base::string16 kHindiLatin = UTF8ToUTF16("\u0915\u093fa\u0915\u093f");
// RTL נָ (Hebrew letter NUN and point QAMATS).
const base::string16 kRTLGrapheme = UTF8ToUTF16("\u05e0\u05b8");
// RTL נָ (Hebrew letter NUN and point QAMATS), LTR a, RTL נָ.
const base::string16 kHebrewLatin = UTF8ToUTF16("\u05e0\u05b8a\u05e0\u05b8");
struct {
base::string16 text;
base::i18n::TextDirection expected_text_direction;
} cases[] = {
{ base::string16(), base::i18n::LEFT_TO_RIGHT },
{ kLatin, base::i18n::LEFT_TO_RIGHT },
{ kLTRGrapheme, base::i18n::LEFT_TO_RIGHT },
{ kHindiLatin, base::i18n::LEFT_TO_RIGHT },
{ kRTLGrapheme, base::i18n::RIGHT_TO_LEFT },
{ kHebrewLatin, base::i18n::RIGHT_TO_LEFT },
};
RenderText* render_text = GetRenderText();
for (size_t i = 0; i < base::size(cases); i++) {
render_text->SetText(cases[i].text);
bool ltr = (cases[i].expected_text_direction == base::i18n::LEFT_TO_RIGHT);
SelectionModel start_edge =
test_api()->EdgeSelectionModel(ltr ? CURSOR_LEFT : CURSOR_RIGHT);
EXPECT_EQ(start_edge, SelectionModel(0, CURSOR_BACKWARD));
SelectionModel end_edge =
test_api()->EdgeSelectionModel(ltr ? CURSOR_RIGHT : CURSOR_LEFT);
EXPECT_EQ(end_edge, SelectionModel(cases[i].text.length(), CURSOR_FORWARD));
}
}
TEST_F(RenderTextTest, SelectAll) {
const char* const cases[] = {kWeak, kLtr, kLtrRtl, kLtrRtlLtr,
kRtl, kRtlLtr, kRtlLtrRtl};
// Ensure that SelectAll respects the |reversed| argument regardless of
// application locale and text content directionality.
RenderText* render_text = GetRenderText();
const SelectionModel expected_reversed(Range(3, 0), CURSOR_FORWARD);
const SelectionModel expected_forwards(Range(0, 3), CURSOR_BACKWARD);
const bool was_rtl = base::i18n::IsRTL();
for (size_t i = 0; i < 2; ++i) {
SetRTL(!base::i18n::IsRTL());
// Test that an empty string produces an empty selection model.
render_text->SetText(base::string16());
EXPECT_EQ(render_text->selection_model(), SelectionModel());
// Test the weak, LTR, RTL, and Bidi string cases.
for (size_t j = 0; j < base::size(cases); j++) {
render_text->SetText(UTF8ToUTF16(cases[j]));
render_text->SelectAll(false);
EXPECT_EQ(render_text->selection_model(), expected_forwards);
render_text->SelectAll(true);
EXPECT_EQ(render_text->selection_model(), expected_reversed);
}
}
EXPECT_EQ(was_rtl, base::i18n::IsRTL());
}
TEST_F(RenderTextTest, MoveCursorLeftRightWithSelection) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("abc\u05d0\u05d1\u05d2"));
// Left arrow on select ranging (6, 4).
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(6), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(4), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(5), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(6), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_RETAIN);
EXPECT_EQ(Range(6, 5), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_RETAIN);
EXPECT_EQ(Range(6, 4), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(6), render_text->selection());
// Right arrow on select ranging (4, 6).
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(0), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(1), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(2), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(3), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(5), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(4), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_RETAIN);
EXPECT_EQ(Range(4, 5), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_RETAIN);
EXPECT_EQ(Range(4, 6), render_text->selection());
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(Range(4), render_text->selection());
}
TEST_F(RenderTextTest, CenteredDisplayOffset) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("abcdefghij"));
render_text->SetHorizontalAlignment(ALIGN_CENTER);
const int kEnlargement = 10;
const int content_width = render_text->GetContentWidth();
Rect display_rect(0, 0, content_width / 2,
render_text->font_list().GetHeight());
render_text->SetDisplayRect(display_rect);
// Move the cursor to the beginning of the text and, by checking the cursor
// bounds, make sure no empty space is to the left of the text.
render_text->SetCursorPosition(0);
EXPECT_EQ(display_rect.x(), render_text->GetUpdatedCursorBounds().x());
// Widen the display rect and, by checking the cursor bounds, make sure no
// empty space is introduced to the left of the text.
display_rect.Inset(0, 0, -kEnlargement, 0);
render_text->SetDisplayRect(display_rect);
EXPECT_EQ(display_rect.x(), render_text->GetUpdatedCursorBounds().x());
// Move the cursor to the end of the text and, by checking the cursor
// bounds, make sure no empty space is to the right of the text.
render_text->SetCursorPosition(render_text->text().length());
EXPECT_EQ(display_rect.right(),
render_text->GetUpdatedCursorBounds().right());
// Widen the display rect and, by checking the cursor bounds, make sure no
// empty space is introduced to the right of the text.
display_rect.Inset(0, 0, -kEnlargement, 0);
render_text->SetDisplayRect(display_rect);
EXPECT_EQ(display_rect.right(),
render_text->GetUpdatedCursorBounds().right());
}
void MoveLeftRightByWordVerifier(RenderText* render_text, const char* str) {
SCOPED_TRACE(str);
const base::string16 str16(UTF8ToUTF16(str));
render_text->SetText(str16);
// Test moving by word from left to right.
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
const size_t num_words = (str16.length() + 1) / 4;
for (size_t i = 0; i < num_words; ++i) {
// First, test moving by word from a word break position, such as from
// "|abc def" to "abc| def".
const SelectionModel start = render_text->selection_model();
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
const SelectionModel end = render_text->selection_model();
// For testing simplicity, each word is a 3-character word.
#if defined(OS_WIN)
// Windows moves from "|abc def" to "abc |def" instead of "abc| def", so
// traverse 4 characters on all but the last word instead of all but the
// first.
const int num_character_moves = (i == num_words - 1) ? 3 : 4;
#else
const int num_character_moves = (i == 0) ? 3 : 4;
#endif
render_text->SetSelection(start);
for (int j = 0; j < num_character_moves; ++j)
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(end, render_text->selection_model());
// Then, test moving by word from positions inside the word, such as from
// "a|bc def" to "abc| def", and from "ab|c def" to "abc| def".
for (int j = 1; j < num_character_moves; ++j) {
render_text->SetSelection(start);
for (int k = 0; k < j; ++k)
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_RIGHT, SELECTION_NONE);
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(end, render_text->selection_model());
}
}
// Test moving by word from right to left.
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
for (size_t i = 0; i < num_words; ++i) {
const SelectionModel start = render_text->selection_model();
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
const SelectionModel end = render_text->selection_model();
const int num_character_moves = (i == 0) ? 3 : 4;
render_text->SetSelection(start);
for (int j = 0; j < num_character_moves; ++j)
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(end, render_text->selection_model());
for (int j = 1; j < num_character_moves; ++j) {
render_text->SetSelection(start);
for (int k = 0; k < j; ++k)
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(end, render_text->selection_model());
}
}
}
#if defined(OS_WIN)
// TODO(aleventhal): https://crbug.com/906308 Fix bugs, update verifier code
// above, and enable for Windows.
#define MAYBE_MoveLeftRightByWordInBidiText \
DISABLED_MoveLeftRightByWordInBidiText
#else
#define MAYBE_MoveLeftRightByWordInBidiText MoveLeftRightByWordInBidiText
#endif
TEST_F(RenderTextTest, MAYBE_MoveLeftRightByWordInBidiText) {
RenderText* render_text = GetRenderText();
// For testing simplicity, each word is a 3-character word.
std::vector<const char*> test;
test.push_back("abc");
test.push_back("abc def");
test.push_back("\u05E1\u05E2\u05E3");
test.push_back("\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6");
test.push_back("abc \u05E1\u05E2\u05E3");
test.push_back("abc def \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6");
test.push_back(
"abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"
" \u05E7\u05E8\u05E9");
test.push_back("abc \u05E1\u05E2\u05E3 hij");
test.push_back("abc def \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 hij opq");
test.push_back(
"abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"
" \u05E7\u05E8\u05E9 opq rst uvw");
test.push_back("\u05E1\u05E2\u05E3 abc");
test.push_back("\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 abc def");
test.push_back(
"\u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6 \u05E7\u05E8\u05E9"
" abc def hij");
test.push_back("\u05D1\u05D2\u05D3 abc \u05E1\u05E2\u05E3");
test.push_back(
"\u05D1\u05D2\u05D3 \u05D4\u05D5\u05D6 abc def"
" \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6");
test.push_back(
"\u05D1\u05D2\u05D3 \u05D4\u05D5\u05D6 \u05D7\u05D8\u05D9"
" abc def hij \u05E1\u05E2\u05E3 \u05E4\u05E5\u05E6"
" \u05E7\u05E8\u05E9");
for (size_t i = 0; i < test.size(); ++i)
MoveLeftRightByWordVerifier(render_text, test[i]);
}
TEST_F(RenderTextTest, MoveLeftRightByWordInBidiText_TestEndOfText) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("ab\u05E1"));
// Moving the cursor by word from "abC|" to the left should return "|abC".
// But since end of text is always treated as a word break, it returns
// position "ab|C".
// TODO(xji): Need to make it work as expected.
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
// EXPECT_EQ(SelectionModel(), render_text->selection_model());
// Moving the cursor by word from "|abC" to the right returns "abC|".
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(SelectionModel(3, CURSOR_FORWARD), render_text->selection_model());
render_text->SetText(UTF8ToUTF16("\u05E1\u05E2a"));
// For logical text "BCa", moving the cursor by word from "aCB|" to the left
// returns "|aCB".
render_text->MoveCursor(LINE_BREAK, CURSOR_RIGHT, SELECTION_NONE);
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(SelectionModel(3, CURSOR_FORWARD), render_text->selection_model());
// Moving the cursor by word from "|aCB" to the right should return "aCB|".
// But since end of text is always treated as a word break, it returns
// position "a|CB".
// TODO(xji): Need to make it work as expected.
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
// EXPECT_EQ(SelectionModel(), render_text->selection_model());
}
TEST_F(RenderTextTest, MoveLeftRightByWordInTextWithMultiSpaces) {
RenderText* render_text = GetRenderText();
render_text->SetText(UTF8ToUTF16("abc def"));
render_text->SetCursorPosition(5);
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
#if defined(OS_WIN)
EXPECT_EQ(8U, render_text->cursor_position());
#else
EXPECT_EQ(11U, render_text->cursor_position());
#endif
render_text->SetCursorPosition(5);
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
}
TEST_F(RenderTextTest, MoveLeftRightByWordInThaiText) {
RenderText* render_text = GetRenderText();
// เรียกดูรวดเร็ว is broken to เรียก|ดู|รวดเร็ว.
render_text->SetText(UTF8ToUTF16("เรียกดูรวดเร็ว"));
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(5U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(7U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(14U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(14U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(7U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(5U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
}
// TODO(crbug.com/865527): Chinese and Japanese tokenization doesn't work on
// mobile.
#if !defined(OS_ANDROID)
TEST_F(RenderTextTest, MoveLeftRightByWordInChineseText) {
RenderText* render_text = GetRenderText();
// zh-Hans-CN: 我们去公园玩, broken to 我们|去|公园|玩.
render_text->SetText(UTF8ToUTF16("\u6211\u4EEC\u53BB\u516C\u56ED\u73A9"));
render_text->MoveCursor(LINE_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(2U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(3U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(5U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(6U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_RIGHT, SELECTION_NONE);
EXPECT_EQ(6U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(5U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(3U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(2U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
render_text->MoveCursor(WORD_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(0U, render_text->cursor_position());
}
#endif
// Test the correct behavior of undirected selections: selections where the
// "end" of the selection that holds the cursor is only determined after the
// first cursor movement.
TEST_F(RenderTextTest, DirectedSelections) {
RenderText* render_text = GetRenderText();
auto ResultAfter = [&](VisualCursorDirection direction) -> base::string16 {
render_text->MoveCursor(CHARACTER_BREAK, direction, SELECTION_RETAIN);
return GetSelectedText(render_text);
};
render_text->SetText(UTF8ToUTF16("01234"));
// Test Right, then Left. LTR.
// Undirected, or forward when kSelectionIsAlwaysDirected.
render_text->SelectRange({2, 4});
EXPECT_EQ(UTF8ToUTF16("23"), GetSelectedText(render_text));
EXPECT_EQ(UTF8ToUTF16("234"), ResultAfter(CURSOR_RIGHT));
EXPECT_EQ(UTF8ToUTF16("23"), ResultAfter(CURSOR_LEFT));
// Test collapsing the selection. This always ignores any existing direction.
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(2, 2), render_text->selection()); // Collapse left.
// Undirected, or backward when kSelectionIsAlwaysDirected.
render_text->SelectRange({4, 2});
EXPECT_EQ(UTF8ToUTF16("23"), GetSelectedText(render_text));
if (RenderText::kSelectionIsAlwaysDirected)
EXPECT_EQ(UTF8ToUTF16("3"), ResultAfter(CURSOR_RIGHT)); // Keep left.
else
EXPECT_EQ(UTF8ToUTF16("234"), ResultAfter(CURSOR_RIGHT)); // Pick right.
EXPECT_EQ(UTF8ToUTF16("23"), ResultAfter(CURSOR_LEFT));
render_text->MoveCursor(CHARACTER_BREAK, CURSOR_LEFT, SELECTION_NONE);
EXPECT_EQ(Range(2, 2), render_text->selection()); // Collapse left.
// Test Left, then Right. LTR.
// Undirected, or forward when kSelectionIsAlwaysDirected.
render_text->SelectRange({2, 4});
EXPECT_EQ(UTF8ToUTF16("23"), GetSelectedText(render_text)); // Sanity check,
if (RenderText::kSelectionIsAlwaysDirected)
EXPECT_EQ(UTF8ToUTF16("2"), ResultAfter(CURSOR_LEFT)); // Keep right.
else