2
0

ElementTextDefault.cpp 19 KB

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