text_elider.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. // Copyright (c) 2012 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. // This file implements utility functions for eliding and formatting UI text.
  6. //
  7. // Note that several of the functions declared in text_elider.h are implemented
  8. // in this file using helper classes in an unnamed namespace.
  9. #include "ui/gfx/text_elider.h"
  10. #include <stdint.h>
  11. #include <algorithm>
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. #include "base/check_op.h"
  16. #include "base/files/file_path.h"
  17. #include "base/i18n/break_iterator.h"
  18. #include "base/i18n/char_iterator.h"
  19. #include "base/i18n/rtl.h"
  20. #include "base/memory/raw_ptr.h"
  21. #include "base/notreached.h"
  22. #include "base/strings/string_split.h"
  23. #include "base/strings/string_util.h"
  24. #include "base/strings/sys_string_conversions.h"
  25. #include "base/strings/utf_string_conversions.h"
  26. #include "build/build_config.h"
  27. #include "third_party/icu/source/common/unicode/rbbi.h"
  28. #include "third_party/icu/source/common/unicode/uloc.h"
  29. #include "third_party/icu/source/common/unicode/umachine.h"
  30. #include "ui/gfx/font_list.h"
  31. #include "ui/gfx/geometry/rect_conversions.h"
  32. #include "ui/gfx/render_text.h"
  33. #include "ui/gfx/text_utils.h"
  34. using base::ASCIIToUTF16;
  35. using base::UTF8ToUTF16;
  36. using base::WideToUTF16;
  37. namespace gfx {
  38. namespace {
  39. #if BUILDFLAG(IS_IOS)
  40. // The returned string will have at least one character besides the ellipsis
  41. // on either side of '@'; if that's impossible, a single ellipsis is returned.
  42. // If possible, only the username is elided. Otherwise, the domain is elided
  43. // in the middle, splitting available width equally with the elided username.
  44. // If the username is short enough that it doesn't need half the available
  45. // width, the elided domain will occupy that extra width.
  46. std::u16string ElideEmail(const std::u16string& email,
  47. const FontList& font_list,
  48. float available_pixel_width) {
  49. if (GetStringWidthF(email, font_list) <= available_pixel_width)
  50. return email;
  51. // Split the email into its local-part (username) and domain-part. The email
  52. // spec allows for @ symbols in the username under some special requirements,
  53. // but not in the domain part, so splitting at the last @ symbol is safe.
  54. const size_t split_index = email.find_last_of('@');
  55. DCHECK_NE(split_index, std::u16string::npos);
  56. std::u16string username = email.substr(0, split_index);
  57. std::u16string domain = email.substr(split_index + 1);
  58. DCHECK(!username.empty());
  59. DCHECK(!domain.empty());
  60. // Subtract the @ symbol from the available width as it is mandatory.
  61. const std::u16string kAtSignUTF16 = u"@";
  62. available_pixel_width -= GetStringWidthF(kAtSignUTF16, font_list);
  63. // Check whether eliding the domain is necessary: if eliding the username
  64. // is sufficient, the domain will not be elided.
  65. const float full_username_width = GetStringWidthF(username, font_list);
  66. const float available_domain_width =
  67. available_pixel_width -
  68. std::min(full_username_width,
  69. GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16,
  70. font_list));
  71. if (GetStringWidthF(domain, font_list) > available_domain_width) {
  72. // Elide the domain so that it only takes half of the available width.
  73. // Should the username not need all the width available in its half, the
  74. // domain will occupy the leftover width.
  75. // If |desired_domain_width| is greater than |available_domain_width|: the
  76. // minimal username elision allowed by the specifications will not fit; thus
  77. // |desired_domain_width| must be <= |available_domain_width| at all cost.
  78. const float desired_domain_width =
  79. std::min(available_domain_width,
  80. std::max(available_pixel_width - full_username_width,
  81. available_pixel_width / 2));
  82. domain = ElideText(domain, font_list, desired_domain_width, ELIDE_MIDDLE);
  83. // Failing to elide the domain such that at least one character remains
  84. // (other than the ellipsis itself) remains: return a single ellipsis.
  85. if (domain.length() <= 1U)
  86. return std::u16string(kEllipsisUTF16);
  87. }
  88. // Fit the username in the remaining width (at this point the elided username
  89. // is guaranteed to fit with at least one character remaining given all the
  90. // precautions taken earlier).
  91. available_pixel_width -= GetStringWidthF(domain, font_list);
  92. username = ElideText(username, font_list, available_pixel_width, ELIDE_TAIL);
  93. return username + kAtSignUTF16 + domain;
  94. }
  95. #endif
  96. bool GetDefaultWhitespaceElision(bool elide_in_middle,
  97. bool elide_at_beginning) {
  98. return elide_at_beginning || !elide_in_middle;
  99. }
  100. } // namespace
  101. // U+2026 in utf8
  102. const char kEllipsis[] = "\xE2\x80\xA6";
  103. const char16_t kEllipsisUTF16[] = {0x2026, 0};
  104. const char16_t kForwardSlash = '/';
  105. StringSlicer::StringSlicer(const std::u16string& text,
  106. const std::u16string& ellipsis,
  107. bool elide_in_middle,
  108. bool elide_at_beginning,
  109. absl::optional<bool> elide_whitespace)
  110. : text_(text),
  111. ellipsis_(ellipsis),
  112. elide_in_middle_(elide_in_middle),
  113. elide_at_beginning_(elide_at_beginning),
  114. elide_whitespace_(elide_whitespace
  115. ? *elide_whitespace
  116. : GetDefaultWhitespaceElision(elide_in_middle,
  117. elide_at_beginning)) {
  118. }
  119. std::u16string StringSlicer::CutString(size_t length,
  120. bool insert_ellipsis) const {
  121. const std::u16string ellipsis_text =
  122. insert_ellipsis ? ellipsis_ : std::u16string();
  123. // For visual consistency, when eliding at either end of the string, excess
  124. // space should be trimmed from the text to return "Foo bar..." instead of
  125. // "Foo bar ...".
  126. if (elide_at_beginning_) {
  127. return ellipsis_text +
  128. text_.substr(FindValidBoundaryAfter(text_, text_.length() - length,
  129. elide_whitespace_));
  130. }
  131. if (!elide_in_middle_) {
  132. return text_.substr(
  133. 0, FindValidBoundaryBefore(text_, length, elide_whitespace_)) +
  134. ellipsis_text;
  135. }
  136. // Put the extra character, if any, before the cut.
  137. // Extra space around the ellipses will *not* be trimmed for |elide_in_middle|
  138. // mode (we can change this later). The reason is that when laying out a
  139. // column of middle-trimmed lines of text (such as a list of paths), the
  140. // desired appearance is to be fully justified and the elipses should more or
  141. // less line up; eliminating space would make the text look more ragged.
  142. const size_t half_length = length / 2;
  143. const size_t prefix_length =
  144. FindValidBoundaryBefore(text_, length - half_length, elide_whitespace_);
  145. const size_t suffix_start = FindValidBoundaryAfter(
  146. text_, text_.length() - half_length, elide_whitespace_);
  147. return text_.substr(0, prefix_length) + ellipsis_text +
  148. text_.substr(suffix_start);
  149. }
  150. std::u16string ElideFilename(const base::FilePath& filename,
  151. const FontList& font_list,
  152. float available_pixel_width) {
  153. #if BUILDFLAG(IS_WIN)
  154. std::u16string filename_utf16 = WideToUTF16(filename.value());
  155. std::u16string extension = WideToUTF16(filename.Extension());
  156. std::u16string rootname =
  157. WideToUTF16(filename.BaseName().RemoveExtension().value());
  158. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  159. std::u16string filename_utf16 =
  160. WideToUTF16(base::SysNativeMBToWide(filename.value()));
  161. std::u16string extension =
  162. WideToUTF16(base::SysNativeMBToWide(filename.Extension()));
  163. std::u16string rootname = WideToUTF16(
  164. base::SysNativeMBToWide(filename.BaseName().RemoveExtension().value()));
  165. #endif
  166. const float full_width = GetStringWidthF(filename_utf16, font_list);
  167. if (full_width <= available_pixel_width)
  168. return base::i18n::GetDisplayStringInLTRDirectionality(filename_utf16);
  169. if (rootname.empty() || extension.empty()) {
  170. const std::u16string elided_name =
  171. ElideText(filename_utf16, font_list, available_pixel_width, ELIDE_TAIL);
  172. return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
  173. }
  174. const float ext_width = GetStringWidthF(extension, font_list);
  175. const float root_width = GetStringWidthF(rootname, font_list);
  176. // We may have trimmed the path.
  177. if (root_width + ext_width <= available_pixel_width) {
  178. const std::u16string elided_name = rootname + extension;
  179. return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
  180. }
  181. if (ext_width >= available_pixel_width) {
  182. const std::u16string elided_name = ElideText(
  183. rootname + extension, font_list, available_pixel_width, ELIDE_MIDDLE);
  184. return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
  185. }
  186. float available_root_width = available_pixel_width - ext_width;
  187. std::u16string elided_name =
  188. ElideText(rootname, font_list, available_root_width, ELIDE_TAIL);
  189. elided_name += extension;
  190. return base::i18n::GetDisplayStringInLTRDirectionality(elided_name);
  191. }
  192. std::u16string ElideText(const std::u16string& text,
  193. const FontList& font_list,
  194. float available_pixel_width,
  195. ElideBehavior behavior) {
  196. #if !BUILDFLAG(IS_IOS)
  197. DCHECK_NE(behavior, FADE_TAIL);
  198. std::unique_ptr<RenderText> render_text = RenderText::CreateRenderText();
  199. render_text->SetCursorEnabled(false);
  200. render_text->SetFontList(font_list);
  201. available_pixel_width = std::ceil(available_pixel_width);
  202. render_text->SetDisplayRect(
  203. gfx::ToEnclosingRect(gfx::RectF(gfx::SizeF(available_pixel_width, 1))));
  204. render_text->SetElideBehavior(behavior);
  205. render_text->SetText(text);
  206. return render_text->GetDisplayText();
  207. #else
  208. DCHECK_NE(behavior, FADE_TAIL);
  209. if (text.empty() || behavior == FADE_TAIL || behavior == NO_ELIDE ||
  210. GetStringWidthF(text, font_list) <= available_pixel_width) {
  211. return text;
  212. }
  213. if (behavior == ELIDE_EMAIL)
  214. return ElideEmail(text, font_list, available_pixel_width);
  215. const bool elide_in_middle = (behavior == ELIDE_MIDDLE);
  216. const bool elide_at_beginning = (behavior == ELIDE_HEAD);
  217. const bool insert_ellipsis = (behavior != TRUNCATE);
  218. const std::u16string ellipsis = std::u16string(kEllipsisUTF16);
  219. StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning);
  220. if (insert_ellipsis &&
  221. GetStringWidthF(ellipsis, font_list) > available_pixel_width)
  222. return std::u16string();
  223. // Use binary search to compute the elided text.
  224. size_t lo = 0;
  225. size_t hi = text.length() - 1;
  226. size_t guess;
  227. std::u16string cut;
  228. for (guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
  229. // We check the width of the whole desired string at once to ensure we
  230. // handle kerning/ligatures/etc. correctly.
  231. // TODO(skanuj) : Handle directionality of ellipsis based on adjacent
  232. // characters. See crbug.com/327963.
  233. cut = slicer.CutString(guess, insert_ellipsis);
  234. const float guess_width = GetStringWidthF(cut, font_list);
  235. if (guess_width == available_pixel_width)
  236. break;
  237. if (guess_width > available_pixel_width) {
  238. hi = guess - 1;
  239. // Move back on the loop terminating condition when the guess is too wide.
  240. if (hi < lo)
  241. lo = hi;
  242. } else {
  243. lo = guess + 1;
  244. }
  245. }
  246. return cut;
  247. #endif
  248. }
  249. bool ElideString(const std::u16string& input,
  250. size_t max_len,
  251. std::u16string* output) {
  252. if (input.length() <= max_len) {
  253. output->assign(input);
  254. return false;
  255. }
  256. switch (max_len) {
  257. case 0:
  258. output->clear();
  259. break;
  260. case 1:
  261. output->assign(input.substr(0, 1));
  262. break;
  263. case 2:
  264. output->assign(input.substr(0, 2));
  265. break;
  266. case 3:
  267. output->assign(input.substr(0, 1) + u"." +
  268. input.substr(input.length() - 1));
  269. break;
  270. case 4:
  271. output->assign(input.substr(0, 1) + u".." +
  272. input.substr(input.length() - 1));
  273. break;
  274. default: {
  275. size_t rstr_len = (max_len - 3) / 2;
  276. size_t lstr_len = rstr_len + ((max_len - 3) % 2);
  277. output->assign(input.substr(0, lstr_len) + u"..." +
  278. input.substr(input.length() - rstr_len));
  279. break;
  280. }
  281. }
  282. return true;
  283. }
  284. namespace {
  285. // Internal class used to track progress of a rectangular string elide
  286. // operation. Exists so the top-level ElideRectangleString() function
  287. // can be broken into smaller methods sharing this state.
  288. class RectangleString {
  289. public:
  290. RectangleString(size_t max_rows,
  291. size_t max_cols,
  292. bool strict,
  293. std::u16string* output)
  294. : max_rows_(max_rows),
  295. max_cols_(max_cols),
  296. current_row_(0),
  297. current_col_(0),
  298. strict_(strict),
  299. suppressed_(false),
  300. output_(output) {}
  301. RectangleString(const RectangleString&) = delete;
  302. RectangleString& operator=(const RectangleString&) = delete;
  303. // Perform deferred initializations following creation. Must be called
  304. // before any input can be added via AddString().
  305. void Init() { output_->clear(); }
  306. // Add an input string, reformatting to fit the desired dimensions.
  307. // AddString() may be called multiple times to concatenate together
  308. // multiple strings into the region (the current caller doesn't do
  309. // this, however).
  310. void AddString(const std::u16string& input);
  311. // Perform any deferred output processing. Must be called after the
  312. // last AddString() call has occurred.
  313. bool Finalize();
  314. private:
  315. // Add a line to the rectangular region at the current position,
  316. // either by itself or by breaking it into words.
  317. void AddLine(const std::u16string& line);
  318. // Add a word to the rectangular region at the current position,
  319. // either by itself or by breaking it into characters.
  320. void AddWord(const std::u16string& word);
  321. // Add text to the output string if the rectangular boundaries
  322. // have not been exceeded, advancing the current position.
  323. void Append(const std::u16string& string);
  324. // Set the current position to the beginning of the next line. If
  325. // |output| is true, add a newline to the output string if the rectangular
  326. // boundaries have not been exceeded. If |output| is false, we assume
  327. // some other mechanism will (likely) do similar breaking after the fact.
  328. void NewLine(bool output);
  329. // Maximum number of rows allowed in the output string.
  330. size_t max_rows_;
  331. // Maximum number of characters allowed in the output string.
  332. size_t max_cols_;
  333. // Current row position, always incremented and may exceed max_rows_
  334. // when the input can not fit in the region. We stop appending to
  335. // the output string, however, when this condition occurs. In the
  336. // future, we may want to expose this value to allow the caller to
  337. // determine how many rows would actually be required to hold the
  338. // formatted string.
  339. size_t current_row_;
  340. // Current character position, should never exceed max_cols_.
  341. size_t current_col_;
  342. // True when we do whitespace to newline conversions ourselves.
  343. bool strict_;
  344. // True when some of the input has been truncated.
  345. bool suppressed_;
  346. // String onto which the output is accumulated.
  347. raw_ptr<std::u16string> output_;
  348. };
  349. void RectangleString::AddString(const std::u16string& input) {
  350. base::i18n::BreakIterator lines(input,
  351. base::i18n::BreakIterator::BREAK_NEWLINE);
  352. if (lines.Init()) {
  353. while (lines.Advance())
  354. AddLine(lines.GetString());
  355. } else {
  356. NOTREACHED() << "BreakIterator (lines) init failed";
  357. }
  358. }
  359. bool RectangleString::Finalize() {
  360. if (suppressed_) {
  361. output_->append(u"...");
  362. return true;
  363. }
  364. return false;
  365. }
  366. void RectangleString::AddLine(const std::u16string& line) {
  367. if (line.length() < max_cols_) {
  368. Append(line);
  369. } else {
  370. base::i18n::BreakIterator words(line,
  371. base::i18n::BreakIterator::BREAK_SPACE);
  372. if (words.Init()) {
  373. while (words.Advance())
  374. AddWord(words.GetString());
  375. } else {
  376. NOTREACHED() << "BreakIterator (words) init failed";
  377. }
  378. }
  379. // Account for naturally-occuring newlines.
  380. ++current_row_;
  381. current_col_ = 0;
  382. }
  383. void RectangleString::AddWord(const std::u16string& word) {
  384. if (word.length() < max_cols_) {
  385. // Word can be made to fit, no need to fragment it.
  386. if (current_col_ + word.length() >= max_cols_)
  387. NewLine(strict_);
  388. Append(word);
  389. } else {
  390. // Word is so big that it must be fragmented.
  391. size_t array_start = 0;
  392. int char_start = 0;
  393. base::i18n::UTF16CharIterator chars(word);
  394. for (; !chars.end(); chars.Advance()) {
  395. // When boundary is hit, add as much as will fit on this line.
  396. if (current_col_ + (chars.char_offset() - char_start) >= max_cols_) {
  397. Append(word.substr(array_start, chars.array_pos() - array_start));
  398. NewLine(true);
  399. array_start = chars.array_pos();
  400. char_start = chars.char_offset();
  401. }
  402. }
  403. // Add the last remaining fragment, if any.
  404. if (array_start != chars.array_pos())
  405. Append(word.substr(array_start, chars.array_pos() - array_start));
  406. }
  407. }
  408. void RectangleString::Append(const std::u16string& string) {
  409. if (current_row_ < max_rows_)
  410. output_->append(string);
  411. else
  412. suppressed_ = true;
  413. current_col_ += string.length();
  414. }
  415. void RectangleString::NewLine(bool output) {
  416. if (current_row_ < max_rows_) {
  417. if (output)
  418. output_->append(u"\n");
  419. } else {
  420. suppressed_ = true;
  421. }
  422. ++current_row_;
  423. current_col_ = 0;
  424. }
  425. // Internal class used to track progress of a rectangular text elide
  426. // operation. Exists so the top-level ElideRectangleText() function
  427. // can be broken into smaller methods sharing this state.
  428. class RectangleText {
  429. public:
  430. RectangleText(const FontList& font_list,
  431. float available_pixel_width,
  432. int available_pixel_height,
  433. WordWrapBehavior wrap_behavior,
  434. std::vector<std::u16string>* lines)
  435. : font_list_(font_list),
  436. line_height_(font_list.GetHeight()),
  437. available_pixel_width_(available_pixel_width),
  438. available_pixel_height_(available_pixel_height),
  439. wrap_behavior_(wrap_behavior),
  440. lines_(lines) {}
  441. RectangleText(const RectangleText&) = delete;
  442. RectangleText& operator=(const RectangleText&) = delete;
  443. // Perform deferred initializations following creation. Must be called
  444. // before any input can be added via AddString().
  445. void Init() { lines_->clear(); }
  446. // Add an input string, reformatting to fit the desired dimensions.
  447. // AddString() may be called multiple times to concatenate together
  448. // multiple strings into the region (the current caller doesn't do
  449. // this, however).
  450. void AddString(const std::u16string& input);
  451. // Perform any deferred output processing. Must be called after the last
  452. // AddString() call has occurred. Returns a combination of
  453. // |ReformattingResultFlags| indicating whether the given width or height was
  454. // insufficient, leading to elision or truncation.
  455. int Finalize();
  456. private:
  457. // Add a line to the rectangular region at the current position,
  458. // either by itself or by breaking it into words.
  459. void AddLine(const std::u16string& line);
  460. // Wrap the specified word across multiple lines.
  461. int WrapWord(const std::u16string& word);
  462. // Add a long word - wrapping, eliding or truncating per the wrap behavior.
  463. int AddWordOverflow(const std::u16string& word);
  464. // Add a word to the rectangular region at the current position.
  465. int AddWord(const std::u16string& word);
  466. // Append the specified |text| to the current output line, incrementing the
  467. // running width by the specified amount. This is an optimization over
  468. // |AddToCurrentLine()| when |text_width| is already known.
  469. void AddToCurrentLineWithWidth(const std::u16string& text, float text_width);
  470. // Append the specified |text| to the current output line.
  471. void AddToCurrentLine(const std::u16string& text);
  472. // Set the current position to the beginning of the next line.
  473. bool NewLine();
  474. // The font list used for measuring text width.
  475. const FontList& font_list_;
  476. // The height of each line of text.
  477. const int line_height_;
  478. // The number of pixels of available width in the rectangle.
  479. const float available_pixel_width_;
  480. // The number of pixels of available height in the rectangle.
  481. const int available_pixel_height_;
  482. // The wrap behavior for words that are too long to fit on a single line.
  483. const WordWrapBehavior wrap_behavior_;
  484. // The current running width.
  485. float current_width_ = 0;
  486. // The current running height.
  487. int current_height_ = 0;
  488. // The current line of text.
  489. std::u16string current_line_;
  490. // Indicates whether the last line ended with \n.
  491. bool last_line_ended_in_lf_ = false;
  492. // The output vector of lines.
  493. raw_ptr<std::vector<std::u16string>> lines_;
  494. // Indicates whether a word was so long that it had to be truncated or elided
  495. // to fit the available width.
  496. bool insufficient_width_ = false;
  497. // Indicates whether there were too many lines for the available height.
  498. bool insufficient_height_ = false;
  499. // Indicates whether the very first word was truncated.
  500. bool first_word_truncated_ = false;
  501. };
  502. void RectangleText::AddString(const std::u16string& input) {
  503. base::i18n::BreakIterator lines(input,
  504. base::i18n::BreakIterator::BREAK_NEWLINE);
  505. if (lines.Init()) {
  506. while (!insufficient_height_ && lines.Advance()) {
  507. std::u16string line = lines.GetString();
  508. // The BREAK_NEWLINE iterator will keep the trailing newline character,
  509. // except in the case of the last line, which may not have one. Remove
  510. // the newline character, if it exists.
  511. last_line_ended_in_lf_ = !line.empty() && line.back() == '\n';
  512. if (last_line_ended_in_lf_)
  513. line.resize(line.length() - 1);
  514. AddLine(line);
  515. }
  516. } else {
  517. NOTREACHED() << "BreakIterator (lines) init failed";
  518. }
  519. }
  520. int RectangleText::Finalize() {
  521. // Remove trailing whitespace from the last line or remove the last line
  522. // completely, if it's just whitespace.
  523. if (!insufficient_height_ && !lines_->empty()) {
  524. base::TrimWhitespace(lines_->back(), base::TRIM_TRAILING, &lines_->back());
  525. if (lines_->back().empty() && !last_line_ended_in_lf_)
  526. lines_->pop_back();
  527. }
  528. if (last_line_ended_in_lf_)
  529. lines_->push_back(std::u16string());
  530. return (insufficient_width_ ? INSUFFICIENT_SPACE_HORIZONTAL : 0) |
  531. (insufficient_height_ ? INSUFFICIENT_SPACE_VERTICAL : 0) |
  532. (first_word_truncated_ ? INSUFFICIENT_SPACE_FOR_FIRST_WORD : 0);
  533. }
  534. void RectangleText::AddLine(const std::u16string& line) {
  535. const float line_width = GetStringWidthF(line, font_list_);
  536. if (line_width <= available_pixel_width_) {
  537. AddToCurrentLineWithWidth(line, line_width);
  538. } else {
  539. // Iterate over positions that are valid to break the line at. In general,
  540. // these are word boundaries but after any punctuation following the word.
  541. base::i18n::BreakIterator words(line,
  542. base::i18n::BreakIterator::BREAK_LINE);
  543. if (words.Init()) {
  544. while (words.Advance()) {
  545. const bool truncate = !current_line_.empty();
  546. const std::u16string& word = words.GetString();
  547. const int lines_added = AddWord(word);
  548. if (lines_added) {
  549. if (truncate) {
  550. // Trim trailing whitespace from the line that was added.
  551. const size_t new_line = lines_->size() - lines_added;
  552. base::TrimWhitespace(lines_->at(new_line), base::TRIM_TRAILING,
  553. &lines_->at(new_line));
  554. }
  555. if (base::ContainsOnlyChars(word, base::kWhitespaceUTF16)) {
  556. // Skip the first space if the previous line was carried over.
  557. current_width_ = 0;
  558. current_line_.clear();
  559. }
  560. }
  561. }
  562. } else {
  563. NOTREACHED() << "BreakIterator (words) init failed";
  564. }
  565. }
  566. // Account for naturally-occuring newlines.
  567. NewLine();
  568. }
  569. int RectangleText::WrapWord(const std::u16string& word) {
  570. // Word is so wide that it must be fragmented.
  571. std::u16string text = word;
  572. int lines_added = 0;
  573. bool first_fragment = true;
  574. while (!insufficient_height_ && !text.empty()) {
  575. std::u16string fragment =
  576. ElideText(text, font_list_, available_pixel_width_, TRUNCATE);
  577. // At least one character has to be added at every line, even if the
  578. // available space is too small.
  579. if (fragment.empty())
  580. fragment = text.substr(0, 1);
  581. if (!first_fragment && NewLine())
  582. lines_added++;
  583. AddToCurrentLine(fragment);
  584. text = text.substr(fragment.length());
  585. first_fragment = false;
  586. }
  587. return lines_added;
  588. }
  589. int RectangleText::AddWordOverflow(const std::u16string& word) {
  590. int lines_added = 0;
  591. // Unless this is the very first word, put it on a new line.
  592. if (!current_line_.empty()) {
  593. if (!NewLine())
  594. return 0;
  595. lines_added++;
  596. } else if (lines_->empty()) {
  597. first_word_truncated_ = true;
  598. }
  599. if (wrap_behavior_ == IGNORE_LONG_WORDS) {
  600. current_line_ = word;
  601. current_width_ = available_pixel_width_;
  602. } else if (wrap_behavior_ == WRAP_LONG_WORDS) {
  603. lines_added += WrapWord(word);
  604. } else {
  605. const ElideBehavior elide_behavior =
  606. (wrap_behavior_ == ELIDE_LONG_WORDS ? ELIDE_TAIL : TRUNCATE);
  607. const std::u16string elided_word =
  608. ElideText(word, font_list_, available_pixel_width_, elide_behavior);
  609. AddToCurrentLine(elided_word);
  610. insufficient_width_ = true;
  611. }
  612. return lines_added;
  613. }
  614. int RectangleText::AddWord(const std::u16string& word) {
  615. int lines_added = 0;
  616. std::u16string trimmed;
  617. base::TrimWhitespace(word, base::TRIM_TRAILING, &trimmed);
  618. const float trimmed_width = GetStringWidthF(trimmed, font_list_);
  619. if (trimmed_width <= available_pixel_width_) {
  620. // Word can be made to fit, no need to fragment it.
  621. if ((current_width_ + trimmed_width > available_pixel_width_) && NewLine())
  622. lines_added++;
  623. // Append the non-trimmed word, in case more words are added after.
  624. AddToCurrentLine(word);
  625. } else {
  626. lines_added = AddWordOverflow(wrap_behavior_ == IGNORE_LONG_WORDS ?
  627. trimmed : word);
  628. }
  629. return lines_added;
  630. }
  631. void RectangleText::AddToCurrentLine(const std::u16string& text) {
  632. AddToCurrentLineWithWidth(text, GetStringWidthF(text, font_list_));
  633. }
  634. void RectangleText::AddToCurrentLineWithWidth(const std::u16string& text,
  635. float text_width) {
  636. if (current_height_ >= available_pixel_height_) {
  637. insufficient_height_ = true;
  638. return;
  639. }
  640. current_line_.append(text);
  641. current_width_ += text_width;
  642. }
  643. bool RectangleText::NewLine() {
  644. bool line_added = false;
  645. if (current_height_ < available_pixel_height_) {
  646. lines_->push_back(current_line_);
  647. current_line_.clear();
  648. line_added = true;
  649. } else {
  650. insufficient_height_ = true;
  651. }
  652. current_height_ += line_height_;
  653. current_width_ = 0;
  654. return line_added;
  655. }
  656. } // namespace
  657. bool ElideRectangleString(const std::u16string& input,
  658. size_t max_rows,
  659. size_t max_cols,
  660. bool strict,
  661. std::u16string* output) {
  662. RectangleString rect(max_rows, max_cols, strict, output);
  663. rect.Init();
  664. rect.AddString(input);
  665. return rect.Finalize();
  666. }
  667. int ElideRectangleText(const std::u16string& input,
  668. const FontList& font_list,
  669. float available_pixel_width,
  670. int available_pixel_height,
  671. WordWrapBehavior wrap_behavior,
  672. std::vector<std::u16string>* lines) {
  673. RectangleText rect(font_list, available_pixel_width, available_pixel_height,
  674. wrap_behavior, lines);
  675. rect.Init();
  676. rect.AddString(input);
  677. return rect.Finalize();
  678. }
  679. std::u16string TruncateString(const std::u16string& string,
  680. size_t length,
  681. BreakType break_type) {
  682. const bool word_break = break_type == WORD_BREAK;
  683. DCHECK(word_break || (break_type == CHARACTER_BREAK));
  684. if (string.size() <= length)
  685. return string; // No need to elide.
  686. if (length == 0)
  687. return std::u16string(); // No room for anything, even an ellipsis.
  688. // Added to the end of strings that are too big.
  689. static const char16_t kElideString[] = {0x2026, 0};
  690. if (length == 1)
  691. return kElideString; // Only room for an ellipsis.
  692. int32_t index = static_cast<int32_t>(length - 1);
  693. if (word_break) {
  694. // Use a word iterator to find the first boundary.
  695. UErrorCode status = U_ZERO_ERROR;
  696. std::unique_ptr<icu::BreakIterator> bi(
  697. icu::RuleBasedBreakIterator::createWordInstance(
  698. icu::Locale::getDefault(), status));
  699. if (U_FAILURE(status))
  700. return string.substr(0, length - 1) + kElideString;
  701. icu::UnicodeString bi_text(string.c_str());
  702. bi->setText(bi_text);
  703. index = bi->preceding(static_cast<int32_t>(length));
  704. if (index == icu::BreakIterator::DONE || index == 0) {
  705. // We either found no valid word break at all, or one right at the
  706. // beginning of the string. Go back to the end; we'll have to break in the
  707. // middle of a word.
  708. index = static_cast<int32_t>(length - 1);
  709. }
  710. }
  711. // By this point, |index| should point at the character that's a candidate for
  712. // replacing with an ellipsis. Use a character iterator to check previous
  713. // characters and stop as soon as we find a previous non-whitespace character.
  714. icu::StringCharacterIterator char_iterator(string.c_str());
  715. char_iterator.setIndex(index);
  716. while (char_iterator.hasPrevious()) {
  717. char_iterator.previous();
  718. if (!(u_isspace(char_iterator.current()) ||
  719. u_charType(char_iterator.current()) == U_CONTROL_CHAR ||
  720. u_charType(char_iterator.current()) == U_NON_SPACING_MARK)) {
  721. // Not a whitespace character. Truncate to everything up to and including
  722. // this character, and append an ellipsis.
  723. char_iterator.next();
  724. return string.substr(0, char_iterator.getIndex()) + kElideString;
  725. }
  726. }
  727. // Couldn't find a previous non-whitespace character. If we were originally
  728. // word-breaking, and index != length - 1, then the string is |index|
  729. // whitespace characters followed by a word we're trying to break in the midst
  730. // of, and we can fit at least one character of the word in the elided string.
  731. // Do that rather than just returning an ellipsis.
  732. if (word_break && (index != static_cast<int32_t>(length - 1)))
  733. return string.substr(0, length - 1) + kElideString;
  734. // Trying to break after only whitespace, elide all of it.
  735. return kElideString;
  736. }
  737. } // namespace gfx