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

Side by Side Diff: app/text_elider.cc

Issue 6257006: Move a bunch of random other files to src/ui/base... (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Created 9 years, 11 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
« no previous file with comments | « app/text_elider.h ('k') | app/text_elider_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2010 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 <vector>
6
7 #include "app/text_elider.h"
8 #include "base/file_path.h"
9 #include "base/i18n/break_iterator.h"
10 #include "base/i18n/char_iterator.h"
11 #include "base/i18n/rtl.h"
12 #include "base/string_split.h"
13 #include "base/string_util.h"
14 #include "base/sys_string_conversions.h"
15 #include "base/utf_string_conversions.h"
16 #include "gfx/font.h"
17 #include "googleurl/src/gurl.h"
18 #include "net/base/escape.h"
19 #include "net/base/net_util.h"
20 #include "net/base/registry_controlled_domain.h"
21
22
23 namespace {
24
25 const char* kEllipsis = "\xE2\x80\xA6";
26
27 // Cuts |text| to be |length| characters long. If |cut_in_middle| is true, the
28 // middle of the string is removed to leave equal-length pieces from the
29 // beginning and end of the string; otherwise, the end of the string is removed
30 // and only the beginning remains. If |insert_ellipsis| is true, then an
31 // ellipsis character will by inserted at the cut point.
32 string16 CutString(const string16& text,
33 size_t length,
34 bool cut_in_middle,
35 bool insert_ellipsis) {
36 // TODO(tony): This is wrong, it might split the string in the middle of a
37 // surrogate pair.
38 const string16 kInsert = insert_ellipsis ? UTF8ToUTF16(kEllipsis) :
39 ASCIIToUTF16("");
40 if (!cut_in_middle)
41 return text.substr(0, length) + kInsert;
42 // We put the extra character, if any, before the cut.
43 const size_t half_length = length / 2;
44 return text.substr(0, length - half_length) + kInsert +
45 text.substr(text.length() - half_length, half_length);
46 }
47
48 } // namespace
49
50 namespace gfx {
51
52 // This function takes a GURL object and elides it. It returns a string
53 // which composed of parts from subdomain, domain, path, filename and query.
54 // A "..." is added automatically at the end if the elided string is bigger
55 // than the available pixel width. For available pixel width = 0, a formatted,
56 // but un-elided, string is returned.
57 //
58 // TODO(pkasting): http://b/119635 This whole function gets
59 // kerning/ligatures/etc. issues potentially wrong by assuming that the width of
60 // a rendered string is always the sum of the widths of its substrings. Also I
61 // suspect it could be made simpler.
62 string16 ElideUrl(const GURL& url,
63 const gfx::Font& font,
64 int available_pixel_width,
65 const std::wstring& languages) {
66 // Get a formatted string and corresponding parsing of the url.
67 url_parse::Parsed parsed;
68 string16 url_string = net::FormatUrl(url, WideToUTF8(languages),
69 net::kFormatUrlOmitAll, UnescapeRule::SPACES, &parsed, NULL, NULL);
70 if (available_pixel_width <= 0)
71 return url_string;
72
73 // If non-standard or not file type, return plain eliding.
74 if (!(url.SchemeIsFile() || url.IsStandard()))
75 return ElideText(url_string, font, available_pixel_width, false);
76
77 // Now start eliding url_string to fit within available pixel width.
78 // Fist pass - check to see whether entire url_string fits.
79 int pixel_width_url_string = font.GetStringWidth(url_string);
80 if (available_pixel_width >= pixel_width_url_string)
81 return url_string;
82
83 // Get the path substring, including query and reference.
84 size_t path_start_index = parsed.path.begin;
85 size_t path_len = parsed.path.len;
86 string16 url_path_query_etc = url_string.substr(path_start_index);
87 string16 url_path = url_string.substr(path_start_index, path_len);
88
89 // Return general elided text if url minus the query fits.
90 string16 url_minus_query = url_string.substr(0, path_start_index + path_len);
91 if (available_pixel_width >= font.GetStringWidth(url_minus_query))
92 return ElideText(url_string, font, available_pixel_width, false);
93
94 // Get Host.
95 string16 url_host = UTF8ToUTF16(url.host());
96
97 // Get domain and registry information from the URL.
98 string16 url_domain = UTF8ToUTF16(
99 net::RegistryControlledDomainService::GetDomainAndRegistry(url));
100 if (url_domain.empty())
101 url_domain = url_host;
102
103 // Add port if required.
104 if (!url.port().empty()) {
105 url_host += UTF8ToUTF16(":" + url.port());
106 url_domain += UTF8ToUTF16(":" + url.port());
107 }
108
109 // Get sub domain.
110 string16 url_subdomain;
111 size_t domain_start_index = url_host.find(url_domain);
112 if (domain_start_index > 0)
113 url_subdomain = url_host.substr(0, domain_start_index);
114 static const string16 kWwwPrefix = UTF8ToUTF16("www.");
115 if ((url_subdomain == kWwwPrefix || url_subdomain.empty() ||
116 url.SchemeIsFile())) {
117 url_subdomain.clear();
118 }
119
120 // If this is a file type, the path is now defined as everything after ":".
121 // For example, "C:/aa/aa/bb", the path is "/aa/bb/cc". Interesting, the
122 // domain is now C: - this is a nice hack for eliding to work pleasantly.
123 if (url.SchemeIsFile()) {
124 // Split the path string using ":"
125 std::vector<string16> file_path_split;
126 base::SplitString(url_path, ':', &file_path_split);
127 if (file_path_split.size() > 1) { // File is of type "file:///C:/.."
128 url_host.clear();
129 url_domain.clear();
130 url_subdomain.clear();
131
132 static const string16 kColon = UTF8ToUTF16(":");
133 url_host = url_domain = file_path_split.at(0).substr(1) + kColon;
134 url_path_query_etc = url_path = file_path_split.at(1);
135 }
136 }
137
138 // Second Pass - remove scheme - the rest fits.
139 int pixel_width_url_host = font.GetStringWidth(url_host);
140 int pixel_width_url_path = font.GetStringWidth(url_path_query_etc);
141 if (available_pixel_width >=
142 pixel_width_url_host + pixel_width_url_path)
143 return url_host + url_path_query_etc;
144
145 // Third Pass: Subdomain, domain and entire path fits.
146 int pixel_width_url_domain = font.GetStringWidth(url_domain);
147 int pixel_width_url_subdomain = font.GetStringWidth(url_subdomain);
148 if (available_pixel_width >=
149 pixel_width_url_subdomain + pixel_width_url_domain +
150 pixel_width_url_path)
151 return url_subdomain + url_domain + url_path_query_etc;
152
153 // Query element.
154 string16 url_query;
155 const int kPixelWidthDotsTrailer =
156 font.GetStringWidth(UTF8ToUTF16(kEllipsis));
157 if (parsed.query.is_nonempty()) {
158 url_query = UTF8ToUTF16("?") + url_string.substr(parsed.query.begin);
159 if (available_pixel_width >= (pixel_width_url_subdomain +
160 pixel_width_url_domain + pixel_width_url_path -
161 font.GetStringWidth(url_query))) {
162 return ElideText(url_subdomain + url_domain + url_path_query_etc,
163 font, available_pixel_width, false);
164 }
165 }
166
167 // Parse url_path using '/'.
168 static const string16 kForwardSlash = UTF8ToUTF16("/");
169 std::vector<string16> url_path_elements;
170 base::SplitString(url_path, kForwardSlash[0], &url_path_elements);
171
172 // Get filename - note that for a path ending with /
173 // such as www.google.com/intl/ads/, the file name is ads/.
174 size_t url_path_number_of_elements = url_path_elements.size();
175 DCHECK(url_path_number_of_elements != 0);
176 string16 url_filename;
177 if ((url_path_elements.at(url_path_number_of_elements - 1)).length() > 0) {
178 url_filename = *(url_path_elements.end() - 1);
179 } else if (url_path_number_of_elements > 1) { // Path ends with a '/'.
180 url_filename = url_path_elements.at(url_path_number_of_elements - 2) +
181 kForwardSlash;
182 url_path_number_of_elements--;
183 }
184 DCHECK(url_path_number_of_elements != 0);
185
186 const size_t kMaxNumberOfUrlPathElementsAllowed = 1024;
187 if (url_path_number_of_elements <= 1 ||
188 url_path_number_of_elements > kMaxNumberOfUrlPathElementsAllowed) {
189 // No path to elide, or too long of a path (could overflow in loop below)
190 // Just elide this as a text string.
191 return ElideText(url_subdomain + url_domain + url_path_query_etc, font,
192 available_pixel_width, false);
193 }
194
195 // Start eliding the path and replacing elements by "../".
196 const string16 kEllipsisAndSlash = UTF8ToUTF16(kEllipsis) + kForwardSlash;
197 int pixel_width_url_filename = font.GetStringWidth(url_filename);
198 int pixel_width_dot_dot_slash = font.GetStringWidth(kEllipsisAndSlash);
199 int pixel_width_slash = font.GetStringWidth(ASCIIToUTF16("/"));
200 int pixel_width_url_path_elements[kMaxNumberOfUrlPathElementsAllowed];
201 for (size_t i = 0; i < url_path_number_of_elements; ++i) {
202 pixel_width_url_path_elements[i] =
203 font.GetStringWidth(url_path_elements.at(i));
204 }
205
206 // Check with both subdomain and domain.
207 string16 elided_path;
208 int pixel_width_elided_path;
209 for (size_t i = url_path_number_of_elements - 1; i >= 1; --i) {
210 // Add the initial elements of the path.
211 elided_path.clear();
212 pixel_width_elided_path = 0;
213 for (size_t j = 0; j < i; ++j) {
214 elided_path += url_path_elements.at(j) + kForwardSlash;
215 pixel_width_elided_path += pixel_width_url_path_elements[j] +
216 pixel_width_slash;
217 }
218
219 // Add url_file_name.
220 if (i == (url_path_number_of_elements - 1)) {
221 elided_path += url_filename;
222 pixel_width_elided_path += pixel_width_url_filename;
223 } else {
224 elided_path += kEllipsisAndSlash + url_filename;
225 pixel_width_elided_path += pixel_width_dot_dot_slash +
226 pixel_width_url_filename;
227 }
228
229 if (available_pixel_width >=
230 pixel_width_url_subdomain + pixel_width_url_domain +
231 pixel_width_elided_path) {
232 return ElideText(url_subdomain + url_domain + elided_path + url_query,
233 font, available_pixel_width, false);
234 }
235 }
236
237 // Check with only domain.
238 // If a subdomain is present, add an ellipsis before domain.
239 // This is added only if the subdomain pixel width is larger than
240 // the pixel width of kEllipsis. Otherwise, subdomain remains,
241 // which means that this case has been resolved earlier.
242 string16 url_elided_domain = url_subdomain + url_domain;
243 int pixel_width_url_elided_domain = pixel_width_url_domain;
244 if (pixel_width_url_subdomain > kPixelWidthDotsTrailer) {
245 if (!url_subdomain.empty()) {
246 url_elided_domain = kEllipsisAndSlash[0] + url_domain;
247 pixel_width_url_elided_domain += kPixelWidthDotsTrailer;
248 } else {
249 url_elided_domain = url_domain;
250 }
251
252 for (size_t i = url_path_number_of_elements - 1; i >= 1; --i) {
253 // Add the initial elements of the path.
254 elided_path.clear();
255 pixel_width_elided_path = 0;
256 for (size_t j = 0; j < i; ++j) {
257 elided_path += url_path_elements.at(j) + kForwardSlash;
258 pixel_width_elided_path += pixel_width_url_path_elements[j] +
259 pixel_width_slash;
260 }
261
262 // Add url_file_name.
263 if (i == (url_path_number_of_elements - 1)) {
264 elided_path += url_filename;
265 pixel_width_elided_path += pixel_width_url_filename;
266 } else {
267 elided_path += kEllipsisAndSlash + url_filename;
268 pixel_width_elided_path += pixel_width_dot_dot_slash +
269 pixel_width_url_filename;
270 }
271
272 if (available_pixel_width >=
273 pixel_width_url_elided_domain + pixel_width_elided_path) {
274 return ElideText(url_elided_domain + elided_path + url_query, font,
275 available_pixel_width, false);
276 }
277 }
278 }
279
280 // Return elided domain/../filename anyway.
281 string16 final_elided_url_string(url_elided_domain);
282 int url_elided_domain_width = font.GetStringWidth(url_elided_domain);
283
284 // A hack to prevent trailing "../...".
285 if ((available_pixel_width - url_elided_domain_width) >
286 pixel_width_dot_dot_slash + kPixelWidthDotsTrailer +
287 font.GetStringWidth(ASCIIToUTF16("UV"))) {
288 final_elided_url_string += elided_path;
289 } else {
290 final_elided_url_string += url_path;
291 }
292
293 return ElideText(final_elided_url_string, font, available_pixel_width, false);
294 }
295
296 string16 ElideFilename(const FilePath& filename,
297 const gfx::Font& font,
298 int available_pixel_width) {
299 #if defined(OS_WIN)
300 string16 filename_utf16 = filename.value();
301 string16 extension = filename.Extension();
302 string16 rootname = filename.BaseName().RemoveExtension().value();
303 #elif defined(OS_POSIX)
304 string16 filename_utf16 = WideToUTF16(base::SysNativeMBToWide(
305 filename.value()));
306 string16 extension = WideToUTF16(base::SysNativeMBToWide(
307 filename.Extension()));
308 string16 rootname = WideToUTF16(base::SysNativeMBToWide(
309 filename.BaseName().RemoveExtension().value()));
310 #endif
311
312 int full_width = font.GetStringWidth(filename_utf16);
313 if (full_width <= available_pixel_width)
314 return base::i18n::GetDisplayStringInLTRDirectionality(filename_utf16);
315
316 if (rootname.empty() || extension.empty()) {
317 string16 elided_name = ElideText(filename_utf16, font,
318 available_pixel_width, false);
319 return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
320 }
321
322 int ext_width = font.GetStringWidth(extension);
323 int root_width = font.GetStringWidth(rootname);
324
325 // We may have trimmed the path.
326 if (root_width + ext_width <= available_pixel_width) {
327 string16 elided_name = rootname + extension;
328 return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
329 }
330
331 int available_root_width = available_pixel_width - ext_width;
332 string16 elided_name =
333 ElideText(rootname, font, available_root_width, false);
334 elided_name += extension;
335 return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
336 }
337
338 // This function adds an ellipsis at the end of the text if the text
339 // does not fit the given pixel width.
340 string16 ElideText(const string16& text,
341 const gfx::Font& font,
342 int available_pixel_width,
343 bool elide_in_middle) {
344 if (text.empty())
345 return text;
346
347 int current_text_pixel_width = font.GetStringWidth(text);
348
349 // Pango will return 0 width for absurdly long strings. Cut the string in
350 // half and try again.
351 // This is caused by an int overflow in Pango (specifically, in
352 // pango_glyph_string_extents_range). It's actually more subtle than just
353 // returning 0, since on super absurdly long strings, the int can wrap and
354 // return positive numbers again. Detecting that is probably not worth it
355 // (eliding way too much from a ridiculous string is probably still
356 // ridiculous), but we should check other widths for bogus values as well.
357 if (current_text_pixel_width <= 0 && !text.empty()) {
358 return ElideText(CutString(text, text.length() / 2, elide_in_middle, false),
359 font, available_pixel_width, false);
360 }
361
362 if (current_text_pixel_width <= available_pixel_width)
363 return text;
364
365 if (font.GetStringWidth(UTF8ToUTF16(kEllipsis)) > available_pixel_width)
366 return string16();
367
368 // Use binary search to compute the elided text.
369 size_t lo = 0;
370 size_t hi = text.length() - 1;
371 for (size_t guess = (lo + hi) / 2; guess != lo; guess = (lo + hi) / 2) {
372 // We check the length of the whole desired string at once to ensure we
373 // handle kerning/ligatures/etc. correctly.
374 int guess_length = font.GetStringWidth(
375 CutString(text, guess, elide_in_middle, true));
376 // Check again that we didn't hit a Pango width overflow. If so, cut the
377 // current string in half and start over.
378 if (guess_length <= 0) {
379 return ElideText(CutString(text, guess / 2, elide_in_middle, false),
380 font, available_pixel_width, elide_in_middle);
381 }
382 if (guess_length > available_pixel_width)
383 hi = guess;
384 else
385 lo = guess;
386 }
387
388 return CutString(text, lo, elide_in_middle, true);
389 }
390
391 // TODO(viettrungluu): convert |languages| to an |std::string|.
392 SortedDisplayURL::SortedDisplayURL(const GURL& url,
393 const std::wstring& languages) {
394 std::wstring host;
395 net::AppendFormattedHost(url, languages, &host, NULL, NULL);
396 sort_host_ = WideToUTF16Hack(host);
397 string16 host_minus_www = net::StripWWW(WideToUTF16Hack(host));
398 url_parse::Parsed parsed;
399 display_url_ = net::FormatUrl(url, WideToUTF8(languages),
400 net::kFormatUrlOmitAll, UnescapeRule::SPACES, &parsed, &prefix_end_,
401 NULL);
402 if (sort_host_.length() > host_minus_www.length()) {
403 prefix_end_ += sort_host_.length() - host_minus_www.length();
404 sort_host_.swap(host_minus_www);
405 }
406 }
407
408 SortedDisplayURL::SortedDisplayURL() {
409 }
410
411 SortedDisplayURL::~SortedDisplayURL() {
412 }
413
414 int SortedDisplayURL::Compare(const SortedDisplayURL& other,
415 icu::Collator* collator) const {
416 // Compare on hosts first. The host won't contain 'www.'.
417 UErrorCode compare_status = U_ZERO_ERROR;
418 UCollationResult host_compare_result = collator->compare(
419 static_cast<const UChar*>(sort_host_.c_str()),
420 static_cast<int>(sort_host_.length()),
421 static_cast<const UChar*>(other.sort_host_.c_str()),
422 static_cast<int>(other.sort_host_.length()),
423 compare_status);
424 DCHECK(U_SUCCESS(compare_status));
425 if (host_compare_result != 0)
426 return host_compare_result;
427
428 // Hosts match, compare on the portion of the url after the host.
429 string16 path = this->AfterHost();
430 string16 o_path = other.AfterHost();
431 compare_status = U_ZERO_ERROR;
432 UCollationResult path_compare_result = collator->compare(
433 static_cast<const UChar*>(path.c_str()),
434 static_cast<int>(path.length()),
435 static_cast<const UChar*>(o_path.c_str()),
436 static_cast<int>(o_path.length()),
437 compare_status);
438 DCHECK(U_SUCCESS(compare_status));
439 if (path_compare_result != 0)
440 return path_compare_result;
441
442 // Hosts and paths match, compare on the complete url. This'll push the www.
443 // ones to the end.
444 compare_status = U_ZERO_ERROR;
445 UCollationResult display_url_compare_result = collator->compare(
446 static_cast<const UChar*>(display_url_.c_str()),
447 static_cast<int>(display_url_.length()),
448 static_cast<const UChar*>(other.display_url_.c_str()),
449 static_cast<int>(other.display_url_.length()),
450 compare_status);
451 DCHECK(U_SUCCESS(compare_status));
452 return display_url_compare_result;
453 }
454
455 string16 SortedDisplayURL::AfterHost() const {
456 size_t slash_index = display_url_.find(sort_host_, prefix_end_);
457 if (slash_index == string16::npos) {
458 NOTREACHED();
459 return string16();
460 }
461 return display_url_.substr(slash_index + sort_host_.length());
462 }
463
464 bool ElideString(const std::wstring& input, int max_len, std::wstring* output) {
465 DCHECK_GE(max_len, 0);
466 if (static_cast<int>(input.length()) <= max_len) {
467 output->assign(input);
468 return false;
469 }
470
471 switch (max_len) {
472 case 0:
473 output->clear();
474 break;
475 case 1:
476 output->assign(input.substr(0, 1));
477 break;
478 case 2:
479 output->assign(input.substr(0, 2));
480 break;
481 case 3:
482 output->assign(input.substr(0, 1) + L"." +
483 input.substr(input.length() - 1));
484 break;
485 case 4:
486 output->assign(input.substr(0, 1) + L".." +
487 input.substr(input.length() - 1));
488 break;
489 default: {
490 int rstr_len = (max_len - 3) / 2;
491 int lstr_len = rstr_len + ((max_len - 3) % 2);
492 output->assign(input.substr(0, lstr_len) + L"..." +
493 input.substr(input.length() - rstr_len));
494 break;
495 }
496 }
497
498 return true;
499 }
500
501 } // namespace gfx
502
503 namespace {
504
505 // Internal class used to track progress of a rectangular string elide
506 // operation. Exists so the top-level ElideRectangleString() function
507 // can be broken into smaller methods sharing this state.
508 class RectangleString {
509 public:
510 RectangleString(size_t max_rows, size_t max_cols, string16 *output)
511 : max_rows_(max_rows),
512 max_cols_(max_cols),
513 current_row_(0),
514 current_col_(0),
515 suppressed_(false),
516 output_(output) {}
517
518 // Perform deferred initializions following creation. Must be called
519 // before any input can be added via AddString().
520 void Init() { output_->clear(); }
521
522 // Add an input string, reformatting to fit the desired dimensions.
523 // AddString() may be called multiple times to concatenate together
524 // multiple strings into the region (the current caller doesn't do
525 // this, however).
526 void AddString(const string16& input);
527
528 // Perform any deferred output processing. Must be called after the
529 // last AddString() call has occured.
530 bool Finalize();
531
532 private:
533 // Add a line to the rectangular region at the current position,
534 // either by itself or by breaking it into words.
535 void AddLine(const string16& line);
536
537 // Add a word to the rectangluar region at the current position,
538 // either by itelf or by breaking it into characters.
539 void AddWord(const string16& word);
540
541 // Add text to the output string if the rectangular boundaries
542 // have not been exceeded, advancing the current position.
543 void Append(const string16& string);
544
545 // Add a newline to the output string if the rectangular boundaries
546 // have not been exceeded, resetting the current position to the
547 // beginning of the next line.
548 void NewLine();
549
550 // Maximum number of rows allowed in the output string.
551 size_t max_rows_;
552
553 // Maximum number of characters allowed in the output string.
554 size_t max_cols_;
555
556 // Current row position, always incremented and may exceed max_rows_
557 // when the input can not fit in the region. We stop appending to
558 // the output string, however, when this condition occurs. In the
559 // future, we may want to expose this value to allow the caller to
560 // determine how many rows would actually be required to hold the
561 // formatted string.
562 size_t current_row_;
563
564 // Current character position, should never exceed max_cols_.
565 size_t current_col_;
566
567 // True when some of the input has been truncated.
568 bool suppressed_;
569
570 // String onto which the output is accumulated.
571 string16 *output_;
572 };
573
574 void RectangleString::AddString(const string16& input) {
575 base::BreakIterator lines(&input, base::BreakIterator::BREAK_NEWLINE);
576 if (lines.Init()) {
577 while (lines.Advance())
578 AddLine(lines.GetString());
579 } else {
580 NOTREACHED() << "BreakIterator (lines) init failed";
581 }
582 }
583
584 bool RectangleString::Finalize() {
585 if (suppressed_) {
586 output_->append(ASCIIToUTF16("..."));
587 return true;
588 }
589 return false;
590 }
591
592 void RectangleString::AddLine(const string16& line) {
593 if (line.length() < max_cols_) {
594 Append(line);
595 } else {
596 base::BreakIterator words(&line, base::BreakIterator::BREAK_SPACE);
597 if (words.Init()) {
598 while (words.Advance())
599 AddWord(words.GetString());
600 } else {
601 NOTREACHED() << "BreakIterator (words) init failed";
602 }
603 }
604 // Account for naturally-occuring newlines.
605 ++current_row_;
606 current_col_ = 0;
607 }
608
609 void RectangleString::AddWord(const string16& word) {
610 if (word.length() < max_cols_) {
611 // Word can be made to fit, no need to fragment it.
612 if (current_col_ + word.length() >= max_cols_)
613 NewLine();
614 Append(word);
615 } else {
616 // Word is so big that it must be fragmented.
617 int array_start = 0;
618 int char_start = 0;
619 base::UTF16CharIterator chars(&word);
620 while (!chars.end()) {
621 // When boundary is hit, add as much as will fit on this line.
622 if (current_col_ + (chars.char_pos() - char_start) >= max_cols_) {
623 Append(word.substr(array_start, chars.array_pos() - array_start));
624 NewLine();
625 array_start = chars.array_pos();
626 char_start = chars.char_pos();
627 }
628 chars.Advance();
629 }
630 // add last remaining fragment, if any.
631 if (array_start != chars.array_pos())
632 Append(word.substr(array_start, chars.array_pos() - array_start));
633 }
634 }
635
636 void RectangleString::Append(const string16& string) {
637 if (current_row_ < max_rows_)
638 output_->append(string);
639 else
640 suppressed_ = true;
641 current_col_ += string.length();
642 }
643
644 void RectangleString::NewLine() {
645 if (current_row_ < max_rows_)
646 output_->append(ASCIIToUTF16("\n"));
647 else
648 suppressed_ = true;
649 ++current_row_;
650 current_col_ = 0;
651 }
652
653 } // namespace
654
655 namespace gfx {
656
657 bool ElideRectangleString(const string16& input, size_t max_rows,
658 size_t max_cols, string16* output) {
659 RectangleString rect(max_rows, max_cols, output);
660 rect.Init();
661 rect.AddString(input);
662 return rect.Finalize();
663 }
664
665 } // namespace gfx
666
OLDNEW
« no previous file with comments | « app/text_elider.h ('k') | app/text_elider_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698