guiHyperText.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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 "guiHyperText.h"
  17. #include "guiScrollBar.h"
  18. #include "client/fontengine.h"
  19. #include "IVideoDriver.h"
  20. #include "client/client.h"
  21. #include "client/renderingengine.h"
  22. #include "hud.h"
  23. #include "inventory.h"
  24. #include "util/string.h"
  25. #include "irrlicht_changes/CGUITTFont.h"
  26. #include "mainmenumanager.h"
  27. #include "porting.h"
  28. using namespace irr::gui;
  29. static bool check_color(const std::string &str)
  30. {
  31. irr::video::SColor color;
  32. return parseColorString(str, color, false);
  33. }
  34. static bool check_integer(const std::string &str)
  35. {
  36. if (str.empty())
  37. return false;
  38. char *endptr = nullptr;
  39. strtol(str.c_str(), &endptr, 10);
  40. return *endptr == '\0';
  41. }
  42. // -----------------------------------------------------------------------------
  43. // ParsedText - A text parser
  44. void ParsedText::Element::setStyle(StyleList &style)
  45. {
  46. this->underline = is_yes(style["underline"]);
  47. video::SColor color;
  48. if (parseColorString(style["color"], color, false))
  49. this->color = color;
  50. if (parseColorString(style["hovercolor"], color, false))
  51. this->hovercolor = color;
  52. unsigned int font_size = std::atoi(style["fontsize"].c_str());
  53. FontMode font_mode = FM_Standard;
  54. if (style["fontstyle"] == "mono")
  55. font_mode = FM_Mono;
  56. // hypertext[] only accepts absolute font size values and has a hardcoded
  57. // default font size of 16. This is the only way to make hypertext[]
  58. // respect font size settings that I can think of.
  59. font_size = myround(font_size / 16.0f * g_fontengine->getFontSize(font_mode));
  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. enterElement(ELEMENT_TEXT);
  243. m_empty_paragraph = false;
  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), m_client(client), m_tsrc(tsrc), m_guienv(environment)
  504. {
  505. // Size all elements
  506. for (auto &p : m_text.m_paragraphs) {
  507. for (auto &e : p.elements) {
  508. switch (e.type) {
  509. case ParsedText::ELEMENT_SEPARATOR:
  510. case ParsedText::ELEMENT_TEXT:
  511. if (e.font) {
  512. e.dim.Width = e.font->getDimension(e.text.c_str()).Width;
  513. e.dim.Height = e.font->getDimension(L"Yy").Height;
  514. if (e.font->getType() == irr::gui::EGFT_CUSTOM) {
  515. CGUITTFont *tmp = static_cast<CGUITTFont*>(e.font);
  516. e.baseline = e.dim.Height - 1 - tmp->getAscender() / 64;
  517. }
  518. } else {
  519. e.dim = {0, 0};
  520. }
  521. break;
  522. case ParsedText::ELEMENT_IMAGE:
  523. case ParsedText::ELEMENT_ITEM:
  524. // Resize only non sized items
  525. if (e.dim.Height != 0 && e.dim.Width != 0)
  526. break;
  527. // Default image and item size
  528. core::dimension2d<u32> dim(80, 80);
  529. if (e.type == ParsedText::ELEMENT_IMAGE) {
  530. video::ITexture *texture =
  531. m_tsrc->
  532. getTexture(stringw_to_utf8(e.text));
  533. if (texture)
  534. dim = texture->getOriginalSize();
  535. }
  536. if (e.dim.Height == 0)
  537. if (e.dim.Width == 0)
  538. e.dim = dim;
  539. else
  540. e.dim.Height = dim.Height * e.dim.Width /
  541. dim.Width;
  542. else
  543. e.dim.Width = dim.Width * e.dim.Height /
  544. dim.Height;
  545. break;
  546. }
  547. }
  548. }
  549. }
  550. // Get element at given coordinates. Coordinates are inner coordinates (starting
  551. // at 0,0).
  552. ParsedText::Element *TextDrawer::getElementAt(core::position2d<s32> pos)
  553. {
  554. pos.Y -= m_voffset;
  555. for (auto &p : m_text.m_paragraphs) {
  556. for (auto &el : p.elements) {
  557. core::rect<s32> rect(el.pos, el.dim);
  558. if (rect.isPointInside(pos))
  559. return &el;
  560. }
  561. }
  562. return 0;
  563. }
  564. /*
  565. This function places all elements according to given width. Elements have
  566. been previously sized by constructor and will be later drawed by draw.
  567. It may be called each time width changes and resulting height can be
  568. retrieved using getHeight. See GUIHyperText constructor, it uses it once to
  569. test if text fits in window and eventually another time if width is reduced
  570. m_floating because of scrollbar added.
  571. */
  572. void TextDrawer::place(const core::rect<s32> &dest_rect)
  573. {
  574. m_floating.clear();
  575. s32 y = 0;
  576. s32 ymargin = m_text.margin;
  577. // Iterator used :
  578. // p - Current paragraph, walked only once
  579. // el - Current element, walked only once
  580. // e and f - local element and floating operators
  581. for (auto &p : m_text.m_paragraphs) {
  582. // Find and place floating stuff in paragraph
  583. for (auto e = p.elements.begin(); e != p.elements.end(); ++e) {
  584. if (e->floating != ParsedText::FLOAT_NONE) {
  585. if (y)
  586. e->pos.Y = y + std::max(ymargin, e->margin);
  587. else
  588. e->pos.Y = ymargin;
  589. if (e->floating == ParsedText::FLOAT_LEFT)
  590. e->pos.X = m_text.margin;
  591. if (e->floating == ParsedText::FLOAT_RIGHT)
  592. e->pos.X = dest_rect.getWidth() - e->dim.Width -
  593. m_text.margin;
  594. RectWithMargin floating;
  595. floating.rect = core::rect<s32>(e->pos, e->dim);
  596. floating.margin = e->margin;
  597. m_floating.push_back(floating);
  598. }
  599. }
  600. if (y)
  601. y = y + std::max(ymargin, p.margin);
  602. ymargin = p.margin;
  603. // Place non floating stuff
  604. std::vector<ParsedText::Element>::iterator el = p.elements.begin();
  605. while (el != p.elements.end()) {
  606. // Determine line width and y pos
  607. s32 left, right;
  608. s32 nexty = y;
  609. do {
  610. y = nexty;
  611. nexty = 0;
  612. // Inner left & right
  613. left = m_text.margin;
  614. right = dest_rect.getWidth() - m_text.margin;
  615. for (const auto &f : m_floating) {
  616. // Does floating rect intersect paragraph y line?
  617. if (f.rect.UpperLeftCorner.Y - f.margin <= y &&
  618. f.rect.LowerRightCorner.Y + f.margin >= y) {
  619. // Next Y to try if no room left
  620. if (!nexty || f.rect.LowerRightCorner.Y +
  621. std::max(f.margin, p.margin) < nexty) {
  622. nexty = f.rect.LowerRightCorner.Y +
  623. std::max(f.margin, p.margin) + 1;
  624. }
  625. if (f.rect.UpperLeftCorner.X - f.margin <= left &&
  626. f.rect.LowerRightCorner.X + f.margin < right) {
  627. // float on left
  628. if (f.rect.LowerRightCorner.X +
  629. std::max(f.margin, p.margin) > left) {
  630. left = f.rect.LowerRightCorner.X +
  631. std::max(f.margin, p.margin);
  632. }
  633. } else if (f.rect.LowerRightCorner.X + f.margin >= right &&
  634. f.rect.UpperLeftCorner.X - f.margin > left) {
  635. // float on right
  636. if (f.rect.UpperLeftCorner.X -
  637. std::max(f.margin, p.margin) < right)
  638. right = f.rect.UpperLeftCorner.X -
  639. std::max(f.margin, p.margin);
  640. } else if (f.rect.UpperLeftCorner.X - f.margin <= left &&
  641. f.rect.LowerRightCorner.X + f.margin >= right) {
  642. // float taking all space
  643. left = right;
  644. }
  645. else
  646. { // float in the middle -- should not occure yet, see that later
  647. }
  648. }
  649. }
  650. } while (nexty && right <= left);
  651. u32 linewidth = right - left;
  652. float x = left;
  653. u32 charsheight = 0;
  654. u32 charswidth = 0;
  655. u32 wordcount = 0;
  656. // Skip beginning of line separators but include them in height
  657. // computation.
  658. while (el != p.elements.end() &&
  659. el->type == ParsedText::ELEMENT_SEPARATOR) {
  660. if (el->floating == ParsedText::FLOAT_NONE) {
  661. el->drawwidth = 0;
  662. if (charsheight < el->dim.Height)
  663. charsheight = el->dim.Height;
  664. }
  665. el++;
  666. }
  667. std::vector<ParsedText::Element>::iterator linestart = el;
  668. std::vector<ParsedText::Element>::iterator lineend = p.elements.end();
  669. // First pass, find elements fitting into line
  670. // (or at least one element)
  671. while (el != p.elements.end() && (charswidth == 0 ||
  672. charswidth + el->dim.Width <= linewidth)) {
  673. if (el->floating == ParsedText::FLOAT_NONE) {
  674. if (el->type != ParsedText::ELEMENT_SEPARATOR) {
  675. lineend = el;
  676. wordcount++;
  677. }
  678. charswidth += el->dim.Width;
  679. if (charsheight < el->dim.Height)
  680. charsheight = el->dim.Height;
  681. }
  682. el++;
  683. }
  684. // Empty line, nothing to place only go down line height
  685. if (lineend == p.elements.end()) {
  686. y += charsheight;
  687. continue;
  688. }
  689. // Point to the first position outside line (may be end())
  690. lineend++;
  691. // Second pass, compute printable line width and adjustments
  692. charswidth = 0;
  693. s32 top = 0;
  694. s32 bottom = 0;
  695. for (auto e = linestart; e != lineend; ++e) {
  696. if (e->floating == ParsedText::FLOAT_NONE) {
  697. charswidth += e->dim.Width;
  698. if (top < (s32)e->dim.Height - e->baseline)
  699. top = e->dim.Height - e->baseline;
  700. if (bottom < e->baseline)
  701. bottom = e->baseline;
  702. }
  703. }
  704. float extraspace = 0.f;
  705. switch (p.halign) {
  706. case ParsedText::HALIGN_CENTER:
  707. x += (linewidth - charswidth) / 2.f;
  708. break;
  709. case ParsedText::HALIGN_JUSTIFY:
  710. if (wordcount > 1 && // Justification only if at least two words
  711. !(lineend == p.elements.end())) // Don't justify last line
  712. extraspace = ((float)(linewidth - charswidth)) / (wordcount - 1);
  713. break;
  714. case ParsedText::HALIGN_RIGHT:
  715. x += linewidth - charswidth;
  716. break;
  717. case ParsedText::HALIGN_LEFT:
  718. break;
  719. }
  720. // Third pass, actually place everything
  721. for (auto e = linestart; e != lineend; ++e) {
  722. if (e->floating != ParsedText::FLOAT_NONE)
  723. continue;
  724. e->pos.X = x;
  725. e->pos.Y = y;
  726. switch (e->type) {
  727. case ParsedText::ELEMENT_TEXT:
  728. case ParsedText::ELEMENT_SEPARATOR:
  729. e->pos.X = x;
  730. // Align char baselines
  731. e->pos.Y = y + top + e->baseline - e->dim.Height;
  732. x += e->dim.Width;
  733. if (e->type == ParsedText::ELEMENT_SEPARATOR)
  734. x += extraspace;
  735. break;
  736. case ParsedText::ELEMENT_IMAGE:
  737. case ParsedText::ELEMENT_ITEM:
  738. x += e->dim.Width;
  739. break;
  740. }
  741. // Draw width for separator can be different than element
  742. // width. This will be important for char effects like
  743. // underline.
  744. e->drawwidth = x - e->pos.X;
  745. }
  746. y += charsheight;
  747. } // Elements (actually lines)
  748. } // Paragraph
  749. // Check if float goes under paragraph
  750. for (const auto &f : m_floating) {
  751. if (f.rect.LowerRightCorner.Y >= y)
  752. y = f.rect.LowerRightCorner.Y;
  753. }
  754. m_height = y + m_text.margin;
  755. // Compute vertical offset according to vertical alignment
  756. if (m_height < dest_rect.getHeight())
  757. switch (m_text.valign) {
  758. case ParsedText::VALIGN_BOTTOM:
  759. m_voffset = dest_rect.getHeight() - m_height;
  760. break;
  761. case ParsedText::VALIGN_MIDDLE:
  762. m_voffset = (dest_rect.getHeight() - m_height) / 2;
  763. break;
  764. case ParsedText::VALIGN_TOP:
  765. default:
  766. m_voffset = 0;
  767. }
  768. else
  769. m_voffset = 0;
  770. }
  771. // Draw text in a rectangle with a given offset. Items are actually placed in
  772. // relative (to upper left corner) coordinates.
  773. void TextDrawer::draw(const core::rect<s32> &clip_rect,
  774. const core::position2d<s32> &dest_offset)
  775. {
  776. irr::video::IVideoDriver *driver = m_guienv->getVideoDriver();
  777. core::position2d<s32> offset = dest_offset;
  778. offset.Y += m_voffset;
  779. if (m_text.background_type == ParsedText::BACKGROUND_COLOR)
  780. driver->draw2DRectangle(m_text.background_color, clip_rect);
  781. for (auto &p : m_text.m_paragraphs) {
  782. for (auto &el : p.elements) {
  783. core::rect<s32> rect(el.pos + offset, el.dim);
  784. if (!rect.isRectCollided(clip_rect))
  785. continue;
  786. switch (el.type) {
  787. case ParsedText::ELEMENT_SEPARATOR:
  788. case ParsedText::ELEMENT_TEXT: {
  789. irr::video::SColor color = el.color;
  790. for (auto tag : el.tags)
  791. if (&(*tag) == m_hovertag)
  792. color = el.hovercolor;
  793. if (!el.font)
  794. break;
  795. if (el.type == ParsedText::ELEMENT_TEXT)
  796. el.font->draw(el.text, rect, color, false, true,
  797. &clip_rect);
  798. if (el.underline && el.drawwidth) {
  799. s32 linepos = el.pos.Y + offset.Y +
  800. el.dim.Height - (el.baseline >> 1);
  801. core::rect<s32> linerect(el.pos.X + offset.X,
  802. linepos - (el.baseline >> 3) - 1,
  803. el.pos.X + offset.X + el.drawwidth,
  804. linepos + (el.baseline >> 3));
  805. driver->draw2DRectangle(color, linerect, &clip_rect);
  806. }
  807. } break;
  808. case ParsedText::ELEMENT_IMAGE: {
  809. video::ITexture *texture =
  810. m_tsrc->getTexture(
  811. stringw_to_utf8(el.text));
  812. if (texture != 0)
  813. m_guienv->getVideoDriver()->draw2DImage(
  814. texture, rect,
  815. irr::core::rect<s32>(
  816. core::position2d<s32>(0, 0),
  817. texture->getOriginalSize()),
  818. &clip_rect, 0, true);
  819. } break;
  820. case ParsedText::ELEMENT_ITEM: {
  821. if (m_client) {
  822. IItemDefManager *idef = m_client->idef();
  823. ItemStack item;
  824. item.deSerialize(stringw_to_utf8(el.text), idef);
  825. drawItemStack(m_guienv->getVideoDriver(),
  826. g_fontengine->getFont(), item, rect, &clip_rect, m_client,
  827. IT_ROT_OTHER, el.angle, el.rotation);
  828. }
  829. } break;
  830. }
  831. }
  832. }
  833. }
  834. // -----------------------------------------------------------------------------
  835. // GUIHyperText - The formated text area formspec item
  836. //! constructor
  837. GUIHyperText::GUIHyperText(const wchar_t *text, IGUIEnvironment *environment,
  838. IGUIElement *parent, s32 id, const core::rect<s32> &rectangle,
  839. Client *client, ISimpleTextureSource *tsrc) :
  840. IGUIElement(EGUIET_ELEMENT, environment, parent, id, rectangle),
  841. m_tsrc(tsrc), m_vscrollbar(nullptr),
  842. m_drawer(text, client, environment, tsrc), m_text_scrollpos(0, 0)
  843. {
  844. #ifdef _DEBUG
  845. setDebugName("GUIHyperText");
  846. #endif
  847. IGUISkin *skin = 0;
  848. if (Environment)
  849. skin = Environment->getSkin();
  850. m_scrollbar_width = skin ? skin->getSize(gui::EGDS_SCROLLBAR_SIZE) : 16;
  851. core::rect<s32> rect = irr::core::rect<s32>(
  852. RelativeRect.getWidth() - m_scrollbar_width, 0,
  853. RelativeRect.getWidth(), RelativeRect.getHeight());
  854. m_vscrollbar = new GUIScrollBar(Environment, this, -1, rect, false, true, tsrc);
  855. m_vscrollbar->setVisible(false);
  856. }
  857. //! destructor
  858. GUIHyperText::~GUIHyperText()
  859. {
  860. m_vscrollbar->remove();
  861. m_vscrollbar->drop();
  862. }
  863. ParsedText::Element *GUIHyperText::getElementAt(s32 X, s32 Y)
  864. {
  865. core::position2d<s32> pos{X, Y};
  866. pos -= m_display_text_rect.UpperLeftCorner;
  867. pos -= m_text_scrollpos;
  868. return m_drawer.getElementAt(pos);
  869. }
  870. void GUIHyperText::checkHover(s32 X, s32 Y)
  871. {
  872. m_drawer.m_hovertag = nullptr;
  873. if (AbsoluteRect.isPointInside(core::position2d<s32>(X, Y))) {
  874. ParsedText::Element *element = getElementAt(X, Y);
  875. if (element) {
  876. for (auto &tag : element->tags) {
  877. if (tag->name == "action") {
  878. m_drawer.m_hovertag = tag;
  879. break;
  880. }
  881. }
  882. }
  883. }
  884. ICursorControl *cursor_control = RenderingEngine::get_raw_device()->getCursorControl();
  885. if (cursor_control)
  886. cursor_control->setActiveIcon(m_drawer.m_hovertag ? gui::ECI_HAND : gui::ECI_NORMAL);
  887. }
  888. bool GUIHyperText::OnEvent(const SEvent &event)
  889. {
  890. // Scroll bar
  891. if (event.EventType == EET_GUI_EVENT &&
  892. event.GUIEvent.EventType == EGET_SCROLL_BAR_CHANGED &&
  893. event.GUIEvent.Caller == m_vscrollbar) {
  894. m_text_scrollpos.Y = -m_vscrollbar->getPos();
  895. }
  896. // Reset hover if element left
  897. if (event.EventType == EET_GUI_EVENT &&
  898. event.GUIEvent.EventType == EGET_ELEMENT_LEFT) {
  899. m_drawer.m_hovertag = nullptr;
  900. ICursorControl *cursor_control = RenderingEngine::get_raw_device()->getCursorControl();
  901. if (cursor_control && cursor_control->isVisible())
  902. cursor_control->setActiveIcon(gui::ECI_NORMAL);
  903. }
  904. if (event.EventType == EET_MOUSE_INPUT_EVENT) {
  905. if (event.MouseInput.Event == EMIE_MOUSE_MOVED)
  906. checkHover(event.MouseInput.X, event.MouseInput.Y);
  907. if (event.MouseInput.Event == EMIE_MOUSE_WHEEL && m_vscrollbar->isVisible()) {
  908. m_vscrollbar->setPos(m_vscrollbar->getPos() -
  909. event.MouseInput.Wheel * m_vscrollbar->getSmallStep());
  910. m_text_scrollpos.Y = -m_vscrollbar->getPos();
  911. m_drawer.draw(m_display_text_rect, m_text_scrollpos);
  912. checkHover(event.MouseInput.X, event.MouseInput.Y);
  913. return true;
  914. } else if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
  915. ParsedText::Element *element = getElementAt(
  916. event.MouseInput.X, event.MouseInput.Y);
  917. if (element) {
  918. for (auto &tag : element->tags) {
  919. if (tag->name == "action") {
  920. Text = core::stringw(L"action:") +
  921. utf8_to_stringw(tag->attrs["name"]);
  922. if (Parent) {
  923. SEvent newEvent;
  924. newEvent.EventType = EET_GUI_EVENT;
  925. newEvent.GUIEvent.Caller = this;
  926. newEvent.GUIEvent.Element = 0;
  927. newEvent.GUIEvent.EventType = EGET_BUTTON_CLICKED;
  928. Parent->OnEvent(newEvent);
  929. }
  930. auto url_it = tag->attrs.find("url");
  931. if (url_it != tag->attrs.end()) {
  932. if (g_gamecallback) {
  933. // in game
  934. g_gamecallback->showOpenURLDialog(url_it->second);
  935. } else {
  936. // main menu
  937. porting::open_url(url_it->second);
  938. }
  939. }
  940. break;
  941. }
  942. }
  943. }
  944. }
  945. }
  946. return IGUIElement::OnEvent(event);
  947. }
  948. //! draws the element and its children
  949. void GUIHyperText::draw()
  950. {
  951. if (!IsVisible)
  952. return;
  953. // Text
  954. m_display_text_rect = AbsoluteRect;
  955. m_drawer.place(m_display_text_rect);
  956. // Show a scrollbar if the text overflows vertically
  957. if (m_drawer.getHeight() > m_display_text_rect.getHeight()) {
  958. // Showing a scrollbar will reduce the width of the viewport, causing
  959. // more text to be wrapped and thus increasing the height of the text.
  960. // Therefore, we have to re-layout the text *before* setting the height
  961. // of the scrollbar.
  962. core::rect<s32> smaller_rect = m_display_text_rect;
  963. smaller_rect.LowerRightCorner.X -= m_scrollbar_width;
  964. m_drawer.place(smaller_rect);
  965. m_vscrollbar->setSmallStep(m_display_text_rect.getHeight() * 0.1f);
  966. m_vscrollbar->setLargeStep(m_display_text_rect.getHeight() * 0.5f);
  967. m_vscrollbar->setMax(m_drawer.getHeight() - m_display_text_rect.getHeight());
  968. m_vscrollbar->setVisible(true);
  969. m_vscrollbar->setPageSize(s32(m_drawer.getHeight()));
  970. } else {
  971. m_vscrollbar->setMax(0);
  972. m_vscrollbar->setPos(0);
  973. m_vscrollbar->setVisible(false);
  974. }
  975. m_drawer.draw(AbsoluteClippingRect,
  976. m_display_text_rect.UpperLeftCorner + m_text_scrollpos);
  977. // draw children
  978. IGUIElement::draw();
  979. }