render_text.h 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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. #ifndef UI_GFX_RENDER_TEXT_H_
  5. #define UI_GFX_RENDER_TEXT_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <algorithm>
  9. #include <array>
  10. #include <cstring>
  11. #include <memory>
  12. #include <string>
  13. #include <utility>
  14. #include <vector>
  15. #include "base/i18n/rtl.h"
  16. #include "base/memory/raw_ptr.h"
  17. #include "build/build_config.h"
  18. #include "cc/paint/paint_flags.h"
  19. #include "third_party/abseil-cpp/absl/types/optional.h"
  20. #include "third_party/skia/include/core/SkColor.h"
  21. #include "third_party/skia/include/core/SkFont.h"
  22. #include "third_party/skia/include/core/SkRefCnt.h"
  23. #include "ui/gfx/break_list.h"
  24. #include "ui/gfx/color_palette.h"
  25. #include "ui/gfx/font_list.h"
  26. #include "ui/gfx/font_render_params.h"
  27. #include "ui/gfx/geometry/point.h"
  28. #include "ui/gfx/geometry/rect.h"
  29. #include "ui/gfx/geometry/rect_f.h"
  30. #include "ui/gfx/geometry/size_f.h"
  31. #include "ui/gfx/geometry/vector2d.h"
  32. #include "ui/gfx/range/range.h"
  33. #include "ui/gfx/range/range_f.h"
  34. #include "ui/gfx/selection_model.h"
  35. #include "ui/gfx/shadow_value.h"
  36. #include "ui/gfx/text_constants.h"
  37. class SkDrawLooper;
  38. struct SkPoint;
  39. class SkTypeface;
  40. namespace cc {
  41. class PaintCanvas;
  42. }
  43. namespace gfx {
  44. namespace test {
  45. class RenderTextTestApi;
  46. }
  47. class Canvas;
  48. struct DecoratedText;
  49. class Font;
  50. namespace internal {
  51. class TextRunList;
  52. // Internal helper class used by derived classes to draw text through Skia.
  53. class GFX_EXPORT SkiaTextRenderer {
  54. public:
  55. explicit SkiaTextRenderer(Canvas* canvas);
  56. SkiaTextRenderer(const SkiaTextRenderer&) = delete;
  57. SkiaTextRenderer& operator=(const SkiaTextRenderer&) = delete;
  58. virtual ~SkiaTextRenderer();
  59. void SetDrawLooper(sk_sp<SkDrawLooper> draw_looper);
  60. void SetFontRenderParams(const FontRenderParams& params,
  61. bool subpixel_rendering_suppressed);
  62. void SetTypeface(sk_sp<SkTypeface> typeface);
  63. void SetTextSize(SkScalar size);
  64. void SetForegroundColor(SkColor foreground);
  65. void SetShader(sk_sp<cc::PaintShader> shader);
  66. // TODO(vmpstr): Change this API to mimic SkCanvas::drawTextBlob instead.
  67. virtual void DrawPosText(const SkPoint* pos,
  68. const uint16_t* glyphs,
  69. size_t glyph_count);
  70. void DrawUnderline(int x, int y, int width, SkScalar thickness_factor = 1.0);
  71. void DrawStrike(int x, int y, int width, SkScalar thickness_factor);
  72. private:
  73. friend class test::RenderTextTestApi;
  74. raw_ptr<Canvas> canvas_;
  75. raw_ptr<cc::PaintCanvas> canvas_skia_;
  76. cc::PaintFlags flags_;
  77. SkFont font_;
  78. };
  79. struct TextToDisplayIndex {
  80. size_t text_index = 0;
  81. size_t display_index = 0;
  82. };
  83. using TextToDisplaySequence = std::vector<TextToDisplayIndex>;
  84. using GraphemeIterator = TextToDisplaySequence::const_iterator;
  85. using StyleArray = std::array<BreakList<bool>, TEXT_STYLE_COUNT>;
  86. // Internal helper class used to iterate colors, baselines, and styles.
  87. class StyleIterator {
  88. public:
  89. StyleIterator(const BreakList<SkColor>* colors,
  90. const BreakList<BaselineStyle>* baselines,
  91. const BreakList<int>* font_size_overrides,
  92. const BreakList<Font::Weight>* weights,
  93. const StyleArray* styles);
  94. StyleIterator(const StyleIterator& style);
  95. ~StyleIterator();
  96. StyleIterator& operator=(const StyleIterator& style);
  97. // Get the colors and styles at the current iterator position.
  98. SkColor color() const { return color_->second; }
  99. BaselineStyle baseline() const { return baseline_->second; }
  100. int font_size_override() const { return font_size_override_->second; }
  101. bool style(TextStyle s) const { return style_[s]->second; }
  102. Font::Weight weight() const { return weight_->second; }
  103. // Get the intersecting range of the current iterator set.
  104. Range GetRange() const;
  105. // Get the intersecting range of the current iterator set for attributes that
  106. // can break text (e.g. not color).
  107. Range GetTextBreakingRange() const;
  108. // Update the iterator to point to colors and styles applicable at |position|.
  109. void IncrementToPosition(size_t position);
  110. private:
  111. // Pointers to the breaklists to iterate through. These pointers can't be
  112. // nullptr and the breaklists must outlive this object.
  113. raw_ptr<const BreakList<SkColor>> colors_;
  114. raw_ptr<const BreakList<BaselineStyle>> baselines_;
  115. raw_ptr<const BreakList<int>> font_size_overrides_;
  116. raw_ptr<const BreakList<Font::Weight>> weights_;
  117. raw_ptr<const StyleArray> styles_;
  118. BreakList<SkColor>::const_iterator color_;
  119. BreakList<BaselineStyle>::const_iterator baseline_;
  120. BreakList<int>::const_iterator font_size_override_;
  121. BreakList<Font::Weight>::const_iterator weight_;
  122. std::array<BreakList<bool>::const_iterator, TEXT_STYLE_COUNT> style_;
  123. };
  124. // Line segments are slices of the display text to be rendered on a single line.
  125. struct LineSegment {
  126. LineSegment();
  127. ~LineSegment();
  128. // X coordinates of this line segment in text space.
  129. RangeF x_range;
  130. // The character range this segment corresponds to.
  131. Range char_range;
  132. // Index of the text run that generated this segment.
  133. size_t run;
  134. // Returns the width of this line segment in text space.
  135. float width() const { return x_range.length(); }
  136. };
  137. // A line of display text, comprised of a line segment list and some metrics.
  138. struct Line {
  139. Line();
  140. Line(const Line& other);
  141. ~Line();
  142. // Segments that make up this line in visual order.
  143. std::vector<LineSegment> segments;
  144. // The sum of segment widths and the maximum of segment heights.
  145. SizeF size;
  146. // Sum of preceding lines' heights.
  147. int preceding_heights;
  148. // Maximum baseline of all segments on this line.
  149. int baseline;
  150. // The text index of this line in |text_|.
  151. int display_text_index = 0;
  152. };
  153. // Internal class that contains the results of the text layout and shaping.
  154. class ShapedText {
  155. public:
  156. explicit ShapedText(std::vector<Line> lines);
  157. ~ShapedText();
  158. const std::vector<Line>& lines() const { return lines_; }
  159. private:
  160. std::vector<Line> lines_;
  161. };
  162. // Creates an SkTypeface from a font, |italic| and a desired |weight|.
  163. // May return null.
  164. sk_sp<SkTypeface> CreateSkiaTypeface(const Font& font,
  165. bool italic,
  166. Font::Weight weight);
  167. // Applies the given FontRenderParams to the SkFont.
  168. void ApplyRenderParams(const FontRenderParams& params,
  169. bool subpixel_rendering_suppressed,
  170. SkFont* font);
  171. } // namespace internal
  172. // RenderText represents an abstract model of styled text and its corresponding
  173. // visual layout. Support is built in for a cursor, selections, simple styling,
  174. // complex scripts, and bi-directional text. Implementations provide mechanisms
  175. // for rendering and translation between logical and visual data.
  176. class GFX_EXPORT RenderText {
  177. public:
  178. #if BUILDFLAG(IS_APPLE)
  179. // On Mac, while selecting text if the cursor is outside the vertical text
  180. // bounds, drag to the end of the text.
  181. static constexpr bool kDragToEndIfOutsideVerticalBounds = true;
  182. // Mac supports a selection that is "undirected". When undirected, the cursor
  183. // doesn't know which end of the selection it's at until it first moves.
  184. static constexpr bool kSelectionIsAlwaysDirected = false;
  185. #else
  186. static constexpr bool kDragToEndIfOutsideVerticalBounds = false;
  187. static constexpr bool kSelectionIsAlwaysDirected = true;
  188. #endif
  189. // Invalid value of baseline. Assigning this value to |baseline_| causes
  190. // re-calculation of baseline.
  191. static constexpr int kInvalidBaseline = INT_MAX;
  192. // Default fraction of the text size to use for a strike-through or underline.
  193. static constexpr SkScalar kLineThicknessFactor = (SK_Scalar1 / 18);
  194. // The character used for displaying obscured text. Use a bullet character.
  195. // TODO(pbos): This is highly font dependent, consider replacing the character
  196. // with a vector glyph.
  197. static constexpr char16_t kPasswordReplacementChar = 0x2022;
  198. RenderText(const RenderText&) = delete;
  199. RenderText& operator=(const RenderText&) = delete;
  200. virtual ~RenderText();
  201. // Creates a RenderText instance.
  202. static std::unique_ptr<RenderText> CreateRenderText();
  203. // Like above but copies all style settings too.
  204. std::unique_ptr<RenderText> CreateInstanceOfSameStyle(
  205. const std::u16string& text) const;
  206. const std::u16string& text() const { return text_; }
  207. void SetText(const std::u16string& text);
  208. void AppendText(const std::u16string& text);
  209. HorizontalAlignment horizontal_alignment() const {
  210. return horizontal_alignment_;
  211. }
  212. void SetHorizontalAlignment(HorizontalAlignment alignment);
  213. VerticalAlignment vertical_alignment() const { return vertical_alignment_; }
  214. void SetVerticalAlignment(VerticalAlignment alignment);
  215. const FontList& font_list() const { return font_list_; }
  216. void SetFontList(const FontList& font_list);
  217. bool cursor_enabled() const { return cursor_enabled_; }
  218. void SetCursorEnabled(bool cursor_enabled);
  219. SkColor selection_color() const { return selection_color_; }
  220. void set_selection_color(SkColor color) { selection_color_ = color; }
  221. SkColor selection_background_focused_color() const {
  222. return selection_background_focused_color_;
  223. }
  224. void set_selection_background_focused_color(SkColor color) {
  225. selection_background_focused_color_ = color;
  226. }
  227. bool symmetric_selection_visual_bounds() const {
  228. return symmetric_selection_visual_bounds_;
  229. }
  230. void set_symmetric_selection_visual_bounds(bool symmetric) {
  231. symmetric_selection_visual_bounds_ = symmetric;
  232. }
  233. bool focused() const { return focused_; }
  234. void set_focused(bool focused) { focused_ = focused; }
  235. bool clip_to_display_rect() const { return clip_to_display_rect_; }
  236. void set_clip_to_display_rect(bool clip) { clip_to_display_rect_ = clip; }
  237. // In an obscured (password) field, all text is drawn as bullets.
  238. bool obscured() const { return obscured_; }
  239. void SetObscured(bool obscured);
  240. // Makes a char in obscured text at |index| to be revealed. |index| should be
  241. // a UTF16 text index. If there is a previous revealed index, the previous one
  242. // is cleared and only the last set index will be revealed. If |index| is
  243. // nullopt or out of range, no char will be revealed. The revealed index is
  244. // also cleared when SetText or SetObscured is called.
  245. void SetObscuredRevealIndex(absl::optional<size_t> index);
  246. // For obscured (password) fields, the extra spacing between glyphs.
  247. int obscured_glyph_spacing() const { return obscured_glyph_spacing_; }
  248. void SetObscuredGlyphSpacing(int spacing);
  249. bool multiline() const { return multiline_; }
  250. void SetMultiline(bool multiline);
  251. // If multiline, a non-zero value will cap the number of lines rendered,
  252. // and elide the rest (currently only ELIDE_TAIL supported.)
  253. void SetMaxLines(size_t max_lines);
  254. size_t max_lines() const { return max_lines_; }
  255. // Returns the actual number of lines, broken by |lines_|.
  256. size_t GetNumLines();
  257. // Returns the text index of the given line |line|. Returns the text length
  258. // for any |line| above the number of lines.
  259. size_t GetTextIndexOfLine(size_t line);
  260. // TODO(mukai): ELIDE_LONG_WORDS is not supported.
  261. WordWrapBehavior word_wrap_behavior() const { return word_wrap_behavior_; }
  262. void SetWordWrapBehavior(WordWrapBehavior behavior);
  263. // TODO(ckocagil): Add vertical alignment and line spacing support instead.
  264. int min_line_height() const { return min_line_height_; }
  265. void SetMinLineHeight(int line_height);
  266. // Set the maximum length of the layout text, not the actual text.
  267. // A |length| of 0 forgoes a hard limit, but does not guarantee proper
  268. // functionality of very long strings. Applies to subsequent SetText calls.
  269. // WARNING: Only use this for system limits, it lacks complex text support.
  270. void set_truncate_length(size_t length) { truncate_length_ = length; }
  271. // The display text will be elided to fit |display_rect| using this behavior.
  272. void SetElideBehavior(ElideBehavior elide_behavior);
  273. ElideBehavior elide_behavior() const { return elide_behavior_; }
  274. // When display text is elided, determines how whitespace is handled.
  275. // If absl::nullopt is specified, the default elision for the current elide
  276. // behavior will be applied.
  277. void SetWhitespaceElision(absl::optional<bool> elide_whitespace);
  278. absl::optional<bool> whitespace_elision() const {
  279. return whitespace_elision_;
  280. }
  281. const Rect& display_rect() const { return display_rect_; }
  282. void SetDisplayRect(const Rect& r);
  283. bool subpixel_rendering_suppressed() const {
  284. return subpixel_rendering_suppressed_;
  285. }
  286. void set_subpixel_rendering_suppressed(bool suppressed) {
  287. subpixel_rendering_suppressed_ = suppressed;
  288. }
  289. const SelectionModel& selection_model() const { return selection_model_; }
  290. const Range& selection() const { return selection_model_.selection(); }
  291. size_t cursor_position() const { return selection_model_.caret_pos(); }
  292. const std::vector<Range>& secondary_selections() const {
  293. return selection_model_.secondary_selections();
  294. }
  295. const std::vector<Range> GetAllSelections() const;
  296. // Set the cursor to |position|, with the caret affinity trailing the previous
  297. // grapheme, or if there is no previous grapheme, leading the cursor position.
  298. // See SelectionModel::caret_affinity_ for details.
  299. void SetCursorPosition(size_t position);
  300. // Moves the cursor left or right. Cursor movement is visual, meaning that
  301. // left and right are relative to screen, not the directionality of the text.
  302. // |selection_behavior| determines whether a selection is to be made and it's
  303. // behavior.
  304. void MoveCursor(BreakType break_type,
  305. VisualCursorDirection direction,
  306. SelectionBehavior selection_behavior);
  307. // Set the selection_model_ to the value of |selection|.
  308. // The selection range is clamped to text().length() if out of range.
  309. // Returns true if the cursor position or selection range changed.
  310. // If any index in |selection_model| is not a cursorable position (not on a
  311. // grapheme boundary), it is a no-op and returns false.
  312. bool SetSelection(const SelectionModel& selection);
  313. // Moves the cursor to the text index corresponding to |point|. If |select| is
  314. // true, a selection is made with the current selection start index. If the
  315. // resultant text indices do not lie on valid grapheme boundaries, it is a no-
  316. // op and returns false. If this move is happening because of a drag causing a
  317. // selection change, and |drag_origin| is not the zero point, then
  318. // |drag_origin| overrides the default origin for a select-to-drag
  319. // (usually the existing text insertion cursor).
  320. bool MoveCursorToPoint(const gfx::Point& point,
  321. bool select,
  322. const gfx::Point& drag_origin = gfx::Point());
  323. // Set the |selection_model_| based on |range|. If the |range| start or end is
  324. // greater than text length, it is modified to be the text length. If the
  325. // |range| start or end is not a cursorable position (not on grapheme
  326. // boundary), it is a NO-OP and returns false. Otherwise, returns true. If
  327. // |primary| is true, secondary selections are cleared; otherwise, the range
  328. // will be added as a secondary selection not associated with the cursor. In
  329. // the latter case, |range| should not overlap with existing selections.
  330. bool SelectRange(const Range& range, bool primary = true);
  331. // Returns true if the local point is over selected text.
  332. bool IsPointInSelection(const Point& point);
  333. // Selects no text, keeping the current cursor position and caret affinity.
  334. void ClearSelection();
  335. // Select the entire text range. If |reversed| is true, the range will end at
  336. // the logical beginning of the text; this generally shows the leading portion
  337. // of text that overflows its display area.
  338. void SelectAll(bool reversed);
  339. // Selects the word at the current cursor position. If there is a non-empty
  340. // selection, the selection bounds are extended to their nearest word
  341. // boundaries.
  342. void SelectWord();
  343. void SetCompositionRange(const Range& composition_range);
  344. // Set the text color over the entire text or a logical character range.
  345. // The |range| should be valid, non-reversed, and within [0, text().length()].
  346. void SetColor(SkColor value);
  347. void ApplyColor(SkColor value, const Range& range);
  348. // DEPRECATED.
  349. // Set the baseline style over the entire text or a logical character range.
  350. // The |range| should be valid, non-reversed, and within [0, text().length()].
  351. // TODO(tapted): Remove this. The only client is moving to
  352. // ApplyFontSizeOverride.
  353. void SetBaselineStyle(BaselineStyle value);
  354. void ApplyBaselineStyle(BaselineStyle value, const Range& range);
  355. // Alters the font size in |range|.
  356. void ApplyFontSizeOverride(int font_size_override, const Range& range);
  357. // Set various text styles over the entire text or a logical character range.
  358. // The respective |style| is applied if |value| is true, or removed if false.
  359. // The |range| should be valid, non-reversed, and within [0, text().length()].
  360. void SetStyle(TextStyle style, bool value);
  361. void ApplyStyle(TextStyle style, bool value, const Range& range);
  362. void SetWeight(Font::Weight weight);
  363. void ApplyWeight(Font::Weight weight, const Range& range);
  364. // Returns whether this style is enabled consistently across the entire
  365. // RenderText.
  366. bool GetStyle(TextStyle style) const;
  367. // Set or get the text directionality mode and get the text direction yielded.
  368. void SetDirectionalityMode(DirectionalityMode mode);
  369. DirectionalityMode directionality_mode() const {
  370. return directionality_mode_;
  371. }
  372. base::i18n::TextDirection GetTextDirection() const;
  373. base::i18n::TextDirection GetDisplayTextDirection();
  374. // Returns the visual movement direction corresponding to the logical
  375. // end/beginning of the text, considering only the dominant direction returned
  376. // by |GetDisplayTextDirection()|, not the direction of a particular run.
  377. VisualCursorDirection GetVisualDirectionOfLogicalEnd();
  378. VisualCursorDirection GetVisualDirectionOfLogicalBeginning();
  379. // Returns the text used to display, which may be obscured, truncated or
  380. // elided. The subclass may compute elided text on the fly, or use
  381. // precomputed the elided text.
  382. virtual const std::u16string& GetDisplayText() = 0;
  383. // Returns the size required to display the current string (which is the
  384. // wrapped size in multiline mode). The returned size does not include space
  385. // reserved for the cursor or the offset text shadows.
  386. Size GetStringSize();
  387. // This is same as GetStringSize except that fractional size is returned.
  388. // The default implementation is same as GetStringSize. Certain platforms that
  389. // compute the text size as floating-point values, like Mac, will override
  390. // this method.
  391. // See comment in Canvas::GetStringWidthF for its usage.
  392. virtual SizeF GetStringSizeF() = 0;
  393. // Returns the size of the line containing |caret|.
  394. virtual SizeF GetLineSizeF(const SelectionModel& caret) = 0;
  395. // Returns the sum of all the line widths.
  396. float TotalLineWidth();
  397. // Returns the width of the content (which is the wrapped width in multiline
  398. // mode). Reserves room for the cursor if |cursor_enabled_| is true.
  399. float GetContentWidthF();
  400. // Same as GetContentWidthF with the width rounded up.
  401. int GetContentWidth();
  402. // Returns the common baseline of the text. The return value is the vertical
  403. // offset from the top of |display_rect_| to the text baseline, in pixels.
  404. // The baseline is determined from the font list and display rect, and does
  405. // not depend on the text.
  406. int GetBaseline();
  407. // If |select_all| is true, draws as focused with all text selected.
  408. void Draw(Canvas* canvas, bool select_all = false);
  409. // Gets the SelectionModel from a visual point in local coordinates. If
  410. // |drag_origin| is nonzero, it is used as the baseline for
  411. // out-of-vertical-bounds drags on platforms that have them, instead of the
  412. // default origin (the insertion cursor's position).
  413. SelectionModel FindCursorPosition(const Point& point,
  414. const Point& drag_origin = gfx::Point());
  415. // Returns true if the position is a valid logical index into text(). Indices
  416. // amid multi-character graphemes are allowed here, unlike IsValidCursorIndex.
  417. bool IsValidLogicalIndex(size_t index) const;
  418. // Returns true if the position is a valid logical index into text(), and is
  419. // also a valid grapheme boundary, which may be used as a cursor position.
  420. bool IsValidCursorIndex(size_t index) const;
  421. // Get the visual bounds of a cursor at |caret|. These bounds typically
  422. // represent a vertical line if |insert_mode| is true. Pass false for
  423. // |insert_mode| to retrieve the bounds of the associated glyph. These bounds
  424. // are in local coordinates, but may be outside the visible region if the text
  425. // is longer than the textfield. Subsequent text, cursor, or bounds changes
  426. // may invalidate returned values. Note that |caret| must be placed at
  427. // grapheme boundary, i.e. caret.caret_pos() must be a cursorable position.
  428. // TODO(crbug.com/248597): Add multiline support.
  429. Rect GetCursorBounds(const SelectionModel& caret, bool insert_mode);
  430. // Compute the current cursor bounds, panning the text to show the cursor in
  431. // the display rect if necessary. These bounds are in local coordinates.
  432. // Subsequent text, cursor, or bounds changes may invalidate returned values.
  433. const Rect& GetUpdatedCursorBounds();
  434. // Returns a grapheme iterator that contains the codepoint at |index|.
  435. internal::GraphemeIterator GetGraphemeIteratorAtTextIndex(size_t index) const;
  436. internal::GraphemeIterator GetGraphemeIteratorAtDisplayTextIndex(
  437. size_t index) const;
  438. // For a given grapheme iterator, returns its index.
  439. size_t GetTextIndex(internal::GraphemeIterator iter) const;
  440. size_t GetDisplayTextIndex(internal::GraphemeIterator iter) const;
  441. // Returns true of the current index is at the start of a grapheme.
  442. bool IsGraphemeBoundary(size_t index) const;
  443. // Given an |index| in text(), return the next or previous grapheme boundary
  444. // in logical order (i.e. the nearest cursorable index). The return value is
  445. // in the range 0 to text().length() inclusive (the input is clamped if it is
  446. // out of that range). Always moves by at least one character index unless the
  447. // supplied index is already at the boundary of the string.
  448. size_t IndexOfAdjacentGrapheme(size_t index,
  449. LogicalCursorDirection direction) const;
  450. // Return a SelectionModel with the cursor at the current selection's start.
  451. // The returned value represents a cursor/caret position without a selection.
  452. SelectionModel GetSelectionModelForSelectionStart() const;
  453. // Sets shadows to drawn with text.
  454. void set_shadows(const ShadowValues& shadows) { shadows_ = shadows; }
  455. const ShadowValues& shadows() const { return shadows_; }
  456. // Get the visual bounds containing the logical substring within the |range|.
  457. // If |range| is empty, the result is empty. This method rounds internally so
  458. // the returned bounds may be slightly larger than the |range|, but are
  459. // guaranteed not to be smaller. These bounds could be visually discontinuous
  460. // if the substring is split by a LTR/RTL level change. These bounds are in
  461. // local coordinates, but may be outside the visible region if the text is
  462. // larger than the available space. Subsequent text, cursor, or bounds changes
  463. // may invalidate returned values.
  464. virtual std::vector<Rect> GetSubstringBounds(const Range& range) = 0;
  465. // Gets the horizontal span (relative to the left of the text, not the view)
  466. // of the sequence of glyphs in |text_range|, over which the cursor will
  467. // jump when breaking by characters. If the glyphs are RTL then the returned
  468. // Range will have is_reversed() true. (This does not return a Rect because a
  469. // Rect can't have a negative width.)
  470. virtual RangeF GetCursorSpan(const Range& text_range) = 0;
  471. const Vector2d& GetUpdatedDisplayOffset();
  472. void SetDisplayOffset(int horizontal_offset);
  473. void SetDisplayOffset(Vector2d offset);
  474. // Returns the line offset from the origin after applying the text alignment
  475. // and the display offset.
  476. Vector2d GetLineOffset(size_t line_number);
  477. // Retrieves the word displayed at the given |point| along with its styling
  478. // information. |point| is in the view's coordinates. If no word is displayed
  479. // at the point, returns a nearby word. |baseline_point| should correspond to
  480. // the baseline point of the leftmost glyph of the |word| in the view's
  481. // coordinates. Returns false, if no word can be retrieved.
  482. bool GetWordLookupDataAtPoint(const Point& point,
  483. DecoratedText* decorated_word,
  484. Point* baseline_point);
  485. // Retrieves the text at |range| along with its styling information.
  486. // |baseline_point| should correspond to the baseline point of
  487. // the leftmost glyph of the text in the view's coordinates. If the text
  488. // spans multiple lines, |baseline_point| will correspond with the leftmost
  489. // glyph on the first line in the range. Returns false, if no text can be
  490. // retrieved.
  491. bool GetLookupDataForRange(const Range& range,
  492. DecoratedText* decorated_text,
  493. Point* baseline_point);
  494. // Retrieves the text in the given |range|.
  495. std::u16string GetTextFromRange(const Range& range) const;
  496. void set_strike_thickness_factor(SkScalar f) { strike_thickness_factor_ = f; }
  497. // Return the line index that contains the argument; or the index of the last
  498. // line if the |caret| exceeds the text length.
  499. virtual size_t GetLineContainingCaret(const SelectionModel& caret) = 0;
  500. // Expands |range| to its nearest grapheme boundaries and returns the
  501. // resulting range. Maintains directionality of |range|.
  502. Range ExpandRangeToGraphemeBoundary(const Range& range) const;
  503. // Specify the width/height of a glyph for test. The width/height of glyphs is
  504. // very platform-dependent and environment-dependent. Otherwise multiline text
  505. // will become really flaky.
  506. void set_glyph_width_for_test(float width) { glyph_width_for_test_ = width; }
  507. void set_glyph_height_for_test(float height) {
  508. glyph_height_for_test_ = height;
  509. }
  510. protected:
  511. RenderText();
  512. // Whether |segment| corresponds to the newline character. This uses |text_|
  513. // to look up the corresponding character.
  514. bool IsNewlineSegment(const internal::LineSegment& segment) const;
  515. // Whether |segment| corresponds to the newline character inside |text|.
  516. bool IsNewlineSegment(const std::u16string& text,
  517. const internal::LineSegment& segment) const;
  518. // Returns the character range of segments in |line| excluding the trailing
  519. // newline segment.
  520. Range GetLineRange(const std::u16string& text,
  521. const internal::Line& line) const;
  522. // Returns the text used for layout (e.g. after rewriting, eliding and
  523. // obscuring characters).
  524. const std::u16string& GetLayoutText() const;
  525. // NOTE: The value of these accessors may be stale. Please make sure
  526. // that these fields are up to date before accessing them.
  527. const std::u16string& display_text() const { return display_text_; }
  528. bool text_elided() const { return text_elided_; }
  529. // Returns an iterator over the |text_| attributes.
  530. internal::StyleIterator GetTextStyleIterator() const;
  531. // Returns an iterator over the |layout_text_| attributes.
  532. internal::StyleIterator GetLayoutTextStyleIterator() const;
  533. const BreakList<SkColor>& colors() const { return colors_; }
  534. const BreakList<BaselineStyle>& baselines() const { return baselines_; }
  535. const BreakList<int>& font_size_overrides() const {
  536. return font_size_overrides_;
  537. }
  538. const BreakList<Font::Weight>& weights() const { return weights_; }
  539. const internal::StyleArray& styles() const { return styles_; }
  540. SkScalar strike_thickness_factor() const { return strike_thickness_factor_; }
  541. const BreakList<SkColor>& layout_colors() const { return layout_colors_; }
  542. // Whether all the BreakLists have only one break.
  543. bool IsHomogeneous() const;
  544. // Returns the shaped text structure. The shaped text contains the visual
  545. // positions of glyphs required to render the text.
  546. bool has_shaped_text() const { return shaped_text_ != nullptr; }
  547. internal::ShapedText* GetShapedText();
  548. void set_shaped_text(std::unique_ptr<internal::ShapedText> shaped_text) {
  549. shaped_text_ = std::move(shaped_text);
  550. }
  551. // Returns the baseline of the current text. The return value depends on
  552. // the text and its layout while the return value of GetBaseline() doesn't.
  553. // GetAlignmentOffset() takes into account the difference between them.
  554. //
  555. // We'd like a RenderText to show the text always on the same baseline
  556. // regardless of the text, so the text does not jump up or down depending
  557. // on the text. However, underlying layout engines return different baselines
  558. // depending on the text. In general, layout engines determine the minimum
  559. // bounding box for the text and return the baseline from the top of the
  560. // bounding box. So the baseline changes depending on font metrics used to
  561. // layout the text.
  562. //
  563. // For example, suppose there are FontA and FontB and the baseline of FontA
  564. // is smaller than the one of FontB. If the text is laid out only with FontA,
  565. // then the baseline of FontA may be returned. If the text includes some
  566. // characters which are laid out with FontB, then the baseline of FontB may
  567. // be returned.
  568. //
  569. // GetBaseline() returns the fixed baseline regardless of the text.
  570. // GetDisplayTextBaseline() returns the baseline determined by the underlying
  571. // layout engine, and it changes depending on the text. GetAlignmentOffset()
  572. // returns the difference between them.
  573. int GetDisplayTextBaseline();
  574. // Get the selection model that visually neighbors |position| by |break_type|.
  575. // The returned value represents a cursor/caret position without a selection.
  576. SelectionModel GetAdjacentSelectionModel(const SelectionModel& current,
  577. BreakType break_type,
  578. VisualCursorDirection direction);
  579. // Get the selection model visually left/right of |selection| by one grapheme.
  580. // The returned value represents a cursor/caret position without a selection.
  581. virtual SelectionModel AdjacentCharSelectionModel(
  582. const SelectionModel& selection,
  583. VisualCursorDirection direction) = 0;
  584. // Get the selection model visually left/right of |selection| by one word.
  585. // The returned value represents a cursor/caret position without a selection.
  586. virtual SelectionModel AdjacentWordSelectionModel(
  587. const SelectionModel& selection,
  588. VisualCursorDirection direction) = 0;
  589. // Get the selection model visually above/below |selection| by one line.
  590. // The returned value represents a cursor/caret position without a selection.
  591. virtual SelectionModel AdjacentLineSelectionModel(
  592. const SelectionModel& selection,
  593. VisualCursorDirection direction) = 0;
  594. // Get the selection model corresponding to visual text ends.
  595. // The returned value represents a cursor/caret position without a selection.
  596. SelectionModel EdgeSelectionModel(VisualCursorDirection direction);
  597. // Get the selection model corresponding to visual text ends for |line_index|.
  598. // The returned value represents a cursor/caret position without a selection.
  599. SelectionModel LineSelectionModel(size_t line_index,
  600. gfx::VisualCursorDirection direction);
  601. // Sets the selection model. |model| should be valid.
  602. void SetSelectionModel(const SelectionModel& model);
  603. // Adds a secondary selection. |selection| should not overlap with existing
  604. // selections.
  605. void AddSecondarySelection(const Range selection);
  606. // Convert between indices into |text_| and indices into
  607. // GetDisplayText(), which differ when the text is obscured,
  608. // truncated or elided.
  609. size_t TextIndexToDisplayIndex(size_t index) const;
  610. size_t DisplayIndexToTextIndex(size_t index) const;
  611. // Notifies that layout text, or attributes that affect the layout text
  612. // shape have changed. |text_changed| is true if the content of the
  613. // |layout_text_| has changed, not just attributes.
  614. virtual void OnLayoutTextAttributeChanged(bool text_changed);
  615. // Notifies that attributes that affect the display text shape have changed.
  616. virtual void OnDisplayTextAttributeChanged() = 0;
  617. // Ensure the text is laid out, lines are computed, and |lines_| is valid.
  618. virtual void EnsureLayout() = 0;
  619. // Draw all text and make the given ranges appear selected.
  620. virtual void DrawVisualText(internal::SkiaTextRenderer* renderer,
  621. const std::vector<Range>& selections) = 0;
  622. // Update the display text.
  623. void UpdateDisplayText(float text_width);
  624. // Convert points from the text space to the view space. Handles the display
  625. // area, display offset, application LTR/RTL mode and multiline. |line| is the
  626. // index of the line in which |point| is found, and is required to be passed
  627. // because by the time |point| is in text space, the information to account
  628. // for certain zero-width characters (such as empty lines) is lost.
  629. Point ToViewPoint(const PointF& point, size_t line);
  630. // Get the alignment, resolving ALIGN_TO_HEAD with the current text direction.
  631. HorizontalAlignment GetCurrentHorizontalAlignment();
  632. // Returns the line offset from the origin, accounts for text alignment only.
  633. Vector2d GetAlignmentOffset(size_t line_number);
  634. // Applies fade effects to |renderer|.
  635. void ApplyFadeEffects(internal::SkiaTextRenderer* renderer);
  636. // Applies text shadows to |renderer|.
  637. void ApplyTextShadows(internal::SkiaTextRenderer* renderer);
  638. // Get the text direction for the current directionality mode and given
  639. // |text|.
  640. base::i18n::TextDirection GetTextDirectionForGivenText(
  641. const std::u16string& text) const;
  642. // Adjust ranged styles to accommodate a new |text_| length.
  643. void UpdateStyleLengths();
  644. // Adjust ranged styles to accommodate a new |layout_text_| length.
  645. void UpdateLayoutStyleLengths(size_t max_length) const;
  646. // Returns the line index for the given argument. |text_y| is relative to
  647. // the text bounds. Returns -1 if |text_y| is above the text and
  648. // lines().size() if |text_y| is below it.
  649. int GetLineContainingYCoord(float text_y);
  650. // A convenience function to check whether the glyph attached to the caret
  651. // is within the given range.
  652. static bool RangeContainsCaret(const Range& range,
  653. size_t caret_pos,
  654. LogicalCursorDirection caret_affinity);
  655. // Returns the baseline, with which the text best appears vertically centered.
  656. static int DetermineBaselineCenteringText(const int display_height,
  657. const FontList& font_list);
  658. // Returns an expanded version of |rect| that is vertically symmetric with
  659. // respect to the center of |display_rect|.
  660. static gfx::Rect ExpandToBeVerticallySymmetric(const gfx::Rect& rect,
  661. const gfx::Rect& display_rect);
  662. // Given |rects|, sort them along the x-axis and merge intersecting rects
  663. // using union. Expects all selections in the text to be from the same line.
  664. static void MergeIntersectingRects(std::vector<Rect>& rects);
  665. // Resets |cached_cursor_x_| to null. When non-null, CURSOR_UP, CURSOR_DOWN
  666. // movements use this value instead of the current cursor x position to
  667. // determine the next cursor x position.
  668. void reset_cached_cursor_x() { cached_cursor_x_.reset(); }
  669. void set_cached_cursor_x(int x) { cached_cursor_x_ = x; }
  670. absl::optional<int> cached_cursor_x() const { return cached_cursor_x_; }
  671. // Fixed width of glyphs. This should only be set in test environments.
  672. float glyph_width_for_test_ = 0;
  673. // Fixed height of glyphs. This should only be set in test environments.
  674. float glyph_height_for_test_ = 0;
  675. private:
  676. friend class test::RenderTextTestApi;
  677. // Resets |layout_text_| and |display_text_| and marks them dirty.
  678. void OnTextAttributeChanged();
  679. // Computes the |layout_text_| by rewriting it from |text_|, if needed.
  680. // Computes the layout break lists, if needed.
  681. void EnsureLayoutTextUpdated() const;
  682. // Elides |text| as needed to fit in the |available_width| using |behavior|.
  683. // |text_width| is the pre-calculated width of the text shaped by this render
  684. // text, or pass 0 if the width is unknown.
  685. std::u16string Elide(const std::u16string& text,
  686. float text_width,
  687. float available_width,
  688. ElideBehavior behavior);
  689. // Elides |email| as needed to fit the |available_width|.
  690. std::u16string ElideEmail(const std::u16string& email, float available_width);
  691. // Update the cached bounds and display offset to ensure that the current
  692. // cursor is within the visible display area.
  693. void UpdateCachedBoundsAndOffset();
  694. // Draws the specified ranges of text with a selected appearance.
  695. void DrawSelections(Canvas* canvas, const std::vector<Range>& selections);
  696. // Returns a grapheme iterator that contains the codepoint at |index|.
  697. internal::GraphemeIterator GetGraphemeIteratorAtIndex(
  698. const std::u16string& text,
  699. const size_t internal::TextToDisplayIndex::*field,
  700. size_t index) const;
  701. // Returns the nearest word start boundary for |index|. First searches in the
  702. // CURSOR_BACKWARD direction, then in the CURSOR_FORWARD direction. Returns
  703. // the text length if no valid boundary is found.
  704. size_t GetNearestWordStartBoundary(size_t index) const;
  705. // Expands |range| to its nearest word boundaries and returns the resulting
  706. // range. Maintains directionality of |range|.
  707. Range ExpandRangeToWordBoundary(const Range& range) const;
  708. // Returns an implementation-specific run list, if implemented.
  709. virtual internal::TextRunList* GetRunList() = 0;
  710. virtual const internal::TextRunList* GetRunList() const = 0;
  711. // Returns the decorated text corresponding to |range|. Returns false if the
  712. // text cannot be retrieved, e.g. if the text is obscured.
  713. virtual bool GetDecoratedTextForRange(const Range& range,
  714. DecoratedText* decorated_text) = 0;
  715. // Logical UTF-16 string data to be drawn.
  716. std::u16string text_;
  717. // Horizontal alignment of the text with respect to |display_rect_|. The
  718. // default is to align left if the application UI is LTR and right if RTL.
  719. HorizontalAlignment horizontal_alignment_{base::i18n::IsRTL() ? ALIGN_RIGHT
  720. : ALIGN_LEFT};
  721. // Vertical alignment of the text with respect to |display_rect_|. Only
  722. // applicable when |multiline_| is true. The default is to align center.
  723. VerticalAlignment vertical_alignment_ = ALIGN_MIDDLE;
  724. // The text directionality mode, defaults to DIRECTIONALITY_FROM_TEXT.
  725. DirectionalityMode directionality_mode_ = DIRECTIONALITY_FROM_TEXT;
  726. // The cached text direction, potentially computed from the text or UI locale.
  727. // Use GetTextDirection(), do not use this potentially invalid value directly!
  728. mutable base::i18n::TextDirection text_direction_ =
  729. base::i18n::UNKNOWN_DIRECTION;
  730. mutable base::i18n::TextDirection display_text_direction_ =
  731. base::i18n::UNKNOWN_DIRECTION;
  732. // A list of fonts used to render |text_|.
  733. FontList font_list_;
  734. // Logical selection ranges and visual cursor position.
  735. SelectionModel selection_model_;
  736. // The cached cursor bounds; get these bounds with GetUpdatedCursorBounds.
  737. Rect cursor_bounds_;
  738. // Specifies whether the cursor is enabled. If disabled, no space is reserved
  739. // for the cursor when positioning text.
  740. bool cursor_enabled_ = true;
  741. // Whether the current selection has a known direction. That is, whether a
  742. // directional input (e.g. arrow key) has been received for the current
  743. // selection to indicate which end of the selection has the caret. When true,
  744. // directed inputs preserve (rather than replace) the selection affinity.
  745. bool has_directed_selection_ = kSelectionIsAlwaysDirected;
  746. // The color used for drawing selected text.
  747. SkColor selection_color_ = kPlaceholderColor;
  748. // The background color used for drawing the selection when focused.
  749. SkColor selection_background_focused_color_ = kPlaceholderColor;
  750. // Whether the selection visual bounds should be expanded vertically to be
  751. // vertically symmetric with respect to the display rect. Note this flag has
  752. // no effect on multi-line text.
  753. bool symmetric_selection_visual_bounds_ = false;
  754. // The focus state of the text.
  755. bool focused_ = false;
  756. // Composition text range.
  757. Range composition_range_ = Range::InvalidRange();
  758. // Color, baseline, and style breaks, used to modify ranges of text.
  759. // BreakList positions are stored with text indices, not display indices.
  760. // TODO(msw): Expand to support cursor, selection, background, etc. colors.
  761. BreakList<SkColor> colors_{kPlaceholderColor};
  762. BreakList<BaselineStyle> baselines_{NORMAL_BASELINE};
  763. BreakList<int> font_size_overrides_{0};
  764. BreakList<Font::Weight> weights_{Font::Weight::NORMAL};
  765. internal::StyleArray styles_;
  766. mutable BreakList<SkColor> layout_colors_;
  767. mutable BreakList<BaselineStyle> layout_baselines_;
  768. mutable BreakList<int> layout_font_size_overrides_;
  769. mutable BreakList<Font::Weight> layout_weights_;
  770. mutable internal::StyleArray layout_styles_;
  771. // A mapping from text to display text indices for each grapheme. The vector
  772. // contains an ordered sequence of indice pairs. Both sequence |text_index|
  773. // and |display_index| are sorted.
  774. mutable internal::TextToDisplaySequence text_to_display_indices_;
  775. // A flag to obscure actual text with asterisks for password fields.
  776. bool obscured_ = false;
  777. // The index at which the char should be revealed in the obscured text.
  778. absl::optional<size_t> obscured_reveal_index_;
  779. // The maximum length of text to display, 0 forgoes a hard limit.
  780. size_t truncate_length_ = 0;
  781. // The obscured and/or truncated text used to layout the text to display.
  782. mutable std::u16string layout_text_;
  783. // The elided text displayed visually. This is empty if the text
  784. // does not have to be elided, or became empty as a result of eliding.
  785. // TODO(oshima): When the text is elided, painting can be done only with
  786. // display text info, so it should be able to clear the |layout_text_| and
  787. // associated information.
  788. mutable std::u16string display_text_;
  789. // The behavior for eliding, fading, or truncating.
  790. ElideBehavior elide_behavior_ = NO_ELIDE;
  791. // The behavior for eliding whitespace when eliding or truncating.
  792. absl::optional<bool> whitespace_elision_;
  793. // True if the text is elided given the current behavior and display area.
  794. bool text_elided_ = false;
  795. // The minimum height a line should have.
  796. int min_line_height_ = 0;
  797. // Whether the text should be broken into multiple lines. Uses the width of
  798. // |display_rect_| as the width cap.
  799. bool multiline_ = false;
  800. // If multiple lines, the maximum number of lines to render, or 0.
  801. size_t max_lines_ = 0;
  802. // The wrap behavior when the text is broken into lines. Do nothing unless
  803. // |multiline_| is set. The default value is IGNORE_LONG_WORDS.
  804. WordWrapBehavior word_wrap_behavior_ = IGNORE_LONG_WORDS;
  805. // Set to true to suppress subpixel rendering due to non-font reasons (eg.
  806. // if the background is transparent). The default value is false.
  807. bool subpixel_rendering_suppressed_ = false;
  808. // The local display area for rendering the text.
  809. Rect display_rect_;
  810. // Flag to work around a Skia bug with the PDF path (http://crbug.com/133548)
  811. // that results in incorrect clipping when drawing to the document margins.
  812. // This field allows disabling clipping to work around the issue.
  813. // TODO(asvitkine): Remove this when the underlying Skia bug is fixed.
  814. bool clip_to_display_rect_ = true;
  815. // The offset for the text to be drawn, relative to the display area.
  816. // Get this point with GetUpdatedDisplayOffset (or risk using a stale value).
  817. Vector2d display_offset_;
  818. // The baseline of the text. This is determined from the height of the
  819. // display area and the cap height of the font list so the text is vertically
  820. // centered.
  821. int baseline_ = kInvalidBaseline;
  822. // The cached bounds and offset are invalidated by changes to the cursor,
  823. // selection, font, and other operations that adjust the visible text bounds.
  824. bool cached_bounds_and_offset_valid_ = false;
  825. // Text shadows to be drawn.
  826. ShadowValues shadows_;
  827. // Text shaping computed by EnsureLayout. This should be invalidated upon
  828. // OnLayoutTextAttributeChanged and OnDisplayTextAttributeChanged calls.
  829. std::unique_ptr<internal::ShapedText> shaped_text_;
  830. // The ratio of strike-through line thickness to text height.
  831. SkScalar strike_thickness_factor_ = kLineThicknessFactor;
  832. // Extra spacing placed between glyphs; used only for obscured text styling.
  833. int obscured_glyph_spacing_ = 0;
  834. // The cursor position in view space, used to traverse lines of varied widths.
  835. absl::optional<int> cached_cursor_x_;
  836. // Tell whether or not the |layout_text_| needs an update or is up to date.
  837. mutable bool layout_text_up_to_date_ = false;
  838. };
  839. } // namespace gfx
  840. #endif // UI_GFX_RENDER_TEXT_H_