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

Side by Side Diff: chrome/common/gfx/text_elider.cc

Issue 113143: Move color_utils, text_elider, drag_utils, accessibility_types, standard_layo... (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: '' Created 11 years, 7 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 | « chrome/common/gfx/text_elider.h ('k') | chrome/common/gfx/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) 2006-2008 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 "app/gfx/chrome_font.h"
6 #include "base/file_path.h"
7 #include "base/string_util.h"
8 #include "base/sys_string_conversions.h"
9 #include "chrome/common/gfx/text_elider.h"
10 #include "chrome/common/pref_names.h"
11 #include "chrome/common/pref_service.h"
12 #include "googleurl/src/gurl.h"
13 #include "net/base/escape.h"
14 #include "net/base/net_util.h"
15 #include "net/base/registry_controlled_domain.h"
16
17 const wchar_t kEllipsis[] = L"\x2026";
18
19 namespace gfx {
20
21 // Appends the given part of the original URL to the output string formatted for
22 // the user. The given parsed structure will be updated. The host name formatter
23 // also takes the same accept languages component as ElideURL. |new_parsed| may
24 // be null.
25 static void AppendFormattedHost(const GURL& url,
26 const std::wstring& languages,
27 std::wstring* output,
28 url_parse::Parsed* new_parsed);
29
30 // Calls the unescaper for the substring |in_component| inside of the URL
31 // |spec|. The decoded string will be appended to |output| and the resulting
32 // range will be filled into |out_component|.
33 static void AppendFormattedComponent(const std::string& spec,
34 const url_parse::Component& in_component,
35 std::wstring* output,
36 url_parse::Component* out_component);
37
38 // This function takes a GURL object and elides it. It returns a string
39 // which composed of parts from subdomain, domain, path, filename and query.
40 // A "..." is added automatically at the end if the elided string is bigger
41 // than the available pixel width. For available pixel width = 0, a formatted,
42 // but un-elided, string is returned.
43 //
44 // TODO(pkasting): http://b/119635 This whole function gets
45 // kerning/ligatures/etc. issues potentially wrong by assuming that the width of
46 // a rendered string is always the sum of the widths of its substrings. Also I
47 // suspect it could be made simpler.
48 std::wstring ElideUrl(const GURL& url,
49 const ChromeFont& font,
50 int available_pixel_width,
51 const std::wstring& languages) {
52 // Get a formatted string and corresponding parsing of the url.
53 url_parse::Parsed parsed;
54 std::wstring url_string = GetCleanStringFromUrl(url, languages, &parsed,
55 NULL);
56 if (available_pixel_width <= 0)
57 return url_string;
58
59 // If non-standard or not file type, return plain eliding.
60 if (!(url.SchemeIsFile() || url.IsStandard()))
61 return ElideText(url_string, font, available_pixel_width);
62
63 // Now start eliding url_string to fit within available pixel width.
64 // Fist pass - check to see whether entire url_string fits.
65 int pixel_width_url_string = font.GetStringWidth(url_string);
66 if (available_pixel_width >= pixel_width_url_string)
67 return url_string;
68
69 // Get the path substring, including query and reference.
70 size_t path_start_index = parsed.path.begin;
71 size_t path_len = parsed.path.len;
72 std::wstring url_path_query_etc = url_string.substr(path_start_index);
73 std::wstring url_path = url_string.substr(path_start_index, path_len);
74
75 // Return general elided text if url minus the query fits.
76 std::wstring url_minus_query = url_string.substr(0, path_start_index +
77 path_len);
78 if (available_pixel_width >= font.GetStringWidth(url_minus_query))
79 return ElideText(url_string, font, available_pixel_width);
80
81 // Get Host.
82 std::wstring url_host = UTF8ToWide(url.host());
83
84 // Get domain and registry information from the URL.
85 std::wstring url_domain = UTF8ToWide(
86 net::RegistryControlledDomainService::GetDomainAndRegistry(url));
87 if (url_domain.empty())
88 url_domain = url_host;
89
90 // Add port if required.
91 if (!url.port().empty()){
92 url_host += L":" + UTF8ToWide(url.port());
93 url_domain += L":" + UTF8ToWide(url.port());
94 }
95
96 // Get sub domain.
97 std::wstring url_subdomain;
98 size_t domain_start_index = url_host.find(url_domain);
99 if (domain_start_index > 0)
100 url_subdomain = url_host.substr(0, domain_start_index);
101 if ((url_subdomain == L"www." || url_subdomain.empty() ||
102 url.SchemeIsFile())) {
103 url_subdomain.clear();
104 }
105
106 // If this is a file type, the path is now defined as everything after ":".
107 // For example, "C:/aa/aa/bb", the path is "/aa/bb/cc". Interesting, the
108 // domain is now C: - this is a nice hack for eliding to work pleasantly.
109 if (url.SchemeIsFile()) {
110 // Split the path string using ":"
111 std::vector<std::wstring> file_path_split;
112 SplitString(url_path, L':', &file_path_split);
113 if (file_path_split.size() > 1) { // File is of type "file:///C:/.."
114 url_host.clear();
115 url_domain.clear();
116 url_subdomain.clear();
117
118 url_host = url_domain = file_path_split.at(0).substr(1) + L":";
119 url_path_query_etc = url_path = file_path_split.at(1);
120 }
121 }
122
123 // Second Pass - remove scheme - the rest fits.
124 int pixel_width_url_host = font.GetStringWidth(url_host);
125 int pixel_width_url_path = font.GetStringWidth(url_path_query_etc);
126 if (available_pixel_width >=
127 pixel_width_url_host + pixel_width_url_path)
128 return url_host + url_path_query_etc;
129
130 // Third Pass: Subdomain, domain and entire path fits.
131 int pixel_width_url_domain = font.GetStringWidth(url_domain);
132 int pixel_width_url_subdomain = font.GetStringWidth(url_subdomain);
133 if (available_pixel_width >=
134 pixel_width_url_subdomain + pixel_width_url_domain +
135 pixel_width_url_path)
136 return url_subdomain + url_domain + url_path_query_etc;
137
138 // Query element.
139 std::wstring url_query;
140 const int pixel_width_dots_trailer = font.GetStringWidth(kEllipsis);
141 if (parsed.query.is_nonempty()) {
142 url_query = std::wstring(L"?") + url_string.substr(parsed.query.begin);
143 if (available_pixel_width >= (pixel_width_url_subdomain +
144 pixel_width_url_domain + pixel_width_url_path -
145 font.GetStringWidth(url_query))) {
146 return ElideText(url_subdomain + url_domain + url_path_query_etc, font,
147 available_pixel_width);
148 }
149 }
150
151 // Parse url_path using '/'.
152 std::vector<std::wstring> url_path_elements;
153 SplitString(url_path, L'/', &url_path_elements);
154
155 // Get filename - note that for a path ending with /
156 // such as www.google.com/intl/ads/, the file name is ads/.
157 int url_path_number_of_elements = static_cast<int> (url_path_elements.
158 size());
159 std::wstring url_filename;
160 if ((url_path_elements.at(url_path_number_of_elements - 1)).length() > 0) {
161 url_filename = *(url_path_elements.end()-1);
162 } else if (url_path_number_of_elements > 1) { // Path ends with a '/'.
163 url_filename = url_path_elements.at(url_path_number_of_elements - 2) +
164 L'/';
165 url_path_number_of_elements--;
166 }
167
168 const int kMaxNumberOfUrlPathElementsAllowed = 1024;
169 if (url_path_number_of_elements <= 1 ||
170 url_path_number_of_elements > kMaxNumberOfUrlPathElementsAllowed) {
171 // No path to elide, or too long of a path (could overflow in loop below)
172 // Just elide this as a text string.
173 return ElideText(url_subdomain + url_domain + url_path_query_etc, font,
174 available_pixel_width);
175 }
176
177 // Start eliding the path and replacing elements by "../".
178 std::wstring an_ellipsis_and_a_slash(kEllipsis);
179 an_ellipsis_and_a_slash += L'/';
180 int pixel_width_url_filename = font.GetStringWidth(url_filename);
181 int pixel_width_dot_dot_slash = font.GetStringWidth(an_ellipsis_and_a_slash);
182 int pixel_width_slash = font.GetStringWidth(L"/");
183 int pixel_width_url_path_elements[kMaxNumberOfUrlPathElementsAllowed];
184 for (int i = 0; i < url_path_number_of_elements; ++i) {
185 pixel_width_url_path_elements[i] =
186 font.GetStringWidth(url_path_elements.at(i));
187 }
188
189 // Check with both subdomain and domain.
190 std::wstring elided_path;
191 int pixel_width_elided_path;
192 for (int i = url_path_number_of_elements - 1; i >= 1; --i) {
193 // Add the initial elements of the path.
194 elided_path.clear();
195 pixel_width_elided_path = 0;
196 for (int j = 0; j < i; ++j) {
197 elided_path += url_path_elements.at(j) + L'/';
198 pixel_width_elided_path += pixel_width_url_path_elements[j] +
199 pixel_width_slash;
200 }
201
202 // Add url_file_name.
203 if (i == (url_path_number_of_elements - 1)) {
204 elided_path += url_filename;
205 pixel_width_elided_path += pixel_width_url_filename;
206 } else {
207 elided_path += an_ellipsis_and_a_slash + url_filename;
208 pixel_width_elided_path += pixel_width_dot_dot_slash +
209 pixel_width_url_filename;
210 }
211
212 if (available_pixel_width >=
213 pixel_width_url_subdomain + pixel_width_url_domain +
214 pixel_width_elided_path) {
215 return ElideText(url_subdomain + url_domain + elided_path + url_query,
216 font, available_pixel_width);
217 }
218 }
219
220 // Check with only domain.
221 // If a subdomain is present, add an ellipsis before domain.
222 // This is added only if the subdomain pixel width is larger than
223 // the pixel width of kEllipsis. Otherwise, subdomain remains,
224 // which means that this case has been resolved earlier.
225 std::wstring url_elided_domain = url_subdomain + url_domain;
226 int pixel_width_url_elided_domain = pixel_width_url_domain;
227 if (pixel_width_url_subdomain > pixel_width_dots_trailer) {
228 if (!url_subdomain.empty()) {
229 url_elided_domain = kEllipsis + url_domain;
230 pixel_width_url_elided_domain += pixel_width_dots_trailer;
231 } else {
232 url_elided_domain = url_domain;
233 }
234
235 for (int i = url_path_number_of_elements - 1; i >= 1; --i) {
236 // Add the initial elements of the path.
237 elided_path.clear();
238 pixel_width_elided_path = 0;
239 for (int j = 0; j < i; ++j) {
240 elided_path += url_path_elements.at(j) + L'/';
241 pixel_width_elided_path += pixel_width_url_path_elements[j] +
242 pixel_width_slash;
243 }
244
245 // Add url_file_name.
246 if (i == (url_path_number_of_elements - 1)) {
247 elided_path += url_filename;
248 pixel_width_elided_path += pixel_width_url_filename;
249 } else {
250 elided_path += an_ellipsis_and_a_slash + url_filename;
251 pixel_width_elided_path += pixel_width_dot_dot_slash +
252 pixel_width_url_filename;
253 }
254
255 if (available_pixel_width >=
256 pixel_width_url_elided_domain + pixel_width_elided_path) {
257 return ElideText(url_elided_domain + elided_path + url_query, font,
258 available_pixel_width);
259 }
260 }
261 }
262
263 // Return elided domain/../filename anyway.
264 std::wstring final_elided_url_string(url_elided_domain);
265 if ((available_pixel_width - font.GetStringWidth(url_elided_domain)) >
266 pixel_width_dot_dot_slash + pixel_width_dots_trailer +
267 font.GetStringWidth(L"UV")) // A hack to prevent trailing "../...".
268 final_elided_url_string += elided_path;
269 else
270 final_elided_url_string += url_path;
271
272 return ElideText(final_elided_url_string, font, available_pixel_width);
273 }
274
275 std::wstring ElideFilename(const FilePath& filename,
276 const ChromeFont& font,
277 int available_pixel_width) {
278 int full_width = font.GetStringWidth(filename.ToWStringHack());
279 if (full_width <= available_pixel_width)
280 return filename.ToWStringHack();
281
282 #if defined(OS_WIN)
283 std::wstring extension = filename.Extension();
284 #elif defined(OS_POSIX)
285 std::wstring extension = base::SysNativeMBToWide(filename.Extension());
286 #endif
287 std::wstring rootname =
288 filename.BaseName().RemoveExtension().ToWStringHack();
289
290 if (rootname.empty() || extension.empty())
291 return ElideText(filename.ToWStringHack(), font, available_pixel_width);
292
293 int ext_width = font.GetStringWidth(extension);
294 int root_width = font.GetStringWidth(rootname);
295
296 // We may have trimmed the path.
297 if (root_width + ext_width <= available_pixel_width)
298 return rootname + extension;
299
300 int available_root_width = available_pixel_width - ext_width;
301 return ElideText(rootname, font, available_root_width) + extension;
302 }
303
304 // This function adds an ellipsis at the end of the text if the text
305 // does not fit the given pixel width.
306 std::wstring ElideText(const std::wstring& text,
307 const ChromeFont& font,
308 int available_pixel_width){
309 if (text.empty())
310 return text;
311
312 int current_text_pixel_width = font.GetStringWidth(text);
313 if (current_text_pixel_width <= available_pixel_width)
314 return text;
315
316 if (font.GetStringWidth(kEllipsis) > available_pixel_width)
317 return std::wstring();
318
319 // Use binary search to compute the elided text.
320 size_t lo = 0;
321 size_t hi = text.length() - 1;
322 size_t guess = hi / 2;
323 while (lo < hi) {
324 // We check the length of the whole desired string at once to ensure we
325 // handle kerning/ligatures/etc. correctly.
326 std::wstring guess_str = text.substr(0, guess) + kEllipsis;
327 int guess_length = font.GetStringWidth(guess_str);
328 if (guess_length > available_pixel_width) {
329 if (hi == guess)
330 break;
331 hi = guess;
332 } else {
333 if (lo == guess)
334 break;
335 lo = guess;
336 }
337 guess = (lo + hi) / 2;
338 }
339
340 return text.substr(0, lo) + kEllipsis;
341 }
342
343 void AppendFormattedHost(const GURL& url,
344 const std::wstring& languages,
345 std::wstring* output,
346 url_parse::Parsed* new_parsed) {
347 const url_parse::Component& host =
348 url.parsed_for_possibly_invalid_spec().host;
349
350 if (host.is_nonempty()) {
351 // Handle possible IDN in the host name.
352 if (new_parsed)
353 new_parsed->host.begin = static_cast<int>(output->length());
354
355 const std::string& spec = url.possibly_invalid_spec();
356 DCHECK(host.begin >= 0 &&
357 ((spec.length() == 0 && host.begin == 0) ||
358 host.begin < static_cast<int>(spec.length())));
359 net::IDNToUnicode(&spec[host.begin], host.len, languages, output);
360
361 if (new_parsed) {
362 new_parsed->host.len =
363 static_cast<int>(output->length()) - new_parsed->host.begin;
364 }
365 } else if (new_parsed) {
366 new_parsed->host.reset();
367 }
368 }
369
370 void AppendFormattedComponent(const std::string& spec,
371 const url_parse::Component& in_component,
372 std::wstring* output,
373 url_parse::Component* out_component) {
374 if (in_component.is_nonempty()) {
375 out_component->begin = static_cast<int>(output->length());
376
377 output->append(UnescapeAndDecodeUTF8URLComponent(
378 spec.substr(in_component.begin, in_component.len),
379 UnescapeRule::NORMAL));
380
381 out_component->len =
382 static_cast<int>(output->length()) - out_component->begin;
383 } else {
384 out_component->reset();
385 }
386 }
387
388 std::wstring GetCleanStringFromUrl(const GURL& url,
389 const std::wstring& languages,
390 url_parse::Parsed* new_parsed,
391 size_t* prefix_end) {
392 url_parse::Parsed parsed_temp;
393 if (!new_parsed)
394 new_parsed = &parsed_temp;
395
396 std::wstring url_string;
397
398 // Check for empty URLs or 0 available text width.
399 if (url.is_empty()) {
400 if (prefix_end)
401 *prefix_end = 0;
402 return url_string;
403 }
404
405 // We handle both valid and invalid URLs (this will give us the spec
406 // regardless of validity).
407 const std::string& spec = url.possibly_invalid_spec();
408 const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
409
410 // Construct a new URL with the username and password fields removed. We
411 // don't want to display those to the user since they can be used for
412 // attacks, e.g. "http://google.com:search@evil.ru/"
413 //
414 // Copy everything before the host name we want (the scheme and the
415 // separators), minus the username start we computed above. These are ASCII.
416 int pre_end = parsed.CountCharactersBefore(
417 url_parse::Parsed::USERNAME, true);
418 for (int i = 0; i < pre_end; ++i)
419 url_string.push_back(spec[i]);
420 if (prefix_end)
421 *prefix_end = static_cast<size_t>(pre_end);
422 new_parsed->scheme = parsed.scheme;
423 new_parsed->username.reset();
424 new_parsed->password.reset();
425
426 AppendFormattedHost(url, languages, &url_string, new_parsed);
427
428 // Port.
429 if (parsed.port.is_nonempty()) {
430 url_string.push_back(':');
431 for (int i = parsed.port.begin; i < parsed.port.end(); ++i)
432 url_string.push_back(spec[i]);
433 }
434
435 // Path and query both get the same general unescape & convert treatment.
436 AppendFormattedComponent(spec, parsed.path, &url_string, &new_parsed->path);
437 if (parsed.query.is_valid())
438 url_string.push_back('?');
439 AppendFormattedComponent(spec, parsed.query, &url_string, &new_parsed->query);
440
441 // Reference is stored in valid, unescaped UTF-8, so we can just convert.
442 if (parsed.ref.is_valid()) {
443 url_string.push_back('#');
444 if (parsed.ref.len > 0)
445 url_string.append(UTF8ToWide(std::string(&spec[parsed.ref.begin],
446 parsed.ref.len)));
447 }
448
449 return url_string;
450 }
451
452 SortedDisplayURL::SortedDisplayURL(const GURL& url,
453 const std::wstring& languages) {
454 std::wstring host;
455 AppendFormattedHost(url, languages, &host, NULL);
456 sort_host_ = WideToUTF16Hack(host);
457 string16 host_minus_www = WideToUTF16Hack(net::StripWWW(host));
458 url_parse::Parsed parsed;
459 display_url_ = WideToUTF16Hack(GetCleanStringFromUrl(url, languages,
460 &parsed, &prefix_end_));
461 if (sort_host_.length() > host_minus_www.length()) {
462 prefix_end_ += sort_host_.length() - host_minus_www.length();
463 sort_host_.swap(host_minus_www);
464 }
465 }
466
467 int SortedDisplayURL::Compare(const SortedDisplayURL& other,
468 Collator* collator) const {
469 // Compare on hosts first. The host won't contain 'www.'.
470 UErrorCode compare_status = U_ZERO_ERROR;
471 UCollationResult host_compare_result = collator->compare(
472 static_cast<const UChar*>(sort_host_.c_str()),
473 static_cast<int>(sort_host_.length()),
474 static_cast<const UChar*>(other.sort_host_.c_str()),
475 static_cast<int>(other.sort_host_.length()),
476 compare_status);
477 DCHECK(U_SUCCESS(compare_status));
478 if (host_compare_result != 0)
479 return host_compare_result;
480
481 // Hosts match, compare on the portion of the url after the host.
482 string16 path = this->AfterHost();
483 string16 o_path = other.AfterHost();
484 compare_status = U_ZERO_ERROR;
485 UCollationResult path_compare_result = collator->compare(
486 static_cast<const UChar*>(path.c_str()),
487 static_cast<int>(path.length()),
488 static_cast<const UChar*>(o_path.c_str()),
489 static_cast<int>(o_path.length()),
490 compare_status);
491 DCHECK(U_SUCCESS(compare_status));
492 if (path_compare_result != 0)
493 return path_compare_result;
494
495 // Hosts and paths match, compare on the complete url. This'll push the www.
496 // ones to the end.
497 compare_status = U_ZERO_ERROR;
498 UCollationResult display_url_compare_result = collator->compare(
499 static_cast<const UChar*>(display_url_.c_str()),
500 static_cast<int>(display_url_.length()),
501 static_cast<const UChar*>(other.display_url_.c_str()),
502 static_cast<int>(other.display_url_.length()),
503 compare_status);
504 DCHECK(U_SUCCESS(compare_status));
505 return display_url_compare_result;
506 }
507
508 string16 SortedDisplayURL::AfterHost() const {
509 size_t slash_index = display_url_.find(sort_host_, prefix_end_);
510 if (slash_index == string16::npos) {
511 NOTREACHED();
512 return string16();
513 }
514 return display_url_.substr(slash_index + sort_host_.length());
515 }
516
517 } // namespace gfx.
OLDNEW
« no previous file with comments | « chrome/common/gfx/text_elider.h ('k') | chrome/common/gfx/text_elider_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698