Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(255)

Side by Side Diff: ui/gfx/render_text.cc

Issue 7265011: RenderText API Outline. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix permissions, export RenderText and StyleRange via UI_API. Created 9 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/gfx/render_text.h"
6
7 #include <algorithm>
8
9 #include "base/i18n/break_iterator.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "ui/gfx/canvas.h"
13 #include "ui/gfx/canvas_skia.h"
14
15 namespace {
16
17 #ifndef NDEBUG
18 // Check StyleRanges invariant conditions: sorted and non-overlapping ranges.
19 void CheckStyleRanges(const gfx::StyleRanges& style_ranges, size_t length) {
20 if (length == 0) {
21 DCHECK(style_ranges.empty()) << "Style ranges exist for empty text.";
22 return;
23 }
24 for (gfx::StyleRanges::size_type i = 0; i < style_ranges.size() - 1; i++) {
25 const ui::Range& former = style_ranges[i].range;
26 const ui::Range& latter = style_ranges[i + 1].range;
27 DCHECK(!former.is_empty()) << "Empty range at " << i << ":" << former;
28 DCHECK(former.IsValid()) << "Invalid range at " << i << ":" << former;
29 DCHECK(!former.is_reversed()) << "Reversed range at " << i << ":" << former;
30 DCHECK(former.end() == latter.start()) << "Ranges gap/overlap/unsorted." <<
31 "former:" << former << ", latter:" << latter;
32 }
33 const gfx::StyleRange& end_style = *style_ranges.rbegin();
34 DCHECK(!end_style.range.is_empty()) << "Empty range at end.";
35 DCHECK(end_style.range.IsValid()) << "Invalid range at end.";
36 DCHECK(!end_style.range.is_reversed()) << "Reversed range at end.";
37 DCHECK(end_style.range.end() == length) << "Style and text length mismatch.";
38 }
39 #endif
40
41 void ApplyStyleRangeImpl(gfx::StyleRanges& style_ranges,
42 gfx::StyleRange style_range) {
43 const ui::Range& new_range = style_range.range;
44 // Follow StyleRanges invariant conditions: sorted and non-overlapping ranges.
45 gfx::StyleRanges::iterator i;
46 for (i = style_ranges.begin(); i != style_ranges.end();) {
47 if (i->range.end() < new_range.start()) {
48 i++;
49 } else if (i->range.start() == new_range.end()) {
50 break;
51 } else if (new_range.Contains(i->range)) {
52 i = style_ranges.erase(i);
53 if (i == style_ranges.end())
54 break;
55 } else if (i->range.start() < new_range.start() &&
56 i->range.end() > new_range.end()) {
57 // Split the current style into two styles.
58 gfx::StyleRange split_style = gfx::StyleRange(*i);
59 split_style.range.set_end(new_range.start());
60 i = style_ranges.insert(i, split_style) + 1;
61 i->range.set_start(new_range.end());
62 break;
63 } else if (i->range.start() < new_range.start()) {
64 i->range.set_end(new_range.start());
65 i++;
66 } else if (i->range.end() > new_range.end()) {
67 i->range.set_start(new_range.end());
68 break;
69 } else
70 NOTREACHED();
71 }
72 // Add the new range in its sorted location.
73 style_ranges.insert(i, style_range);
74 }
75
76 } // namespace
77
78 namespace gfx {
79
80 StyleRange::StyleRange()
81 : font(),
82 foreground(SK_ColorBLACK),
83 strike(false),
84 underline(false),
85 range() {
86 }
87
88 void RenderText::SetText(const string16& text) {
89 size_t old_text_length = text_.length();
90 text_ = text;
91
92 // Update the style ranges as needed.
93 if (text_.empty()) {
94 style_ranges_.clear();
95 } else if (style_ranges_.empty()) {
96 ApplyDefaultStyle();
97 } else if (text_.length() > old_text_length) {
98 style_ranges_.back().range.set_end(text_.length());
99 } else if (text_.length() < old_text_length) {
100 StyleRanges::iterator i;
101 for (i = style_ranges_.begin(); i != style_ranges_.end(); i++) {
102 if (i->range.start() >= text_.length()) {
103 i = style_ranges_.erase(i);
104 if (i == style_ranges_.end())
105 break;
106 } else if (i->range.end() > text_.length()) {
107 i->range.set_end(text_.length());
108 }
109 }
110 style_ranges_.back().range.set_end(text_.length());
111 }
112 #ifndef NDEBUG
113 CheckStyleRanges(style_ranges_, text_.length());
114 #endif
115 }
116
117 size_t RenderText::GetCursorPosition() const {
118 return GetSelection().end();
119 }
120
121 void RenderText::SetCursorPosition(const size_t position) {
122 SetSelection(ui::Range(position, position));
123 }
124
125 void RenderText::MoveCursorLeft(BreakType break_type, bool select) {
126 if (break_type == LINE_BREAK) {
127 MoveCursorTo(0, select);
128 return;
129 }
130 size_t position = GetCursorPosition();
131 // Cancelling a selection moves to the edge of the selection.
132 if (!GetSelection().is_empty() && !select) {
133 // Use the selection start if it is left of the selection end.
134 if (GetCursorBounds(GetSelection().start(), false).x() <
135 GetCursorBounds(position, false).x())
136 position = GetSelection().start();
137 // If |move_by_word|, use the nearest word boundary left of the selection.
138 if (break_type == WORD_BREAK)
139 position = GetLeftCursorPosition(position, true);
140 } else {
141 position = GetLeftCursorPosition(position, break_type == WORD_BREAK);
142 }
143 MoveCursorTo(position, select);
144 }
145
146 void RenderText::MoveCursorRight(BreakType break_type, bool select) {
147 if (break_type == LINE_BREAK) {
148 MoveCursorTo(text().length(), select);
149 return;
150 }
151 size_t position = GetCursorPosition();
152 // Cancelling a selection moves to the edge of the selection.
153 if (!GetSelection().is_empty() && !select) {
154 // Use the selection start if it is right of the selection end.
155 if (GetCursorBounds(GetSelection().start(), false).x() >
156 GetCursorBounds(position, false).x())
157 position = GetSelection().start();
158 // If |move_by_word|, use the nearest word boundary right of the selection.
159 if (break_type == WORD_BREAK)
160 position = GetRightCursorPosition(position, true);
161 } else {
162 position = GetRightCursorPosition(position, break_type == WORD_BREAK);
163 }
164 MoveCursorTo(position, select);
165 }
166
167 bool RenderText::MoveCursorTo(size_t position, bool select) {
168 bool changed = GetCursorPosition() != position ||
169 select == GetSelection().is_empty();
170 if (select)
171 SetSelection(ui::Range(GetSelection().start(), position));
172 else
173 SetSelection(ui::Range(position, position));
174 return changed;
175 }
176
177 bool RenderText::MoveCursorTo(const gfx::Point& point, bool select) {
178 // TODO(msw): Make this function support cursor placement via mouse near BiDi
179 // level changes. The visual cursor appearance will depend on the location
180 // clicked, not solely the resulting logical cursor position. See the TODO
181 // note pertaining to selection_range_ for more information.
182 return MoveCursorTo(FindCursorPosition(point), select);
183 }
184
185 const ui::Range& RenderText::GetSelection() const {
186 return selection_range_;
187 }
188
189 void RenderText::SetSelection(const ui::Range& range) {
190 selection_range_.set_end(std::min(range.end(), text().length()));
191 selection_range_.set_start(std::min(range.start(), text().length()));
192
193 // Update |display_offset_| to ensure the current cursor is visible.
194 gfx::Rect cursor_bounds(GetCursorBounds(GetCursorPosition(), insert_mode()));
195 int display_width = display_rect_.width();
196 int string_width = GetStringWidth();
197 if (string_width < display_width) {
198 // Show all text whenever the text fits to the size.
199 display_offset_.set_x(0);
200 } else if ((display_offset_.x() + cursor_bounds.right()) > display_width) {
201 // Pan to show the cursor when it overflows to the right,
202 display_offset_.set_x(display_width - cursor_bounds.right());
203 } else if ((display_offset_.x() + cursor_bounds.x()) < 0) {
204 // Pan to show the cursor when it overflows to the left.
205 display_offset_.set_x(-cursor_bounds.x());
206 }
207 }
208
209 bool RenderText::IsPointInSelection(const gfx::Point& point) const {
210 size_t pos = FindCursorPosition(point);
211 return (pos >= GetSelection().GetMin() && pos < GetSelection().GetMax());
212 }
213
214 void RenderText::ClearSelection() {
215 SetCursorPosition(GetCursorPosition());
216 }
217
218 void RenderText::SelectAll() {
219 SetSelection(ui::Range(0, text().length()));
220 }
221
222 void RenderText::SelectWord() {
223 size_t selection_start = GetSelection().start();
224 size_t cursor_position = GetCursorPosition();
225 // First we setup selection_start_ and cursor_pos_. There are so many cases
226 // because we try to emulate what select-word looks like in a gtk textfield.
227 // See associated testcase for different cases.
228 if (cursor_position > 0 && cursor_position < text().length()) {
229 if (isalnum(text()[cursor_position])) {
230 selection_start = cursor_position;
231 cursor_position++;
232 } else
233 selection_start = cursor_position - 1;
234 } else if (cursor_position == 0) {
235 selection_start = cursor_position;
236 if (text().length() > 0)
237 cursor_position++;
238 } else {
239 selection_start = cursor_position - 1;
240 }
241
242 // Now we move selection_start_ to beginning of selection. Selection boundary
243 // is defined as the position where we have alpha-num character on one side
244 // and non-alpha-num char on the other side.
245 for (; selection_start > 0; selection_start--) {
246 if (IsPositionAtWordSelectionBoundary(selection_start))
247 break;
248 }
249
250 // Now we move cursor_pos_ to end of selection. Selection boundary
251 // is defined as the position where we have alpha-num character on one side
252 // and non-alpha-num char on the other side.
253 for (; cursor_position < text().length(); cursor_position++) {
254 if (IsPositionAtWordSelectionBoundary(cursor_position))
255 break;
256 }
257
258 SetSelection(ui::Range(selection_start, cursor_position));
259 }
260
261 const ui::Range& RenderText::GetCompositionRange() const {
262 return composition_range_;
263 }
264
265 void RenderText::SetCompositionRange(const ui::Range& composition_range) {
266 CHECK(!composition_range.IsValid() ||
267 ui::Range(0, text_.length()).Contains(composition_range));
268 composition_range_.set_end(composition_range.end());
269 composition_range_.set_start(composition_range.start());
270 }
271
272 void RenderText::ApplyStyleRange(StyleRange style_range) {
273 const ui::Range& new_range = style_range.range;
274 if (!new_range.IsValid() || new_range.is_empty())
275 return;
276 CHECK(!new_range.is_reversed());
277 CHECK(ui::Range(0, text_.length()).Contains(new_range));
278 ApplyStyleRangeImpl(style_ranges_, style_range);
279 #ifndef NDEBUG
280 CheckStyleRanges(style_ranges_, text_.length());
281 #endif
282 }
283
284 void RenderText::ApplyDefaultStyle() {
285 style_ranges_.clear();
286 StyleRange style = StyleRange(default_style_);
287 style.range.set_end(text_.length());
288 style_ranges_.push_back(style);
289 }
290
291 base::i18n::TextDirection RenderText::GetTextDirection() const {
292 // TODO(msw): Bidi implementation, intended to replace the functionality added
293 // in crrev.com/91881 (discussed in codereview.chromium.org/7324011).
294 return base::i18n::LEFT_TO_RIGHT;
295 }
296
297 int RenderText::GetStringWidth() const {
298 return GetSubstringBounds(ui::Range(0, text_.length()))[0].width();
299 }
300
301 void RenderText::Draw(gfx::Canvas* canvas) {
302 // Clip the canvas to the text display area.
303 canvas->ClipRectInt(display_rect_.x(), display_rect_.y(),
304 display_rect_.width(), display_rect_.height());
305
306 // Draw the selection.
307 std::vector<gfx::Rect> selection(GetSubstringBounds(GetSelection()));
308 SkColor selection_color =
309 focused() ? kFocusedSelectionColor : kUnfocusedSelectionColor;
310 for (std::vector<gfx::Rect>::const_iterator i = selection.begin();
311 i < selection.end(); ++i) {
312 gfx::Rect r(*i);
313 r.Offset(display_offset_);
314 canvas->FillRectInt(selection_color, r.x(), r.y(), r.width(), r.height());
315 }
316
317 // Create a temporary copy of the style ranges for composition and selection.
318 // TODO(msw): This pattern ought to be reconsidered; what about composition
319 // and selection overlaps, retain existing local style features?
320 StyleRanges style_ranges(style_ranges_);
321 // Apply a composition style override to a copy of the style ranges.
322 if (composition_range_.IsValid() && !composition_range_.is_empty()) {
323 StyleRange composition_style(default_style_);
324 composition_style.underline = true;
325 composition_style.range.set_start(composition_range_.start());
326 composition_style.range.set_end(composition_range_.end());
327 ApplyStyleRangeImpl(style_ranges, composition_style);
328 }
329 // Apply a selection style override to a copy of the style ranges.
330 if (selection_range_.IsValid() && !selection_range_.is_empty()) {
331 StyleRange selection_style(default_style_);
332 selection_style.foreground = kSelectedTextColor;
333 selection_style.range.set_start(selection_range_.GetMin());
334 selection_style.range.set_end(selection_range_.GetMax());
335 ApplyStyleRangeImpl(style_ranges, selection_style);
336 }
337
338 // Draw the text.
339 gfx::Rect bounds(display_rect_);
340 bounds.Offset(display_offset_);
341 for (StyleRanges::const_iterator i = style_ranges.begin();
342 i < style_ranges.end(); ++i) {
343 Font font = !i->underline ? i->font :
344 i->font.DeriveFont(0, i->font.GetStyle() | Font::UNDERLINED);
345 string16 text = text_.substr(i->range.start(), i->range.length());
346 bounds.set_width(font.GetStringWidth(text));
347 canvas->DrawStringInt(text, font, i->foreground, bounds);
348
349 // Draw the strikethrough.
350 if (i->strike) {
351 SkPaint paint;
352 paint.setAntiAlias(true);
353 paint.setStyle(SkPaint::kFill_Style);
354 paint.setColor(i->foreground);
355 paint.setStrokeWidth(kStrikeWidth);
356 canvas->AsCanvasSkia()->drawLine(SkIntToScalar(bounds.x()),
357 SkIntToScalar(bounds.bottom()),
358 SkIntToScalar(bounds.right()),
359 SkIntToScalar(bounds.y()),
360 paint);
361 }
362
363 bounds.set_x(bounds.x() + bounds.width());
364 }
365
366 // Paint cursor. Replace cursor is drawn as rectangle for now.
367 if (cursor_visible() && focused()) {
368 bounds = GetCursorBounds(GetCursorPosition(), insert_mode());
369 bounds.Offset(display_offset_);
370 if (!bounds.IsEmpty())
371 canvas->DrawRectInt(kCursorColor,
372 bounds.x(),
373 bounds.y(),
374 bounds.width(),
375 bounds.height());
376 }
377 }
378
379 size_t RenderText::FindCursorPosition(const gfx::Point& point) const {
380 const gfx::Font& font = Font();
381 int left = 0;
382 int left_pos = 0;
383 int right = font.GetStringWidth(text());
384 int right_pos = text().length();
385
386 int x = point.x();
387 if (x <= left) return left_pos;
388 if (x >= right) return right_pos;
389 // binary searching the cursor position.
390 // TODO(oshima): use the center of character instead of edge.
391 // Binary search may not work for language like arabic.
392 while (std::abs(static_cast<long>(right_pos - left_pos) > 1)) {
393 int pivot_pos = left_pos + (right_pos - left_pos) / 2;
394 int pivot = font.GetStringWidth(text().substr(0, pivot_pos));
395 if (pivot < x) {
396 left = pivot;
397 left_pos = pivot_pos;
398 } else if (pivot == x) {
399 return pivot_pos;
400 } else {
401 right = pivot;
402 right_pos = pivot_pos;
403 }
404 }
405 return left_pos;
406 }
407
408 std::vector<gfx::Rect> RenderText::GetSubstringBounds(
409 const ui::Range& range) const {
410 size_t start = range.GetMin();
411 size_t end = range.GetMax();
412 gfx::Font font;
413 int start_x = font.GetStringWidth(text().substr(0, start));
414 int end_x = font.GetStringWidth(text().substr(0, end));
415 std::vector<gfx::Rect> bounds;
416 bounds.push_back(gfx::Rect(start_x, 0, end_x - start_x, font.GetHeight()));
417 return bounds;
418 }
419
420 gfx::Rect RenderText::GetCursorBounds(size_t cursor_pos,
421 bool insert_mode) const {
422 gfx::Font font;
423 int x = font.GetStringWidth(text_.substr(0U, cursor_pos));
424 DCHECK_GE(x, 0);
425 int h = std::min(display_rect_.height(), font.GetHeight());
426 gfx::Rect bounds(x, (display_rect_.height() - h) / 2, 1, h);
427 if (!insert_mode && text_.length() != cursor_pos)
428 bounds.set_width(font.GetStringWidth(text_.substr(0, cursor_pos + 1)) - x);
429 return bounds;
430 }
431
432 size_t RenderText::GetLeftCursorPosition(size_t position,
433 bool move_by_word) const {
434 if (!move_by_word)
435 return position == 0? position : position - 1;
436 // Notes: We always iterate words from the begining.
437 // This is probably fast enough for our usage, but we may
438 // want to modify WordIterator so that it can start from the
439 // middle of string and advance backwards.
440 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
441 bool success = iter.Init();
442 DCHECK(success);
443 if (!success)
444 return position;
445 int last = 0;
446 while (iter.Advance()) {
447 if (iter.IsWord()) {
448 size_t begin = iter.pos() - iter.GetString().length();
449 if (begin == position) {
450 // The cursor is at the beginning of a word.
451 // Move to previous word.
452 break;
453 } else if(iter.pos() >= position) {
454 // The cursor is in the middle or at the end of a word.
455 // Move to the top of current word.
456 last = begin;
457 break;
458 } else {
459 last = iter.pos() - iter.GetString().length();
460 }
461 }
462 }
463
464 return last;
465 }
466
467 size_t RenderText::GetRightCursorPosition(size_t position,
468 bool move_by_word) const {
469 if (!move_by_word)
470 return std::min(position + 1, text().length());
471 base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
472 bool success = iter.Init();
473 DCHECK(success);
474 if (!success)
475 return position;
476 size_t pos = 0;
477 while (iter.Advance()) {
478 pos = iter.pos();
479 if (iter.IsWord() && pos > position) {
480 break;
481 }
482 }
483 return pos;
484 }
485
486 RenderText::RenderText()
487 : text_(),
488 selection_range_(),
489 cursor_visible_(false),
490 insert_mode_(true),
491 composition_range_(),
492 style_ranges_(),
493 default_style_(),
494 display_rect_(),
495 display_offset_() {
496 }
497
498 RenderText::~RenderText() {
499 }
500
501 bool RenderText::IsPositionAtWordSelectionBoundary(size_t pos) {
502 return pos == 0 || (isalnum(text()[pos - 1]) && !isalnum(text()[pos])) ||
503 (!isalnum(text()[pos - 1]) && isalnum(text()[pos]));
504 }
505
506 } // namespace gfx
OLDNEW
« no previous file with comments | « ui/gfx/render_text.h ('k') | ui/gfx/render_text_linux.h » ('j') | ui/ui.gyp » ('J')

Powered by Google App Engine
This is Rietveld 408576698