guiHyperText.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. /*
  2. Minetest
  3. Copyright (C) 2019 EvicenceBKidscode / Pierre-Yves Rollo <dev@pyrollo.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "IGUIEnvironment.h"
  17. #include "IGUIElement.h"
  18. #include "guiScrollBar.h"
  19. #include "IGUIFont.h"
  20. #include <vector>
  21. #include <list>
  22. #include <unordered_map>
  23. using namespace irr::gui;
  24. #include "client/fontengine.h"
  25. #include <SColor.h>
  26. #include "client/tile.h"
  27. #include "IVideoDriver.h"
  28. #include "client/client.h"
  29. #include "client/renderingengine.h"
  30. #include "hud.h"
  31. #include "guiHyperText.h"
  32. #include "util/string.h"
  33. bool check_color(const std::string &str)
  34. {
  35. irr::video::SColor color;
  36. return parseColorString(str, color, false);
  37. }
  38. bool check_integer(const std::string &str)
  39. {
  40. if (str.empty())
  41. return false;
  42. char *endptr = nullptr;
  43. strtol(str.c_str(), &endptr, 10);
  44. return *endptr == '\0';
  45. }
  46. // -----------------------------------------------------------------------------
  47. // ParsedText - A text parser
  48. void ParsedText::Element::setStyle(StyleList &style)
  49. {
  50. this->underline = is_yes(style["underline"]);
  51. video::SColor color;
  52. if (parseColorString(style["color"], color, false))
  53. this->color = color;
  54. if (parseColorString(style["hovercolor"], color, false))
  55. this->hovercolor = color;
  56. unsigned int font_size = std::atoi(style["fontsize"].c_str());
  57. FontMode font_mode = FM_Standard;
  58. if (style["fontstyle"] == "mono")
  59. font_mode = FM_Mono;
  60. FontSpec spec(font_size, font_mode,
  61. is_yes(style["bold"]), is_yes(style["italic"]));
  62. // TODO: find a way to check font validity
  63. // Build a new fontengine ?
  64. this->font = g_fontengine->getFont(spec);
  65. if (!this->font)
  66. printf("No font found ! Size=%d, mode=%d, bold=%s, italic=%s\n",
  67. font_size, font_mode, style["bold"].c_str(),
  68. style["italic"].c_str());
  69. }
  70. void ParsedText::Paragraph::setStyle(StyleList &style)
  71. {
  72. if (style["halign"] == "center")
  73. this->halign = HALIGN_CENTER;
  74. else if (style["halign"] == "right")
  75. this->halign = HALIGN_RIGHT;
  76. else if (style["halign"] == "justify")
  77. this->halign = HALIGN_JUSTIFY;
  78. else
  79. this->halign = HALIGN_LEFT;
  80. }
  81. ParsedText::ParsedText(const wchar_t *text)
  82. {
  83. // Default style
  84. m_root_tag.name = "root";
  85. m_root_tag.style["fontsize"] = "16";
  86. m_root_tag.style["fontstyle"] = "normal";
  87. m_root_tag.style["bold"] = "false";
  88. m_root_tag.style["italic"] = "false";
  89. m_root_tag.style["underline"] = "false";
  90. m_root_tag.style["halign"] = "left";
  91. m_root_tag.style["color"] = "#EEEEEE";
  92. m_root_tag.style["hovercolor"] = "#FF0000";
  93. m_active_tags.push_front(&m_root_tag);
  94. m_style = m_root_tag.style;
  95. // Default simple tags definitions
  96. StyleList style;
  97. style["color"] = "#0000FF";
  98. style["underline"] = "true";
  99. m_elementtags["action"] = style;
  100. style.clear();
  101. style["bold"] = "true";
  102. m_elementtags["b"] = style;
  103. style.clear();
  104. style["italic"] = "true";
  105. m_elementtags["i"] = style;
  106. style.clear();
  107. style["underline"] = "true";
  108. m_elementtags["u"] = style;
  109. style.clear();
  110. style["fontstyle"] = "mono";
  111. m_elementtags["mono"] = style;
  112. style.clear();
  113. style["fontsize"] = m_root_tag.style["fontsize"];
  114. m_elementtags["normal"] = style;
  115. style.clear();
  116. style["fontsize"] = "24";
  117. m_elementtags["big"] = style;
  118. style.clear();
  119. style["fontsize"] = "36";
  120. m_elementtags["bigger"] = style;
  121. style.clear();
  122. style["halign"] = "center";
  123. m_paragraphtags["center"] = style;
  124. style.clear();
  125. style["halign"] = "justify";
  126. m_paragraphtags["justify"] = style;
  127. style.clear();
  128. style["halign"] = "left";
  129. m_paragraphtags["left"] = style;
  130. style.clear();
  131. style["halign"] = "right";
  132. m_paragraphtags["right"] = style;
  133. style.clear();
  134. m_element = NULL;
  135. m_paragraph = NULL;
  136. m_end_paragraph_reason = ER_NONE;
  137. parse(text);
  138. }
  139. ParsedText::~ParsedText()
  140. {
  141. for (auto &tag : m_not_root_tags)
  142. delete tag;
  143. }
  144. void ParsedText::parse(const wchar_t *text)
  145. {
  146. wchar_t c;
  147. u32 cursor = 0;
  148. bool escape = false;
  149. while ((c = text[cursor]) != L'\0') {
  150. cursor++;
  151. if (c == L'\r') { // Mac or Windows breaks
  152. if (text[cursor] == L'\n')
  153. cursor++;
  154. // If text has begun, don't skip empty line
  155. if (m_paragraph) {
  156. endParagraph(ER_NEWLINE);
  157. enterElement(ELEMENT_SEPARATOR);
  158. }
  159. escape = false;
  160. continue;
  161. }
  162. if (c == L'\n') { // Unix breaks
  163. // If text has begun, don't skip empty line
  164. if (m_paragraph) {
  165. endParagraph(ER_NEWLINE);
  166. enterElement(ELEMENT_SEPARATOR);
  167. }
  168. escape = false;
  169. continue;
  170. }
  171. if (escape) {
  172. escape = false;
  173. pushChar(c);
  174. continue;
  175. }
  176. if (c == L'\\') {
  177. escape = true;
  178. continue;
  179. }
  180. // Tag check
  181. if (c == L'<') {
  182. u32 newcursor = parseTag(text, cursor);
  183. if (newcursor > 0) {
  184. cursor = newcursor;
  185. continue;
  186. }
  187. }
  188. // Default behavior
  189. pushChar(c);
  190. }
  191. endParagraph(ER_NONE);
  192. }
  193. void ParsedText::endElement()
  194. {
  195. m_element = NULL;
  196. }
  197. void ParsedText::endParagraph(EndReason reason)
  198. {
  199. if (!m_paragraph)
  200. return;
  201. EndReason previous = m_end_paragraph_reason;
  202. m_end_paragraph_reason = reason;
  203. if (m_empty_paragraph && (reason == ER_TAG ||
  204. (reason == ER_NEWLINE && previous == ER_TAG))) {
  205. // Ignore last empty paragraph
  206. m_paragraph = nullptr;
  207. m_paragraphs.pop_back();
  208. return;
  209. }
  210. endElement();
  211. m_paragraph = NULL;
  212. }
  213. void ParsedText::enterParagraph()
  214. {
  215. if (!m_paragraph) {
  216. m_paragraphs.emplace_back();
  217. m_paragraph = &m_paragraphs.back();
  218. m_paragraph->setStyle(m_style);
  219. m_empty_paragraph = true;
  220. }
  221. }
  222. void ParsedText::enterElement(ElementType type)
  223. {
  224. enterParagraph();
  225. if (!m_element || m_element->type != type) {
  226. m_paragraph->elements.emplace_back();
  227. m_element = &m_paragraph->elements.back();
  228. m_element->type = type;
  229. m_element->tags = m_active_tags;
  230. m_element->setStyle(m_style);
  231. }
  232. }
  233. void ParsedText::pushChar(wchar_t c)
  234. {
  235. // New word if needed
  236. if (c == L' ' || c == L'\t') {
  237. if (!m_empty_paragraph)
  238. enterElement(ELEMENT_SEPARATOR);
  239. else
  240. return;
  241. } else {
  242. m_empty_paragraph = false;
  243. enterElement(ELEMENT_TEXT);
  244. }
  245. m_element->text += c;
  246. }
  247. ParsedText::Tag *ParsedText::newTag(const std::string &name, const AttrsList &attrs)
  248. {
  249. endElement();
  250. Tag *newtag = new Tag();
  251. newtag->name = name;
  252. newtag->attrs = attrs;
  253. m_not_root_tags.push_back(newtag);
  254. return newtag;
  255. }
  256. ParsedText::Tag *ParsedText::openTag(const std::string &name, const AttrsList &attrs)
  257. {
  258. Tag *newtag = newTag(name, attrs);
  259. m_active_tags.push_front(newtag);
  260. return newtag;
  261. }
  262. bool ParsedText::closeTag(const std::string &name)
  263. {
  264. bool found = false;
  265. for (auto id = m_active_tags.begin(); id != m_active_tags.end(); ++id)
  266. if ((*id)->name == name) {
  267. m_active_tags.erase(id);
  268. found = true;
  269. break;
  270. }
  271. return found;
  272. }
  273. void ParsedText::parseGenericStyleAttr(
  274. const std::string &name, const std::string &value, StyleList &style)
  275. {
  276. // Color styles
  277. if (name == "color" || name == "hovercolor") {
  278. if (check_color(value))
  279. style[name] = value;
  280. // Boolean styles
  281. } else if (name == "bold" || name == "italic" || name == "underline") {
  282. style[name] = is_yes(value);
  283. } else if (name == "size") {
  284. if (check_integer(value))
  285. style["fontsize"] = value;
  286. } else if (name == "font") {
  287. if (value == "mono" || value == "normal")
  288. style["fontstyle"] = value;
  289. }
  290. }
  291. void ParsedText::parseStyles(const AttrsList &attrs, StyleList &style)
  292. {
  293. for (auto const &attr : attrs)
  294. parseGenericStyleAttr(attr.first, attr.second, style);
  295. }
  296. void ParsedText::globalTag(const AttrsList &attrs)
  297. {
  298. for (const auto &attr : attrs) {
  299. // Only page level style
  300. if (attr.first == "margin") {
  301. if (check_integer(attr.second))
  302. margin = stoi(attr.second.c_str());
  303. } else if (attr.first == "valign") {
  304. if (attr.second == "top")
  305. valign = ParsedText::VALIGN_TOP;
  306. else if (attr.second == "bottom")
  307. valign = ParsedText::VALIGN_BOTTOM;
  308. else if (attr.second == "middle")
  309. valign = ParsedText::VALIGN_MIDDLE;
  310. } else if (attr.first == "background") {
  311. irr::video::SColor color;
  312. if (attr.second == "none") {
  313. background_type = BACKGROUND_NONE;
  314. } else if (parseColorString(attr.second, color, false)) {
  315. background_type = BACKGROUND_COLOR;
  316. background_color = color;
  317. }
  318. // Inheriting styles
  319. } else if (attr.first == "halign") {
  320. if (attr.second == "left" || attr.second == "center" ||
  321. attr.second == "right" ||
  322. attr.second == "justify")
  323. m_root_tag.style["halign"] = attr.second;
  324. // Generic default styles
  325. } else {
  326. parseGenericStyleAttr(attr.first, attr.second, m_root_tag.style);
  327. }
  328. }
  329. }
  330. u32 ParsedText::parseTag(const wchar_t *text, u32 cursor)
  331. {
  332. // Tag name
  333. bool end = false;
  334. std::string name = "";
  335. wchar_t c = text[cursor];
  336. if (c == L'/') {
  337. end = true;
  338. c = text[++cursor];
  339. if (c == L'\0')
  340. return 0;
  341. }
  342. while (c != ' ' && c != '>') {
  343. name += c;
  344. c = text[++cursor];
  345. if (c == L'\0')
  346. return 0;
  347. }
  348. // Tag attributes
  349. AttrsList attrs;
  350. while (c != L'>') {
  351. std::string attr_name = "";
  352. core::stringw attr_val = L"";
  353. while (c == ' ') {
  354. c = text[++cursor];
  355. if (c == L'\0' || c == L'=')
  356. return 0;
  357. }
  358. while (c != L' ' && c != L'=') {
  359. attr_name += (char)c;
  360. c = text[++cursor];
  361. if (c == L'\0' || c == L'>')
  362. return 0;
  363. }
  364. while (c == L' ') {
  365. c = text[++cursor];
  366. if (c == L'\0' || c == L'>')
  367. return 0;
  368. }
  369. if (c != L'=')
  370. return 0;
  371. c = text[++cursor];
  372. if (c == L'\0')
  373. return 0;
  374. while (c != L'>' && c != L' ') {
  375. attr_val += c;
  376. c = text[++cursor];
  377. if (c == L'\0')
  378. return 0;
  379. }
  380. attrs[attr_name] = stringw_to_utf8(attr_val);
  381. }
  382. ++cursor; // Last ">"
  383. // Tag specific processing
  384. StyleList style;
  385. if (name == "global") {
  386. if (end)
  387. return 0;
  388. globalTag(attrs);
  389. } else if (name == "style") {
  390. if (end) {
  391. closeTag(name);
  392. } else {
  393. parseStyles(attrs, style);
  394. openTag(name, attrs)->style = style;
  395. }
  396. endElement();
  397. } else if (name == "img" || name == "item") {
  398. if (end)
  399. return 0;
  400. // Name is a required attribute
  401. if (!attrs.count("name"))
  402. return 0;
  403. // Rotate attribute is only for <item>
  404. if (attrs.count("rotate") && name != "item")
  405. return 0;
  406. // Angle attribute is only for <item>
  407. if (attrs.count("angle") && name != "item")
  408. return 0;
  409. // Ok, element can be created
  410. newTag(name, attrs);
  411. if (name == "img")
  412. enterElement(ELEMENT_IMAGE);
  413. else
  414. enterElement(ELEMENT_ITEM);
  415. m_element->text = utf8_to_stringw(attrs["name"]);
  416. if (attrs.count("float")) {
  417. if (attrs["float"] == "left")
  418. m_element->floating = FLOAT_LEFT;
  419. if (attrs["float"] == "right")
  420. m_element->floating = FLOAT_RIGHT;
  421. }
  422. if (attrs.count("width")) {
  423. int width = stoi(attrs["width"]);
  424. if (width > 0)
  425. m_element->dim.Width = width;
  426. }
  427. if (attrs.count("height")) {
  428. int height = stoi(attrs["height"]);
  429. if (height > 0)
  430. m_element->dim.Height = height;
  431. }
  432. if (attrs.count("angle")) {
  433. std::string str = attrs["angle"];
  434. std::vector<std::string> parts = split(str, ',');
  435. if (parts.size() == 3) {
  436. m_element->angle = v3s16(
  437. rangelim(stoi(parts[0]), -180, 180),
  438. rangelim(stoi(parts[1]), -180, 180),
  439. rangelim(stoi(parts[2]), -180, 180));
  440. m_element->rotation = v3s16(0, 0, 0);
  441. }
  442. }
  443. if (attrs.count("rotate")) {
  444. if (attrs["rotate"] == "yes") {
  445. m_element->rotation = v3s16(0, 100, 0);
  446. } else {
  447. std::string str = attrs["rotate"];
  448. std::vector<std::string> parts = split(str, ',');
  449. if (parts.size() == 3) {
  450. m_element->rotation = v3s16 (
  451. rangelim(stoi(parts[0]), -1000, 1000),
  452. rangelim(stoi(parts[1]), -1000, 1000),
  453. rangelim(stoi(parts[2]), -1000, 1000));
  454. }
  455. }
  456. }
  457. endElement();
  458. } else if (name == "tag") {
  459. // Required attributes
  460. if (!attrs.count("name"))
  461. return 0;
  462. StyleList tagstyle;
  463. parseStyles(attrs, tagstyle);
  464. if (is_yes(attrs["paragraph"]))
  465. m_paragraphtags[attrs["name"]] = tagstyle;
  466. else
  467. m_elementtags[attrs["name"]] = tagstyle;
  468. } else if (name == "action") {
  469. if (end) {
  470. closeTag(name);
  471. } else {
  472. if (!attrs.count("name"))
  473. return 0;
  474. openTag(name, attrs)->style = m_elementtags["action"];
  475. }
  476. } else if (m_elementtags.count(name)) {
  477. if (end) {
  478. closeTag(name);
  479. } else {
  480. openTag(name, attrs)->style = m_elementtags[name];
  481. }
  482. endElement();
  483. } else if (m_paragraphtags.count(name)) {
  484. if (end) {
  485. closeTag(name);
  486. } else {
  487. openTag(name, attrs)->style = m_paragraphtags[name];
  488. }
  489. endParagraph(ER_TAG);
  490. } else
  491. return 0; // Unknown tag
  492. // Update styles accordingly
  493. m_style.clear();
  494. for (auto tag = m_active_tags.crbegin(); tag != m_active_tags.crend(); ++tag)
  495. for (const auto &prop : (*tag)->style)
  496. m_style[prop.first] = prop.second;
  497. return cursor;
  498. }
  499. // -----------------------------------------------------------------------------
  500. // Text Drawer
  501. TextDrawer::TextDrawer(const wchar_t *text, Client *client,
  502. gui::IGUIEnvironment *environment, ISimpleTextureSource *tsrc) :
  503. m_text(text),
  504. m_client(client), m_environment(environment)
  505. {
  506. // Size all elements
  507. for (auto &p : m_text.m_paragraphs) {
  508. for (auto &e : p.elements) {
  509. switch (e.type) {
  510. case ParsedText::ELEMENT_SEPARATOR:
  511. case ParsedText::ELEMENT_TEXT:
  512. if (e.font) {
  513. e.dim.Width = e.font->getDimension(e.text.c_str()).Width;
  514. e.dim.Height = e.font->getDimension(L"Yy").Height;
  515. #if USE_FREETYPE
  516. if (e.font->getType() == irr::gui::EGFT_CUSTOM) {
  517. e.baseline = e.dim.Height - 1 -
  518. ((irr::gui::CGUITTFont *)e.font)->getAscender() / 64;
  519. }
  520. #endif
  521. } else {
  522. e.dim = {0, 0};
  523. }
  524. break;
  525. case ParsedText::ELEMENT_IMAGE:
  526. case ParsedText::ELEMENT_ITEM:
  527. // Resize only non sized items
  528. if (e.dim.Height != 0 && e.dim.Width != 0)
  529. break;
  530. // Default image and item size
  531. core::dimension2d<u32> dim(80, 80);
  532. if (e.type == ParsedText::ELEMENT_IMAGE) {
  533. video::ITexture *texture =
  534. m_client->getTextureSource()->
  535. getTexture(stringw_to_utf8(e.text));
  536. if (texture)
  537. dim = texture->getOriginalSize();
  538. }
  539. if (e.dim.Height == 0)
  540. if (e.dim.Width == 0)
  541. e.dim = dim;
  542. else
  543. e.dim.Height = dim.Height * e.dim.Width /
  544. dim.Width;
  545. else
  546. e.dim.Width = dim.Width * e.dim.Height /
  547. dim.Height;
  548. break;
  549. }
  550. }
  551. }
  552. }
  553. // Get element at given coordinates. Coordinates are inner coordinates (starting
  554. // at 0,0).
  555. ParsedText::Element *TextDrawer::getElementAt(core::position2d<s32> pos)
  556. {
  557. pos.Y -= m_voffset;
  558. for (auto &p : m_text.m_paragraphs) {
  559. for (auto &el : p.elements) {
  560. core::rect<s32> rect(el.pos, el.dim);
  561. if (rect.isPointInside(pos))
  562. return &el;
  563. }
  564. }
  565. return 0;
  566. }
  567. /*
  568. This function places all elements according to given width. Elements have
  569. been previously sized by constructor and will be later drawed by draw.
  570. It may be called each time width changes and resulting height can be
  571. retrieved using getHeight. See GUIHyperText constructor, it uses it once to
  572. test if text fits in window and eventually another time if width is reduced
  573. m_floating because of scrollbar added.
  574. */
  575. void TextDrawer::place(const core::rect<s32> &dest_rect)
  576. {
  577. m_floating.clear();
  578. s32 y = 0;
  579. s32 ymargin = m_text.margin;
  580. // Iterator used :
  581. // p - Current paragraph, walked only once
  582. // el - Current element, walked only once
  583. // e and f - local element and floating operators
  584. for (auto &p : m_text.m_paragraphs) {
  585. // Find and place floating stuff in paragraph
  586. for (auto e = p.elements.begin(); e != p.elements.end(); ++e) {
  587. if (e->floating != ParsedText::FLOAT_NONE) {
  588. if (y)
  589. e->pos.Y = y + std::max(ymargin, e->margin);
  590. else
  591. e->pos.Y = ymargin;
  592. if (e->floating == ParsedText::FLOAT_LEFT)
  593. e->pos.X = m_text.margin;
  594. if (e->floating == ParsedText::FLOAT_RIGHT)
  595. e->pos.X = dest_rect.getWidth() - e->dim.Width -
  596. m_text.margin;
  597. RectWithMargin floating;
  598. floating.rect = core::rect<s32>(e->pos, e->dim);
  599. floating.margin = e->margin;
  600. m_floating.push_back(floating);
  601. }
  602. }
  603. if (y)
  604. y = y + std::max(ymargin, p.margin);
  605. ymargin = p.margin;
  606. // Place non floating stuff
  607. std::vector<ParsedText::Element>::iterator el = p.elements.begin();
  608. while (el != p.elements.end()) {
  609. // Determine line width and y pos
  610. s32 left, right;
  611. s32 nexty = y;
  612. do {
  613. y = nexty;
  614. nexty = 0;
  615. // Inner left & right
  616. left = m_text.margin;
  617. right = dest_rect.getWidth() - m_text.margin;
  618. for (const auto &f : m_floating) {
  619. // Does floating rect intersect paragraph y line?
  620. if (f.rect.UpperLeftCorner.Y - f.margin <= y &&
  621. f.rect.LowerRightCorner.Y + f.margin >= y) {
  622. // Next Y to try if no room left
  623. if (!nexty || f.rect.LowerRightCorner.Y +
  624. std::max(f.margin, p.margin) < nexty) {
  625. nexty = f.rect.LowerRightCorner.Y +
  626. std::max(f.margin, p.margin) + 1;
  627. }
  628. if (f.rect.UpperLeftCorner.X - f.margin <= left &&
  629. f.rect.LowerRightCorner.X + f.margin < right) {
  630. // float on left
  631. if (f.rect.LowerRightCorner.X +
  632. std::max(f.margin, p.margin) > left) {
  633. left = f.rect.LowerRightCorner.X +
  634. std::max(f.margin, p.margin);
  635. }
  636. } else if (f.rect.LowerRightCorner.X + f.margin >= right &&
  637. f.rect.UpperLeftCorner.X - f.margin > left) {
  638. // float on right
  639. if (f.rect.UpperLeftCorner.X -
  640. std::max(f.margin, p.margin) < right)
  641. right = f.rect.UpperLeftCorner.X -
  642. std::max(f.margin, p.margin);
  643. } else if (f.rect.UpperLeftCorner.X - f.margin <= left &&
  644. f.rect.LowerRightCorner.X + f.margin >= right) {
  645. // float taking all space
  646. left = right;
  647. }
  648. else
  649. { // float in the middle -- should not occure yet, see that later
  650. }
  651. }
  652. }
  653. } while (nexty && right <= left);
  654. u32 linewidth = right - left;
  655. float x = left;
  656. u32 charsheight = 0;
  657. u32 charswidth = 0;
  658. u32 wordcount = 0;
  659. // Skip begining of line separators but include them in height
  660. // computation.
  661. while (el != p.elements.end() &&
  662. el->type == ParsedText::ELEMENT_SEPARATOR) {
  663. if (el->floating == ParsedText::FLOAT_NONE) {
  664. el->drawwidth = 0;
  665. if (charsheight < el->dim.Height)
  666. charsheight = el->dim.Height;
  667. }
  668. el++;
  669. }
  670. std::vector<ParsedText::Element>::iterator linestart = el;
  671. std::vector<ParsedText::Element>::iterator lineend = p.elements.end();
  672. // First pass, find elements fitting into line
  673. // (or at least one element)
  674. while (el != p.elements.end() && (charswidth == 0 ||
  675. charswidth + el->dim.Width <= linewidth)) {
  676. if (el->floating == ParsedText::FLOAT_NONE) {
  677. if (el->type != ParsedText::ELEMENT_SEPARATOR) {
  678. lineend = el;
  679. wordcount++;
  680. }
  681. charswidth += el->dim.Width;
  682. if (charsheight < el->dim.Height)
  683. charsheight = el->dim.Height;
  684. }
  685. el++;
  686. }
  687. // Empty line, nothing to place only go down line height
  688. if (lineend == p.elements.end()) {
  689. y += charsheight;
  690. continue;
  691. }
  692. // Point to the first position outside line (may be end())
  693. lineend++;
  694. // Second pass, compute printable line width and adjustments
  695. charswidth = 0;
  696. s32 top = 0;
  697. s32 bottom = 0;
  698. for (auto e = linestart; e != lineend; ++e) {
  699. if (e->floating == ParsedText::FLOAT_NONE) {
  700. charswidth += e->dim.Width;
  701. if (top < (s32)e->dim.Height - e->baseline)
  702. top = e->dim.Height - e->baseline;
  703. if (bottom < e->baseline)
  704. bottom = e->baseline;
  705. }
  706. }
  707. float extraspace = 0.f;
  708. switch (p.halign) {
  709. case ParsedText::HALIGN_CENTER:
  710. x += (linewidth - charswidth) / 2.f;
  711. break;
  712. case ParsedText::HALIGN_JUSTIFY:
  713. if (wordcount > 1 && // Justification only if at least two words
  714. !(lineend == p.elements.end())) // Don't justify last line
  715. extraspace = ((float)(linewidth - charswidth)) / (wordcount - 1);
  716. break;
  717. case ParsedText::HALIGN_RIGHT:
  718. x += linewidth - charswidth;
  719. break;
  720. case ParsedText::HALIGN_LEFT:
  721. break;
  722. }
  723. // Third pass, actually place everything
  724. for (auto e = linestart; e != lineend; ++e) {
  725. if (e->floating != ParsedText::FLOAT_NONE)
  726. continue;
  727. e->pos.X = x;
  728. e->pos.Y = y;
  729. switch (e->type) {
  730. case ParsedText::ELEMENT_TEXT:
  731. case ParsedText::ELEMENT_SEPARATOR:
  732. e->pos.X = x;
  733. // Align char baselines
  734. e->pos.Y = y + top + e->baseline - e->dim.Height;
  735. x += e->dim.Width;
  736. if (e->type == ParsedText::ELEMENT_SEPARATOR)
  737. x += extraspace;
  738. break;
  739. case ParsedText::ELEMENT_IMAGE:
  740. case ParsedText::ELEMENT_ITEM:
  741. x += e->dim.Width;
  742. break;
  743. }
  744. // Draw width for separator can be different than element
  745. // width. This will be important for char effects like
  746. // underline.
  747. e->drawwidth = x - e->pos.X;
  748. }
  749. y += charsheight;
  750. } // Elements (actually lines)
  751. } // Paragraph
  752. // Check if float goes under paragraph
  753. for (const auto &f : m_floating) {
  754. if (f.rect.LowerRightCorner.Y >= y)
  755. y = f.rect.LowerRightCorner.Y;
  756. }
  757. m_height = y + m_text.margin;
  758. // Compute vertical offset according to vertical alignment
  759. if (m_height < dest_rect.getHeight())
  760. switch (m_text.valign) {
  761. case ParsedText::VALIGN_BOTTOM:
  762. m_voffset = dest_rect.getHeight() - m_height;
  763. break;
  764. case ParsedText::VALIGN_MIDDLE:
  765. m_voffset = (dest_rect.getHeight() - m_height) / 2;
  766. break;
  767. case ParsedText::VALIGN_TOP:
  768. default:
  769. m_voffset = 0;
  770. }
  771. else
  772. m_voffset = 0;
  773. }
  774. // Draw text in a rectangle with a given offset. Items are actually placed in
  775. // relative (to upper left corner) coordinates.
  776. void TextDrawer::draw(const core::rect<s32> &clip_rect,
  777. const core::position2d<s32> &dest_offset)
  778. {
  779. irr::video::IVideoDriver *driver = m_environment->getVideoDriver();
  780. core::position2d<s32> offset = dest_offset;
  781. offset.Y += m_voffset;
  782. if (m_text.background_type == ParsedText::BACKGROUND_COLOR)
  783. driver->draw2DRectangle(m_text.background_color, clip_rect);
  784. for (auto &p : m_text.m_paragraphs) {
  785. for (auto &el : p.elements) {
  786. core::rect<s32> rect(el.pos + offset, el.dim);
  787. if (!rect.isRectCollided(clip_rect))
  788. continue;
  789. switch (el.type) {
  790. case ParsedText::ELEMENT_SEPARATOR:
  791. case ParsedText::ELEMENT_TEXT: {
  792. irr::video::SColor color = el.color;
  793. for (auto tag : el.tags)
  794. if (&(*tag) == m_hovertag)
  795. color = el.hovercolor;
  796. if (!el.font)
  797. break;
  798. if (el.type == ParsedText::ELEMENT_TEXT)
  799. el.font->draw(el.text, rect, color, false, true,
  800. &clip_rect);
  801. if (el.underline && el.drawwidth) {
  802. s32 linepos = el.pos.Y + offset.Y +
  803. el.dim.Height - (el.baseline >> 1);
  804. core::rect<s32> linerect(el.pos.X + offset.X,
  805. linepos - (el.baseline >> 3) - 1,
  806. el.pos.X + offset.X + el.drawwidth,
  807. linepos + (el.baseline >> 3));
  808. driver->draw2DRectangle(color, linerect, &clip_rect);
  809. }
  810. } break;
  811. case ParsedText::ELEMENT_IMAGE: {
  812. video::ITexture *texture =
  813. m_client->getTextureSource()->getTexture(
  814. stringw_to_utf8(el.text));
  815. if (texture != 0)
  816. m_environment->getVideoDriver()->draw2DImage(
  817. texture, rect,
  818. irr::core::rect<s32>(
  819. core::position2d<s32>(0, 0),
  820. texture->getOriginalSize()),
  821. &clip_rect, 0, true);
  822. } break;
  823. case ParsedText::ELEMENT_ITEM: {
  824. IItemDefManager *idef = m_client->idef();
  825. ItemStack item;
  826. item.deSerialize(stringw_to_utf8(el.text), idef);
  827. drawItemStack(
  828. m_environment->getVideoDriver(),
  829. g_fontengine->getFont(), item, rect, &clip_rect,
  830. m_client, IT_ROT_OTHER, el.angle, el.rotation
  831. );
  832. } break;
  833. }
  834. }
  835. }
  836. }
  837. // -----------------------------------------------------------------------------
  838. // GUIHyperText - The formated text area formspec item
  839. //! constructor
  840. GUIHyperText::GUIHyperText(const wchar_t *text, IGUIEnvironment *environment,
  841. IGUIElement *parent, s32 id, const core::rect<s32> &rectangle,
  842. Client *client, ISimpleTextureSource *tsrc) :
  843. IGUIElement(EGUIET_ELEMENT, environment, parent, id, rectangle),
  844. m_client(client), m_vscrollbar(nullptr),
  845. m_drawer(text, client, environment, tsrc), m_text_scrollpos(0, 0)
  846. {
  847. #ifdef _DEBUG
  848. setDebugName("GUIHyperText");
  849. #endif
  850. IGUISkin *skin = 0;
  851. if (Environment)
  852. skin = Environment->getSkin();
  853. m_scrollbar_width = skin ? skin->getSize(gui::EGDS_SCROLLBAR_SIZE) : 16;
  854. core::rect<s32> rect = irr::core::rect<s32>(
  855. RelativeRect.getWidth() - m_scrollbar_width, 0,
  856. RelativeRect.getWidth(), RelativeRect.getHeight());
  857. m_vscrollbar = new GUIScrollBar(Environment, this, -1, rect, false, true);
  858. m_vscrollbar->setVisible(false);
  859. }
  860. //! destructor
  861. GUIHyperText::~GUIHyperText()
  862. {
  863. m_vscrollbar->remove();
  864. m_vscrollbar->drop();
  865. }
  866. ParsedText::Element *GUIHyperText::getElementAt(s32 X, s32 Y)
  867. {
  868. core::position2d<s32> pos{X, Y};
  869. pos -= m_display_text_rect.UpperLeftCorner;
  870. pos -= m_text_scrollpos;
  871. return m_drawer.getElementAt(pos);
  872. }
  873. void GUIHyperText::checkHover(s32 X, s32 Y)
  874. {
  875. m_drawer.m_hovertag = nullptr;
  876. if (AbsoluteRect.isPointInside(core::position2d<s32>(X, Y))) {
  877. ParsedText::Element *element = getElementAt(X, Y);
  878. if (element) {
  879. for (auto &tag : element->tags) {
  880. if (tag->name == "action") {
  881. m_drawer.m_hovertag = tag;
  882. break;
  883. }
  884. }
  885. }
  886. }
  887. #ifndef HAVE_TOUCHSCREENGUI
  888. if (m_drawer.m_hovertag)
  889. RenderingEngine::get_raw_device()->getCursorControl()->setActiveIcon(
  890. gui::ECI_HAND);
  891. else
  892. RenderingEngine::get_raw_device()->getCursorControl()->setActiveIcon(
  893. gui::ECI_NORMAL);
  894. #endif
  895. }
  896. bool GUIHyperText::OnEvent(const SEvent &event)
  897. {
  898. // Scroll bar
  899. if (event.EventType == EET_GUI_EVENT &&
  900. event.GUIEvent.EventType == EGET_SCROLL_BAR_CHANGED &&
  901. event.GUIEvent.Caller == m_vscrollbar) {
  902. m_text_scrollpos.Y = -m_vscrollbar->getPos();
  903. }
  904. // Reset hover if element left
  905. if (event.EventType == EET_GUI_EVENT &&
  906. event.GUIEvent.EventType == EGET_ELEMENT_LEFT) {
  907. m_drawer.m_hovertag = nullptr;
  908. #ifndef HAVE_TOUCHSCREENGUI
  909. gui::ICursorControl *cursor_control =
  910. RenderingEngine::get_raw_device()->getCursorControl();
  911. if (cursor_control->isVisible())
  912. cursor_control->setActiveIcon(gui::ECI_NORMAL);
  913. #endif
  914. }
  915. if (event.EventType == EET_MOUSE_INPUT_EVENT) {
  916. if (event.MouseInput.Event == EMIE_MOUSE_MOVED)
  917. checkHover(event.MouseInput.X, event.MouseInput.Y);
  918. if (event.MouseInput.Event == EMIE_MOUSE_WHEEL && m_vscrollbar->isVisible()) {
  919. m_vscrollbar->setPos(m_vscrollbar->getPos() -
  920. event.MouseInput.Wheel * m_vscrollbar->getSmallStep());
  921. m_text_scrollpos.Y = -m_vscrollbar->getPos();
  922. m_drawer.draw(m_display_text_rect, m_text_scrollpos);
  923. checkHover(event.MouseInput.X, event.MouseInput.Y);
  924. return true;
  925. } else if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
  926. ParsedText::Element *element = getElementAt(
  927. event.MouseInput.X, event.MouseInput.Y);
  928. if (element) {
  929. for (auto &tag : element->tags) {
  930. if (tag->name == "action") {
  931. Text = core::stringw(L"action:") +
  932. utf8_to_stringw(tag->attrs["name"]);
  933. if (Parent) {
  934. SEvent newEvent;
  935. newEvent.EventType = EET_GUI_EVENT;
  936. newEvent.GUIEvent.Caller = this;
  937. newEvent.GUIEvent.Element = 0;
  938. newEvent.GUIEvent.EventType = EGET_BUTTON_CLICKED;
  939. Parent->OnEvent(newEvent);
  940. }
  941. break;
  942. }
  943. }
  944. }
  945. }
  946. }
  947. return IGUIElement::OnEvent(event);
  948. }
  949. //! draws the element and its children
  950. void GUIHyperText::draw()
  951. {
  952. if (!IsVisible)
  953. return;
  954. // Text
  955. m_display_text_rect = AbsoluteRect;
  956. m_drawer.place(m_display_text_rect);
  957. // Show scrollbar if text overflow
  958. if (m_drawer.getHeight() > m_display_text_rect.getHeight()) {
  959. m_vscrollbar->setSmallStep(m_display_text_rect.getHeight() * 0.1f);
  960. m_vscrollbar->setLargeStep(m_display_text_rect.getHeight() * 0.5f);
  961. m_vscrollbar->setMax(m_drawer.getHeight() - m_display_text_rect.getHeight());
  962. m_vscrollbar->setVisible(true);
  963. m_vscrollbar->setPageSize(s32(m_drawer.getHeight()));
  964. core::rect<s32> smaller_rect = m_display_text_rect;
  965. smaller_rect.LowerRightCorner.X -= m_scrollbar_width;
  966. m_drawer.place(smaller_rect);
  967. } else {
  968. m_vscrollbar->setMax(0);
  969. m_vscrollbar->setPos(0);
  970. m_vscrollbar->setVisible(false);
  971. }
  972. m_drawer.draw(AbsoluteClippingRect,
  973. m_display_text_rect.UpperLeftCorner + m_text_scrollpos);
  974. // draw children
  975. IGUIElement::draw();
  976. }