ElementTextDefault.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "precompiled.h"
  29. #include "ElementTextDefault.h"
  30. #include "ElementDefinition.h"
  31. #include "ElementStyle.h"
  32. #include "FontFaceHandleDefault.h"
  33. #include "../../Include/RmlUi/Core/ElementDocument.h"
  34. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  35. #include "../../Include/RmlUi/Core/Event.h"
  36. #include "../../Include/RmlUi/Core/Property.h"
  37. namespace Rml {
  38. namespace Core {
  39. static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation);
  40. static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline);
  41. ElementTextDefault::ElementTextDefault(const String& tag) : ElementText(tag), colour(255, 255, 255), decoration(this)
  42. {
  43. dirty_layout_on_change = true;
  44. generated_decoration = Style::TextDecoration::None;
  45. decoration_property = Style::TextDecoration::None;
  46. geometry_dirty = true;
  47. font_configuration = -1;
  48. font_dirty = true;
  49. }
  50. ElementTextDefault::~ElementTextDefault()
  51. {
  52. }
  53. void ElementTextDefault::SetText(const String& _text)
  54. {
  55. if (text != _text)
  56. {
  57. text = _text;
  58. if (dirty_layout_on_change)
  59. DirtyLayout();
  60. }
  61. }
  62. const String& ElementTextDefault::GetText() const
  63. {
  64. return text;
  65. }
  66. void ElementTextDefault::OnRender()
  67. {
  68. RMLUI_ZoneScoped;
  69. FontFaceHandle font_face_handle = GetFontFaceHandle();
  70. if (font_face_handle == 0)
  71. return;
  72. // If our font configuration has potentially changed, update it and force a geometry
  73. // generation if necessary.
  74. if (font_dirty && UpdateFontConfiguration())
  75. geometry_dirty = true;
  76. // Regenerate the geometry if the colour or font configuration has altered.
  77. if (geometry_dirty)
  78. GenerateGeometry(font_face_handle);
  79. Vector2f translation = GetAbsoluteOffset();
  80. bool render = true;
  81. Vector2i clip_origin;
  82. Vector2i clip_dimensions;
  83. if (GetContext()->GetActiveClipRegion(clip_origin, clip_dimensions))
  84. {
  85. float clip_top = (float)clip_origin.y;
  86. float clip_left = (float)clip_origin.x;
  87. float clip_right = (float)(clip_origin.x + clip_dimensions.x);
  88. float clip_bottom = (float)(clip_origin.y + clip_dimensions.y);
  89. float line_height = (float)GetFontEngineInterface()->GetLineHeight(GetFontFaceHandle());
  90. render = false;
  91. for (size_t i = 0; i < lines.size(); ++i)
  92. {
  93. const Line& line = lines[i];
  94. float x = translation.x + line.position.x;
  95. float y = translation.y + line.position.y;
  96. bool render_line = !(x > clip_right);
  97. render_line = render_line && !(x + line.width < clip_left);
  98. render_line = render_line && !(y - line_height > clip_bottom);
  99. render_line = render_line && !(y < clip_top);
  100. if (render_line)
  101. {
  102. render = true;
  103. break;
  104. }
  105. }
  106. }
  107. translation = translation.Round();
  108. if (render)
  109. {
  110. for (size_t i = 0; i < geometry.size(); ++i)
  111. geometry[i].Render(translation);
  112. }
  113. if (decoration_property != Style::TextDecoration::None)
  114. decoration.Render(translation);
  115. }
  116. // Generates a token of text from this element, returning only the width.
  117. bool ElementTextDefault::GenerateToken(float& token_width, int line_begin)
  118. {
  119. RMLUI_ZoneScoped;
  120. // Bail if we don't have a valid font face.
  121. FontFaceHandle font_face_handle = GetFontFaceHandle();
  122. if (font_face_handle == 0 ||
  123. line_begin >= (int) text.size())
  124. return 0;
  125. // Determine how we are processing white-space while formatting the text.
  126. using namespace Style;
  127. auto& computed = GetComputedValues();
  128. WhiteSpace white_space_property = computed.white_space;
  129. bool collapse_white_space = white_space_property == WhiteSpace::Normal ||
  130. white_space_property == WhiteSpace::Nowrap ||
  131. white_space_property == WhiteSpace::Preline;
  132. bool break_at_endline = white_space_property == WhiteSpace::Pre ||
  133. white_space_property == WhiteSpace::Prewrap ||
  134. white_space_property == WhiteSpace::Preline;
  135. const char* token_begin = text.c_str() + line_begin;
  136. String token;
  137. BuildToken(token, token_begin, text.c_str() + text.size(), true, collapse_white_space, break_at_endline, computed.text_transform);
  138. token_width = (float) GetFontEngineInterface()->GetStringWidth(font_face_handle, token);
  139. return LastToken(token_begin, text.c_str() + text.size(), collapse_white_space, break_at_endline);
  140. }
  141. // Generates a line of text rendered from this element
  142. bool ElementTextDefault::GenerateLine(String& line, int& line_length, float& line_width, int line_begin, float maximum_line_width, float right_spacing_width, bool trim_whitespace_prefix)
  143. {
  144. RMLUI_ZoneScoped;
  145. FontFaceHandle font_face_handle = GetFontFaceHandle();
  146. // Initialise the output variables.
  147. line.clear();
  148. line_length = 0;
  149. line_width = 0;
  150. // Bail if we don't have a valid font face.
  151. if (font_face_handle == 0)
  152. return true;
  153. // Determine how we are processing white-space while formatting the text.
  154. using namespace Style;
  155. auto& computed = GetComputedValues();
  156. WhiteSpace white_space_property = computed.white_space;
  157. bool collapse_white_space = white_space_property == WhiteSpace::Normal ||
  158. white_space_property == WhiteSpace::Nowrap ||
  159. white_space_property == WhiteSpace::Preline;
  160. bool break_at_line = maximum_line_width >= 0 &&
  161. (white_space_property == WhiteSpace::Normal ||
  162. white_space_property == WhiteSpace::Prewrap ||
  163. white_space_property == WhiteSpace::Preline);
  164. bool break_at_endline = white_space_property == WhiteSpace::Pre ||
  165. white_space_property == WhiteSpace::Prewrap ||
  166. white_space_property == WhiteSpace::Preline;
  167. // Determine what (if any) text transformation we are putting the characters through.
  168. TextTransform text_transform_property = computed.text_transform;
  169. // Starting at the line_begin character, we generate sections of the text (we'll call them tokens) depending on the
  170. // white-space parsing parameters. Each section is then appended to the line if it can fit. If not, or if an
  171. // endline is found (and we're processing them), then the line is ended. kthxbai!
  172. const char* token_begin = text.c_str() + line_begin;
  173. const char* string_end = text.c_str() + text.size();
  174. while (token_begin != string_end)
  175. {
  176. String token;
  177. const char* next_token_begin = token_begin;
  178. CodePoint previous_codepoint = CodePoint::Null;
  179. if (!line.empty())
  180. previous_codepoint = StringUtilities::ToCodePoint(StringUtilities::SeekBackU8(&line.back(), line.data()));
  181. // Generate the next token and determine its pixel-length.
  182. bool break_line = BuildToken(token, next_token_begin, string_end, line.empty() && trim_whitespace_prefix, collapse_white_space, break_at_endline, text_transform_property);
  183. int token_width = GetFontEngineInterface()->GetStringWidth(font_face_handle, token, previous_codepoint);
  184. // If we're breaking to fit a line box, check if the token can fit on the line before we add it.
  185. if (break_at_line)
  186. {
  187. if (!line.empty() &&
  188. (line_width + token_width > maximum_line_width ||
  189. (LastToken(next_token_begin, string_end, collapse_white_space, break_at_endline) && line_width + token_width > maximum_line_width - right_spacing_width)))
  190. {
  191. return false;
  192. }
  193. }
  194. // The token can fit on the end of the line, so add it onto the end and increment our width and length
  195. // counters.
  196. line += token;
  197. line_length += (int)(next_token_begin - token_begin);
  198. line_width += token_width;
  199. // Break out of the loop if an endline was forced.
  200. if (break_line)
  201. return false;
  202. // Set the beginning of the next token.
  203. token_begin = next_token_begin;
  204. }
  205. return true;
  206. }
  207. // Clears all lines of generated text and prepares the element for generating new lines.
  208. void ElementTextDefault::ClearLines()
  209. {
  210. // Clear the rendering information.
  211. for (size_t i = 0; i < geometry.size(); ++i)
  212. geometry[i].Release(true);
  213. lines.clear();
  214. decoration.Release(true);
  215. }
  216. // Adds a new line into the text element.
  217. void ElementTextDefault::AddLine(const Vector2f& line_position, const String& line)
  218. {
  219. FontFaceHandle font_face_handle = GetFontFaceHandle();
  220. if (font_face_handle == 0)
  221. return;
  222. if (font_dirty)
  223. UpdateFontConfiguration();
  224. Vector2f baseline_position = line_position + Vector2f(0.0f, (float)GetFontEngineInterface()->GetLineHeight(font_face_handle) - GetFontEngineInterface()->GetBaseline(font_face_handle));
  225. lines.push_back(Line(line, baseline_position));
  226. geometry_dirty = true;
  227. }
  228. // Prevents the element from dirtying its document's layout when its text is changed.
  229. void ElementTextDefault::SuppressAutoLayout()
  230. {
  231. dirty_layout_on_change = false;
  232. }
  233. void ElementTextDefault::OnPropertyChange(const PropertyIdSet& changed_properties)
  234. {
  235. RMLUI_ZoneScoped;
  236. Element::OnPropertyChange(changed_properties);
  237. bool colour_changed = false;
  238. bool font_face_changed = false;
  239. auto& computed = GetComputedValues();
  240. if (changed_properties.Contains(PropertyId::Color) ||
  241. changed_properties.Contains(PropertyId::Opacity))
  242. {
  243. // Fetch our (potentially) new colour.
  244. Colourb new_colour = computed.color;
  245. float opacity = computed.opacity;
  246. new_colour.alpha = byte(opacity * float(new_colour.alpha));
  247. colour_changed = colour != new_colour;
  248. if (colour_changed)
  249. colour = new_colour;
  250. }
  251. if (changed_properties.Contains(PropertyId::FontFamily) ||
  252. changed_properties.Contains(PropertyId::FontWeight) ||
  253. changed_properties.Contains(PropertyId::FontStyle) ||
  254. changed_properties.Contains(PropertyId::FontSize))
  255. {
  256. font_face_changed = true;
  257. geometry.clear();
  258. font_dirty = true;
  259. }
  260. if (changed_properties.Contains(PropertyId::TextDecoration))
  261. {
  262. decoration_property = computed.text_decoration;
  263. if (decoration_property != Style::TextDecoration::None)
  264. {
  265. if (decoration_property != generated_decoration)
  266. {
  267. decoration.Release(true);
  268. FontFaceHandle font_face_handle = GetFontFaceHandle();
  269. if (font_face_handle != 0)
  270. {
  271. for (size_t i = 0; i < lines.size(); ++i)
  272. GenerateDecoration(font_face_handle, lines[i]);
  273. }
  274. generated_decoration = decoration_property;
  275. }
  276. }
  277. }
  278. if (font_face_changed)
  279. {
  280. // We have to let our document know we need to be regenerated.
  281. if (dirty_layout_on_change)
  282. DirtyLayout();
  283. }
  284. else if (colour_changed)
  285. {
  286. // Force the geometry to be regenerated.
  287. geometry_dirty = true;
  288. // Re-colour the decoration geometry.
  289. std::vector< Vertex >& vertices = decoration.GetVertices();
  290. for (size_t i = 0; i < vertices.size(); ++i)
  291. vertices[i].colour = colour;
  292. decoration.Release();
  293. }
  294. }
  295. // Returns the RML of this element
  296. void ElementTextDefault::GetRML(String& content)
  297. {
  298. content += text;
  299. }
  300. // Updates the configuration this element uses for its font.
  301. bool ElementTextDefault::UpdateFontConfiguration()
  302. {
  303. RMLUI_ZoneScoped;
  304. if (GetFontFaceHandle() == 0)
  305. return false;
  306. font_dirty = false;
  307. static const FontEffectList empty_font_effects;
  308. // Fetch the font-effect for this text element
  309. const FontEffectList* font_effects = &empty_font_effects;
  310. if (const FontEffects* effects = GetComputedValues().font_effect.get())
  311. font_effects = &effects->list;
  312. // Request a font layer configuration to match this set of effects. If this is different from
  313. // our old configuration, then return true to indicate we'll need to regenerate geometry.
  314. int new_configuration = GetFontEngineInterface()->GenerateLayerConfiguration(GetFontFaceHandle(), *font_effects);
  315. if (new_configuration != font_configuration)
  316. {
  317. font_configuration = new_configuration;
  318. return true;
  319. }
  320. return false;
  321. }
  322. // Clears and regenerates all of the text's geometry.
  323. void ElementTextDefault::GenerateGeometry(const FontFaceHandle font_face_handle)
  324. {
  325. RMLUI_ZoneScopedC(0xD2691E);
  326. // Release the old geometry ...
  327. for (size_t i = 0; i < geometry.size(); ++i)
  328. geometry[i].Release(true);
  329. // ... and generate it all again!
  330. for (size_t i = 0; i < lines.size(); ++i)
  331. GenerateGeometry(font_face_handle, lines[i]);
  332. geometry_dirty = false;
  333. }
  334. void ElementTextDefault::GenerateGeometry(const FontFaceHandle font_face_handle, Line& line)
  335. {
  336. line.width = GetFontEngineInterface()->GenerateString(font_face_handle, geometry, line.text, line.position, colour, font_configuration);
  337. for (size_t i = 0; i < geometry.size(); ++i)
  338. geometry[i].SetHostElement(this);
  339. if (decoration_property != Style::TextDecoration::None)
  340. GenerateDecoration(font_face_handle, line);
  341. }
  342. // Generates any geometry necessary for rendering a line decoration (underline, strike-through, etc).
  343. void ElementTextDefault::GenerateDecoration(const FontFaceHandle font_face_handle, const Line& line)
  344. {
  345. RMLUI_ZoneScopedC(0xA52A2A);
  346. GeometryUtilities::GenerateLine(font_face_handle, &decoration, line.position, line.width, decoration_property, colour);
  347. }
  348. static bool BuildToken(String& token, const char*& token_begin, const char* string_end, bool first_token, bool collapse_white_space, bool break_at_endline, Style::TextTransform text_transformation)
  349. {
  350. RMLUI_ASSERT(token_begin != string_end);
  351. token.reserve(string_end - token_begin + token.size());
  352. // Check what the first character of the token is; all we need to know is if it is white-space or not.
  353. bool parsing_white_space = StringUtilities::IsWhitespace(*token_begin);
  354. // Loop through the string from the token's beginning until we find an end to the token. This can occur in various
  355. // places, depending on the white-space processing;
  356. // - at the end of a section of non-white-space characters,
  357. // - at the end of a section of white-space characters, if we're not collapsing white-space,
  358. // - at an endline token, if we're breaking on endlines.
  359. while (token_begin != string_end)
  360. {
  361. bool force_non_whitespace = false;
  362. char character = *token_begin;
  363. const char* escape_begin = token_begin;
  364. // Check for an ampersand; if we find one, we've got an HTML escaped character.
  365. if (character == '&')
  366. {
  367. // Find the terminating ';'.
  368. while (token_begin != string_end &&
  369. *token_begin != ';')
  370. ++token_begin;
  371. // If we couldn't find the ';', print the token like normal text.
  372. if (token_begin == string_end)
  373. {
  374. token_begin = escape_begin;
  375. }
  376. // We could find a ';', parse the escape code. If the escape code is recognised, set the parsed character
  377. // to the appropriate one. If it is a non-breaking space, prevent it being picked up as whitespace. If it
  378. // is not recognised, print the token like normal text.
  379. else
  380. {
  381. String escape_code(escape_begin + 1, token_begin);
  382. if (escape_code == "lt")
  383. character = '<';
  384. else if (escape_code == "gt")
  385. character = '>';
  386. else if (escape_code == "amp")
  387. character = '&';
  388. else if (escape_code == "quot")
  389. character = '"';
  390. else if (escape_code == "nbsp")
  391. {
  392. character = ' ';
  393. force_non_whitespace = true;
  394. }
  395. else
  396. token_begin = escape_begin;
  397. }
  398. }
  399. // Check for an endline token; if we're breaking on endlines and we find one, then return true to indicate a
  400. // forced break.
  401. if (break_at_endline &&
  402. character == '\n')
  403. {
  404. token += '\n';
  405. token_begin++;
  406. return true;
  407. }
  408. // If we've transitioned from white-space characters to non-white-space characters, or vice-versa, then check
  409. // if should terminate the token; if we're not collapsing white-space, then yes (as sections of white-space are
  410. // non-breaking), otherwise only if we've transitioned from characters to white-space.
  411. bool white_space = !force_non_whitespace && StringUtilities::IsWhitespace(character);
  412. if (white_space != parsing_white_space)
  413. {
  414. if (!collapse_white_space)
  415. {
  416. // Restore pointer to the beginning of the escaped token, if we processed an escape code.
  417. token_begin = escape_begin;
  418. return false;
  419. }
  420. // We're collapsing white-space; we only tokenise words, not white-space, so we're only done tokenising
  421. // once we've begun parsing non-white-space and then found white-space.
  422. if (!parsing_white_space)
  423. {
  424. // However, if we are the last non-whitespace character in the string, and there are trailing
  425. // whitespace characters after this token, then we need to append a single space to the end of this
  426. // token.
  427. if (token_begin != string_end &&
  428. LastToken(token_begin, string_end, collapse_white_space, break_at_endline))
  429. token += ' ';
  430. return false;
  431. }
  432. // We've transitioned from white-space to non-white-space, so we append a single white-space character.
  433. if (!first_token)
  434. token += ' ';
  435. parsing_white_space = false;
  436. }
  437. // If the current character is white-space, we'll append a space character to the token if we're not collapsing
  438. // sections of white-space.
  439. if (white_space)
  440. {
  441. if (!collapse_white_space)
  442. token += ' ';
  443. }
  444. else
  445. {
  446. if (text_transformation == Style::TextTransform::Uppercase)
  447. {
  448. if (character >= 'a' && character <= 'z')
  449. character += ('A' - 'a');
  450. }
  451. else if (text_transformation == Style::TextTransform::Lowercase)
  452. {
  453. if (character >= 'A' && character <= 'Z')
  454. character -= ('A' - 'a');
  455. }
  456. token += character;
  457. }
  458. ++token_begin;
  459. }
  460. return false;
  461. }
  462. static bool LastToken(const char* token_begin, const char* string_end, bool collapse_white_space, bool break_at_endline)
  463. {
  464. bool last_token = (token_begin == string_end);
  465. if (collapse_white_space &&
  466. !last_token)
  467. {
  468. last_token = true;
  469. const char* character = token_begin;
  470. while (character != string_end)
  471. {
  472. if (!StringUtilities::IsWhitespace(*character) ||
  473. (break_at_endline && *character == '\n'))
  474. {
  475. last_token = false;
  476. break;
  477. }
  478. character++;
  479. }
  480. }
  481. return last_token;
  482. }
  483. }
  484. }