Android buttons: Inset 'rare controls', inset and resize 'gear icon' (#7792)
[oweals/minetest.git] / src / gui / guiTable.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include "guiTable.h"
22 #include <queue>
23 #include <sstream>
24 #include <utility>
25 #include <cstring>
26 #include <IGUISkin.h>
27 #include <IGUIFont.h>
28 #include <IGUIScrollBar.h>
29 #include "client/renderingengine.h"
30 #include "debug.h"
31 #include "log.h"
32 #include "client/tile.h"
33 #include "gettime.h"
34 #include "util/string.h"
35 #include "util/numeric.h"
36 #include "util/string.h" // for parseColorString()
37 #include "settings.h" // for settings
38 #include "porting.h" // for dpi
39 #include "guiscalingfilter.h"
40
41 /*
42         GUITable
43 */
44
45 GUITable::GUITable(gui::IGUIEnvironment *env,
46                 gui::IGUIElement* parent, s32 id,
47                 core::rect<s32> rectangle,
48                 ISimpleTextureSource *tsrc
49 ):
50         gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle),
51         m_tsrc(tsrc)
52 {
53         assert(tsrc != NULL);
54
55         gui::IGUISkin* skin = Environment->getSkin();
56
57         m_font = skin->getFont();
58         if (m_font) {
59                 m_font->grab();
60                 m_rowheight = m_font->getDimension(L"A").Height + 4;
61                 m_rowheight = MYMAX(m_rowheight, 1);
62         }
63
64         const s32 s = skin->getSize(gui::EGDS_SCROLLBAR_SIZE);
65         m_scrollbar = Environment->addScrollBar(false,
66                         core::rect<s32>(RelativeRect.getWidth() - s,
67                                         0,
68                                         RelativeRect.getWidth(),
69                                         RelativeRect.getHeight()),
70                         this, -1);
71         m_scrollbar->setSubElement(true);
72         m_scrollbar->setTabStop(false);
73         m_scrollbar->setAlignment(gui::EGUIA_LOWERRIGHT, gui::EGUIA_LOWERRIGHT,
74                         gui::EGUIA_UPPERLEFT, gui::EGUIA_LOWERRIGHT);
75         m_scrollbar->setVisible(false);
76         m_scrollbar->setPos(0);
77
78         setTabStop(true);
79         setTabOrder(-1);
80         updateAbsolutePosition();
81
82         core::rect<s32> relative_rect = m_scrollbar->getRelativePosition();
83         s32 width = (relative_rect.getWidth()/(2.0/3.0)) *
84                         RenderingEngine::getDisplayDensity() *
85                         g_settings->getFloat("gui_scaling");
86         m_scrollbar->setRelativePosition(core::rect<s32>(
87                         relative_rect.LowerRightCorner.X-width,relative_rect.UpperLeftCorner.Y,
88                         relative_rect.LowerRightCorner.X,relative_rect.LowerRightCorner.Y
89                         ));
90 }
91
92 GUITable::~GUITable()
93 {
94         for (GUITable::Row &row : m_rows)
95                 delete[] row.cells;
96
97         if (m_font)
98                 m_font->drop();
99
100         m_scrollbar->remove();
101 }
102
103 GUITable::Option GUITable::splitOption(const std::string &str)
104 {
105         size_t equal_pos = str.find('=');
106         if (equal_pos == std::string::npos)
107                 return GUITable::Option(str, "");
108
109         return GUITable::Option(str.substr(0, equal_pos),
110                         str.substr(equal_pos + 1));
111 }
112
113 void GUITable::setTextList(const std::vector<std::string> &content,
114                 bool transparent)
115 {
116         clear();
117
118         if (transparent) {
119                 m_background.setAlpha(0);
120                 m_border = false;
121         }
122
123         m_is_textlist = true;
124
125         s32 empty_string_index = allocString("");
126
127         m_rows.resize(content.size());
128         for (s32 i = 0; i < (s32) content.size(); ++i) {
129                 Row *row = &m_rows[i];
130                 row->cells = new Cell[1];
131                 row->cellcount = 1;
132                 row->indent = 0;
133                 row->visible_index = i;
134                 m_visible_rows.push_back(i);
135
136                 Cell *cell = row->cells;
137                 cell->xmin = 0;
138                 cell->xmax = 0x7fff;  // something large enough
139                 cell->xpos = 6;
140                 cell->content_type = COLUMN_TYPE_TEXT;
141                 cell->content_index = empty_string_index;
142                 cell->tooltip_index = empty_string_index;
143                 cell->color.set(255, 255, 255, 255);
144                 cell->color_defined = false;
145                 cell->reported_column = 1;
146
147                 // parse row content (color)
148                 const std::string &s = content[i];
149                 if (s[0] == '#' && s[1] == '#') {
150                         // double # to escape
151                         cell->content_index = allocString(s.substr(2));
152                 }
153                 else if (s[0] == '#' && s.size() >= 7 &&
154                                 parseColorString(
155                                         s.substr(0,7), cell->color, false)) {
156                         // single # for color
157                         cell->color_defined = true;
158                         cell->content_index = allocString(s.substr(7));
159                 }
160                 else {
161                         // no #, just text
162                         cell->content_index = allocString(s);
163                 }
164
165         }
166
167         allocationComplete();
168
169         // Clamp scroll bar position
170         updateScrollBar();
171 }
172
173 void GUITable::setTable(const TableOptions &options,
174                 const TableColumns &columns,
175                 std::vector<std::string> &content)
176 {
177         clear();
178
179         // Naming conventions:
180         // i is always a row index, 0-based
181         // j is always a column index, 0-based
182         // k is another index, for example an option index
183
184         // Handle a stupid error case... (issue #1187)
185         if (columns.empty()) {
186                 TableColumn text_column;
187                 text_column.type = "text";
188                 TableColumns new_columns;
189                 new_columns.push_back(text_column);
190                 setTable(options, new_columns, content);
191                 return;
192         }
193
194         // Handle table options
195         video::SColor default_color(255, 255, 255, 255);
196         s32 opendepth = 0;
197         for (const Option &option : options) {
198                 const std::string &name = option.name;
199                 const std::string &value = option.value;
200                 if (name == "color")
201                         parseColorString(value, m_color, false);
202                 else if (name == "background")
203                         parseColorString(value, m_background, false);
204                 else if (name == "border")
205                         m_border = is_yes(value);
206                 else if (name == "highlight")
207                         parseColorString(value, m_highlight, false);
208                 else if (name == "highlight_text")
209                         parseColorString(value, m_highlight_text, false);
210                 else if (name == "opendepth")
211                         opendepth = stoi(value);
212                 else
213                         errorstream<<"Invalid table option: \""<<name<<"\""
214                                 <<" (value=\""<<value<<"\")"<<std::endl;
215         }
216
217         // Get number of columns and rows
218         // note: error case columns.size() == 0 was handled above
219         s32 colcount = columns.size();
220         assert(colcount >= 1);
221         // rowcount = ceil(cellcount / colcount) but use integer arithmetic
222         s32 rowcount = (content.size() + colcount - 1) / colcount;
223         assert(rowcount >= 0);
224         // Append empty strings to content if there is an incomplete row
225         s32 cellcount = rowcount * colcount;
226         while (content.size() < (u32) cellcount)
227                 content.emplace_back("");
228
229         // Create temporary rows (for processing columns)
230         struct TempRow {
231                 // Current horizontal position (may different between rows due
232                 // to indent/tree columns, or text/image columns with width<0)
233                 s32 x;
234                 // Tree indentation level
235                 s32 indent;
236                 // Next cell: Index into m_strings or m_images
237                 s32 content_index;
238                 // Next cell: Width in pixels
239                 s32 content_width;
240                 // Vector of completed cells in this row
241                 std::vector<Cell> cells;
242                 // Stores colors and how long they last (maximum column index)
243                 std::vector<std::pair<video::SColor, s32> > colors;
244
245                 TempRow(): x(0), indent(0), content_index(0), content_width(0) {}
246         };
247         TempRow *rows = new TempRow[rowcount];
248
249         // Get em width. Pedantically speaking, the width of "M" is not
250         // necessarily the same as the em width, but whatever, close enough.
251         s32 em = 6;
252         if (m_font)
253                 em = m_font->getDimension(L"M").Width;
254
255         s32 default_tooltip_index = allocString("");
256
257         std::map<s32, s32> active_image_indices;
258
259         // Process content in column-major order
260         for (s32 j = 0; j < colcount; ++j) {
261                 // Check column type
262                 ColumnType columntype = COLUMN_TYPE_TEXT;
263                 if (columns[j].type == "text")
264                         columntype = COLUMN_TYPE_TEXT;
265                 else if (columns[j].type == "image")
266                         columntype = COLUMN_TYPE_IMAGE;
267                 else if (columns[j].type == "color")
268                         columntype = COLUMN_TYPE_COLOR;
269                 else if (columns[j].type == "indent")
270                         columntype = COLUMN_TYPE_INDENT;
271                 else if (columns[j].type == "tree")
272                         columntype = COLUMN_TYPE_TREE;
273                 else
274                         errorstream<<"Invalid table column type: \""
275                                 <<columns[j].type<<"\""<<std::endl;
276
277                 // Process column options
278                 s32 padding = myround(0.5 * em);
279                 s32 tooltip_index = default_tooltip_index;
280                 s32 align = 0;
281                 s32 width = 0;
282                 s32 span = colcount;
283
284                 if (columntype == COLUMN_TYPE_INDENT) {
285                         padding = 0; // default indent padding
286                 }
287                 if (columntype == COLUMN_TYPE_INDENT ||
288                                 columntype == COLUMN_TYPE_TREE) {
289                         width = myround(em * 1.5); // default indent width
290                 }
291
292                 for (const Option &option : columns[j].options) {
293                         const std::string &name = option.name;
294                         const std::string &value = option.value;
295                         if (name == "padding")
296                                 padding = myround(stof(value) * em);
297                         else if (name == "tooltip")
298                                 tooltip_index = allocString(value);
299                         else if (name == "align" && value == "left")
300                                 align = 0;
301                         else if (name == "align" && value == "center")
302                                 align = 1;
303                         else if (name == "align" && value == "right")
304                                 align = 2;
305                         else if (name == "align" && value == "inline")
306                                 align = 3;
307                         else if (name == "width")
308                                 width = myround(stof(value) * em);
309                         else if (name == "span" && columntype == COLUMN_TYPE_COLOR)
310                                 span = stoi(value);
311                         else if (columntype == COLUMN_TYPE_IMAGE &&
312                                         !name.empty() &&
313                                         string_allowed(name, "0123456789")) {
314                                 s32 content_index = allocImage(value);
315                                 active_image_indices.insert(std::make_pair(
316                                                         stoi(name),
317                                                         content_index));
318                         }
319                         else {
320                                 errorstream<<"Invalid table column option: \""<<name<<"\""
321                                         <<" (value=\""<<value<<"\")"<<std::endl;
322                         }
323                 }
324
325                 // If current column type can use information from "color" columns,
326                 // find out which of those is currently active
327                 if (columntype == COLUMN_TYPE_TEXT) {
328                         for (s32 i = 0; i < rowcount; ++i) {
329                                 TempRow *row = &rows[i];
330                                 while (!row->colors.empty() && row->colors.back().second < j)
331                                         row->colors.pop_back();
332                         }
333                 }
334
335                 // Make template for new cells
336                 Cell newcell;
337                 newcell.content_type = columntype;
338                 newcell.tooltip_index = tooltip_index;
339                 newcell.reported_column = j+1;
340
341                 if (columntype == COLUMN_TYPE_TEXT) {
342                         // Find right edge of column
343                         s32 xmax = 0;
344                         for (s32 i = 0; i < rowcount; ++i) {
345                                 TempRow *row = &rows[i];
346                                 row->content_index = allocString(content[i * colcount + j]);
347                                 const core::stringw &text = m_strings[row->content_index];
348                                 row->content_width = m_font ?
349                                         m_font->getDimension(text.c_str()).Width : 0;
350                                 row->content_width = MYMAX(row->content_width, width);
351                                 s32 row_xmax = row->x + padding + row->content_width;
352                                 xmax = MYMAX(xmax, row_xmax);
353                         }
354                         // Add a new cell (of text type) to each row
355                         for (s32 i = 0; i < rowcount; ++i) {
356                                 newcell.xmin = rows[i].x + padding;
357                                 alignContent(&newcell, xmax, rows[i].content_width, align);
358                                 newcell.content_index = rows[i].content_index;
359                                 newcell.color_defined = !rows[i].colors.empty();
360                                 if (newcell.color_defined)
361                                         newcell.color = rows[i].colors.back().first;
362                                 rows[i].cells.push_back(newcell);
363                                 rows[i].x = newcell.xmax;
364                         }
365                 }
366                 else if (columntype == COLUMN_TYPE_IMAGE) {
367                         // Find right edge of column
368                         s32 xmax = 0;
369                         for (s32 i = 0; i < rowcount; ++i) {
370                                 TempRow *row = &rows[i];
371                                 row->content_index = -1;
372
373                                 // Find content_index. Image indices are defined in
374                                 // column options so check active_image_indices.
375                                 s32 image_index = stoi(content[i * colcount + j]);
376                                 std::map<s32, s32>::iterator image_iter =
377                                         active_image_indices.find(image_index);
378                                 if (image_iter != active_image_indices.end())
379                                         row->content_index = image_iter->second;
380
381                                 // Get texture object (might be NULL)
382                                 video::ITexture *image = NULL;
383                                 if (row->content_index >= 0)
384                                         image = m_images[row->content_index];
385
386                                 // Get content width and update xmax
387                                 row->content_width = image ? image->getOriginalSize().Width : 0;
388                                 row->content_width = MYMAX(row->content_width, width);
389                                 s32 row_xmax = row->x + padding + row->content_width;
390                                 xmax = MYMAX(xmax, row_xmax);
391                         }
392                         // Add a new cell (of image type) to each row
393                         for (s32 i = 0; i < rowcount; ++i) {
394                                 newcell.xmin = rows[i].x + padding;
395                                 alignContent(&newcell, xmax, rows[i].content_width, align);
396                                 newcell.content_index = rows[i].content_index;
397                                 rows[i].cells.push_back(newcell);
398                                 rows[i].x = newcell.xmax;
399                         }
400                         active_image_indices.clear();
401                 }
402                 else if (columntype == COLUMN_TYPE_COLOR) {
403                         for (s32 i = 0; i < rowcount; ++i) {
404                                 video::SColor cellcolor(255, 255, 255, 255);
405                                 if (parseColorString(content[i * colcount + j], cellcolor, true))
406                                         rows[i].colors.emplace_back(cellcolor, j+span);
407                         }
408                 }
409                 else if (columntype == COLUMN_TYPE_INDENT ||
410                                 columntype == COLUMN_TYPE_TREE) {
411                         // For column type "tree", reserve additional space for +/-
412                         // Also enable special processing for treeview-type tables
413                         s32 content_width = 0;
414                         if (columntype == COLUMN_TYPE_TREE) {
415                                 content_width = m_font ? m_font->getDimension(L"+").Width : 0;
416                                 m_has_tree_column = true;
417                         }
418                         // Add a new cell (of indent or tree type) to each row
419                         for (s32 i = 0; i < rowcount; ++i) {
420                                 TempRow *row = &rows[i];
421
422                                 s32 indentlevel = stoi(content[i * colcount + j]);
423                                 indentlevel = MYMAX(indentlevel, 0);
424                                 if (columntype == COLUMN_TYPE_TREE)
425                                         row->indent = indentlevel;
426
427                                 newcell.xmin = row->x + padding;
428                                 newcell.xpos = newcell.xmin + indentlevel * width;
429                                 newcell.xmax = newcell.xpos + content_width;
430                                 newcell.content_index = 0;
431                                 newcell.color_defined = !rows[i].colors.empty();
432                                 if (newcell.color_defined)
433                                         newcell.color = rows[i].colors.back().first;
434                                 row->cells.push_back(newcell);
435                                 row->x = newcell.xmax;
436                         }
437                 }
438         }
439
440         // Copy temporary rows to not so temporary rows
441         if (rowcount >= 1) {
442                 m_rows.resize(rowcount);
443                 for (s32 i = 0; i < rowcount; ++i) {
444                         Row *row = &m_rows[i];
445                         row->cellcount = rows[i].cells.size();
446                         row->cells = new Cell[row->cellcount];
447                         memcpy((void*) row->cells, (void*) &rows[i].cells[0],
448                                         row->cellcount * sizeof(Cell));
449                         row->indent = rows[i].indent;
450                         row->visible_index = i;
451                         m_visible_rows.push_back(i);
452                 }
453         }
454
455         if (m_has_tree_column) {
456                 // Treeview: convert tree to indent cells on leaf rows
457                 for (s32 i = 0; i < rowcount; ++i) {
458                         if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent)
459                                 for (s32 j = 0; j < m_rows[i].cellcount; ++j)
460                                         if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE)
461                                                 m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT;
462                 }
463
464                 // Treeview: close rows according to opendepth option
465                 std::set<s32> opened_trees;
466                 for (s32 i = 0; i < rowcount; ++i)
467                         if (m_rows[i].indent < opendepth)
468                                 opened_trees.insert(i);
469                 setOpenedTrees(opened_trees);
470         }
471
472         // Delete temporary information used only during setTable()
473         delete[] rows;
474         allocationComplete();
475
476         // Clamp scroll bar position
477         updateScrollBar();
478 }
479
480 void GUITable::clear()
481 {
482         // Clean up cells and rows
483         for (GUITable::Row &row : m_rows)
484                 delete[] row.cells;
485         m_rows.clear();
486         m_visible_rows.clear();
487
488         // Get colors from skin
489         gui::IGUISkin *skin = Environment->getSkin();
490         m_color          = skin->getColor(gui::EGDC_BUTTON_TEXT);
491         m_background     = skin->getColor(gui::EGDC_3D_HIGH_LIGHT);
492         m_highlight      = skin->getColor(gui::EGDC_HIGH_LIGHT);
493         m_highlight_text = skin->getColor(gui::EGDC_HIGH_LIGHT_TEXT);
494
495         // Reset members
496         m_is_textlist = false;
497         m_has_tree_column = false;
498         m_selected = -1;
499         m_sel_column = 0;
500         m_sel_doubleclick = false;
501         m_keynav_time = 0;
502         m_keynav_buffer = L"";
503         m_border = true;
504         m_strings.clear();
505         m_images.clear();
506         m_alloc_strings.clear();
507         m_alloc_images.clear();
508 }
509
510 std::string GUITable::checkEvent()
511 {
512         s32 sel = getSelected();
513         assert(sel >= 0);
514
515         if (sel == 0) {
516                 return "INV";
517         }
518
519         std::ostringstream os(std::ios::binary);
520         if (m_sel_doubleclick) {
521                 os<<"DCL:";
522                 m_sel_doubleclick = false;
523         }
524         else {
525                 os<<"CHG:";
526         }
527         os<<sel;
528         if (!m_is_textlist) {
529                 os<<":"<<m_sel_column;
530         }
531         return os.str();
532 }
533
534 s32 GUITable::getSelected() const
535 {
536         if (m_selected < 0)
537                 return 0;
538
539         assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size());
540         return m_visible_rows[m_selected] + 1;
541 }
542
543 void GUITable::setSelected(s32 index)
544 {
545         s32 old_selected = m_selected;
546
547         m_selected = -1;
548         m_sel_column = 0;
549         m_sel_doubleclick = false;
550
551         --index; // Switch from 1-based indexing to 0-based indexing
552
553         s32 rowcount = m_rows.size();
554         if (rowcount == 0 || index < 0) {
555                 return;
556         }
557
558         if (index >= rowcount) {
559                 index = rowcount - 1;
560         }
561
562         // If the selected row is not visible, open its ancestors to make it visible
563         bool selection_invisible = m_rows[index].visible_index < 0;
564         if (selection_invisible) {
565                 std::set<s32> opened_trees;
566                 getOpenedTrees(opened_trees);
567                 s32 indent = m_rows[index].indent;
568                 for (s32 j = index - 1; j >= 0; --j) {
569                         if (m_rows[j].indent < indent) {
570                                 opened_trees.insert(j);
571                                 indent = m_rows[j].indent;
572                         }
573                 }
574                 setOpenedTrees(opened_trees);
575         }
576
577         if (index >= 0) {
578                 m_selected = m_rows[index].visible_index;
579                 assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size());
580         }
581
582         if (m_selected != old_selected || selection_invisible) {
583                 autoScroll();
584         }
585 }
586
587 GUITable::DynamicData GUITable::getDynamicData() const
588 {
589         DynamicData dyndata;
590         dyndata.selected = getSelected();
591         dyndata.scrollpos = m_scrollbar->getPos();
592         dyndata.keynav_time = m_keynav_time;
593         dyndata.keynav_buffer = m_keynav_buffer;
594         if (m_has_tree_column)
595                 getOpenedTrees(dyndata.opened_trees);
596         return dyndata;
597 }
598
599 void GUITable::setDynamicData(const DynamicData &dyndata)
600 {
601         if (m_has_tree_column)
602                 setOpenedTrees(dyndata.opened_trees);
603
604         m_keynav_time = dyndata.keynav_time;
605         m_keynav_buffer = dyndata.keynav_buffer;
606
607         setSelected(dyndata.selected);
608         m_sel_column = 0;
609         m_sel_doubleclick = false;
610
611         m_scrollbar->setPos(dyndata.scrollpos);
612 }
613
614 const c8* GUITable::getTypeName() const
615 {
616         return "GUITable";
617 }
618
619 void GUITable::updateAbsolutePosition()
620 {
621         IGUIElement::updateAbsolutePosition();
622         updateScrollBar();
623 }
624
625 void GUITable::draw()
626 {
627         if (!IsVisible)
628                 return;
629
630         gui::IGUISkin *skin = Environment->getSkin();
631
632         // draw background
633
634         bool draw_background = m_background.getAlpha() > 0;
635         if (m_border)
636                 skin->draw3DSunkenPane(this, m_background,
637                                 true, draw_background,
638                                 AbsoluteRect, &AbsoluteClippingRect);
639         else if (draw_background)
640                 skin->draw2DRectangle(this, m_background,
641                                 AbsoluteRect, &AbsoluteClippingRect);
642
643         // get clipping rect
644
645         core::rect<s32> client_clip(AbsoluteRect);
646         client_clip.UpperLeftCorner.Y += 1;
647         client_clip.UpperLeftCorner.X += 1;
648         client_clip.LowerRightCorner.Y -= 1;
649         client_clip.LowerRightCorner.X -= 1;
650         if (m_scrollbar->isVisible()) {
651                 client_clip.LowerRightCorner.X =
652                                 m_scrollbar->getAbsolutePosition().UpperLeftCorner.X;
653         }
654         client_clip.clipAgainst(AbsoluteClippingRect);
655
656         // draw visible rows
657
658         s32 scrollpos = m_scrollbar->getPos();
659         s32 row_min = scrollpos / m_rowheight;
660         s32 row_max = (scrollpos + AbsoluteRect.getHeight() - 1)
661                         / m_rowheight + 1;
662         row_max = MYMIN(row_max, (s32) m_visible_rows.size());
663
664         core::rect<s32> row_rect(AbsoluteRect);
665         if (m_scrollbar->isVisible())
666                 row_rect.LowerRightCorner.X -=
667                         skin->getSize(gui::EGDS_SCROLLBAR_SIZE);
668         row_rect.UpperLeftCorner.Y += row_min * m_rowheight - scrollpos;
669         row_rect.LowerRightCorner.Y = row_rect.UpperLeftCorner.Y + m_rowheight;
670
671         for (s32 i = row_min; i < row_max; ++i) {
672                 Row *row = &m_rows[m_visible_rows[i]];
673                 bool is_sel = i == m_selected;
674                 video::SColor color = m_color;
675
676                 if (is_sel) {
677                         skin->draw2DRectangle(this, m_highlight, row_rect, &client_clip);
678                         color = m_highlight_text;
679                 }
680
681                 for (s32 j = 0; j < row->cellcount; ++j)
682                         drawCell(&row->cells[j], color, row_rect, client_clip);
683
684                 row_rect.UpperLeftCorner.Y += m_rowheight;
685                 row_rect.LowerRightCorner.Y += m_rowheight;
686         }
687
688         // Draw children
689         IGUIElement::draw();
690 }
691
692 void GUITable::drawCell(const Cell *cell, video::SColor color,
693                 const core::rect<s32> &row_rect,
694                 const core::rect<s32> &client_clip)
695 {
696         if ((cell->content_type == COLUMN_TYPE_TEXT)
697                         || (cell->content_type == COLUMN_TYPE_TREE)) {
698
699                 core::rect<s32> text_rect = row_rect;
700                 text_rect.UpperLeftCorner.X = row_rect.UpperLeftCorner.X
701                                 + cell->xpos;
702                 text_rect.LowerRightCorner.X = row_rect.UpperLeftCorner.X
703                                 + cell->xmax;
704
705                 if (cell->color_defined)
706                         color = cell->color;
707
708                 if (m_font) {
709                         if (cell->content_type == COLUMN_TYPE_TEXT)
710                                 m_font->draw(m_strings[cell->content_index],
711                                                 text_rect, color,
712                                                 false, true, &client_clip);
713                         else // tree
714                                 m_font->draw(cell->content_index ? L"+" : L"-",
715                                                 text_rect, color,
716                                                 false, true, &client_clip);
717                 }
718         }
719         else if (cell->content_type == COLUMN_TYPE_IMAGE) {
720
721                 if (cell->content_index < 0)
722                         return;
723
724                 video::IVideoDriver *driver = Environment->getVideoDriver();
725                 video::ITexture *image = m_images[cell->content_index];
726
727                 if (image) {
728                         core::position2d<s32> dest_pos =
729                                         row_rect.UpperLeftCorner;
730                         dest_pos.X += cell->xpos;
731                         core::rect<s32> source_rect(
732                                         core::position2d<s32>(0, 0),
733                                         image->getOriginalSize());
734                         s32 imgh = source_rect.LowerRightCorner.Y;
735                         s32 rowh = row_rect.getHeight();
736                         if (imgh < rowh)
737                                 dest_pos.Y += (rowh - imgh) / 2;
738                         else
739                                 source_rect.LowerRightCorner.Y = rowh;
740
741                         video::SColor color(255, 255, 255, 255);
742
743                         driver->draw2DImage(image, dest_pos, source_rect,
744                                         &client_clip, color, true);
745                 }
746         }
747 }
748
749 bool GUITable::OnEvent(const SEvent &event)
750 {
751         if (!isEnabled())
752                 return IGUIElement::OnEvent(event);
753
754         if (event.EventType == EET_KEY_INPUT_EVENT) {
755                 if (event.KeyInput.PressedDown && (
756                                 event.KeyInput.Key == KEY_DOWN ||
757                                 event.KeyInput.Key == KEY_UP   ||
758                                 event.KeyInput.Key == KEY_HOME ||
759                                 event.KeyInput.Key == KEY_END  ||
760                                 event.KeyInput.Key == KEY_NEXT ||
761                                 event.KeyInput.Key == KEY_PRIOR)) {
762                         s32 offset = 0;
763                         switch (event.KeyInput.Key) {
764                                 case KEY_DOWN:
765                                         offset = 1;
766                                         break;
767                                 case KEY_UP:
768                                         offset = -1;
769                                         break;
770                                 case KEY_HOME:
771                                         offset = - (s32) m_visible_rows.size();
772                                         break;
773                                 case KEY_END:
774                                         offset = m_visible_rows.size();
775                                         break;
776                                 case KEY_NEXT:
777                                         offset = AbsoluteRect.getHeight() / m_rowheight;
778                                         break;
779                                 case KEY_PRIOR:
780                                         offset = - (s32) (AbsoluteRect.getHeight() / m_rowheight);
781                                         break;
782                                 default:
783                                         break;
784                         }
785                         s32 old_selected = m_selected;
786                         s32 rowcount = m_visible_rows.size();
787                         if (rowcount != 0) {
788                                 m_selected = rangelim(m_selected + offset, 0, rowcount-1);
789                                 autoScroll();
790                         }
791
792                         if (m_selected != old_selected)
793                                 sendTableEvent(0, false);
794
795                         return true;
796                 }
797
798                 if (event.KeyInput.PressedDown && (
799                                 event.KeyInput.Key == KEY_LEFT ||
800                                 event.KeyInput.Key == KEY_RIGHT)) {
801                         // Open/close subtree via keyboard
802                         if (m_selected >= 0) {
803                                 int dir = event.KeyInput.Key == KEY_LEFT ? -1 : 1;
804                                 toggleVisibleTree(m_selected, dir, true);
805                         }
806                         return true;
807                 }
808                 else if (!event.KeyInput.PressedDown && (
809                                 event.KeyInput.Key == KEY_RETURN ||
810                                 event.KeyInput.Key == KEY_SPACE)) {
811                         sendTableEvent(0, true);
812                         return true;
813                 }
814                 else if (event.KeyInput.Key == KEY_ESCAPE ||
815                                 event.KeyInput.Key == KEY_SPACE) {
816                         // pass to parent
817                 }
818                 else if (event.KeyInput.PressedDown && event.KeyInput.Char) {
819                         // change selection based on text as it is typed
820                         u64 now = porting::getTimeMs();
821                         if (now - m_keynav_time >= 500)
822                                 m_keynav_buffer = L"";
823                         m_keynav_time = now;
824
825                         // add to key buffer if not a key repeat
826                         if (!(m_keynav_buffer.size() == 1 &&
827                                         m_keynav_buffer[0] == event.KeyInput.Char)) {
828                                 m_keynav_buffer.append(event.KeyInput.Char);
829                         }
830
831                         // find the selected item, starting at the current selection
832                         // don't change selection if the key buffer matches the current item
833                         s32 old_selected = m_selected;
834                         s32 start = MYMAX(m_selected, 0);
835                         s32 rowcount = m_visible_rows.size();
836                         for (s32 k = 1; k < rowcount; ++k) {
837                                 s32 current = start + k;
838                                 if (current >= rowcount)
839                                         current -= rowcount;
840                                 if (doesRowStartWith(getRow(current), m_keynav_buffer)) {
841                                         m_selected = current;
842                                         break;
843                                 }
844                         }
845                         autoScroll();
846                         if (m_selected != old_selected)
847                                 sendTableEvent(0, false);
848
849                         return true;
850                 }
851         }
852         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
853                 core::position2d<s32> p(event.MouseInput.X, event.MouseInput.Y);
854
855                 if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
856                         m_scrollbar->setPos(m_scrollbar->getPos() +
857                                         (event.MouseInput.Wheel < 0 ? -3 : 3) *
858                                         - (s32) m_rowheight / 2);
859                         return true;
860                 }
861
862                 // Find hovered row and cell
863                 bool really_hovering = false;
864                 s32 row_i = getRowAt(p.Y, really_hovering);
865                 const Cell *cell = NULL;
866                 if (really_hovering) {
867                         s32 cell_j = getCellAt(p.X, row_i);
868                         if (cell_j >= 0)
869                                 cell = &(getRow(row_i)->cells[cell_j]);
870                 }
871
872                 // Update tooltip
873                 setToolTipText(cell ? m_strings[cell->tooltip_index].c_str() : L"");
874
875                 // Fix for #1567/#1806:
876                 // IGUIScrollBar passes double click events to its parent,
877                 // which we don't want. Detect this case and discard the event
878                 if (event.MouseInput.Event != EMIE_MOUSE_MOVED &&
879                                 m_scrollbar->isVisible() &&
880                                 m_scrollbar->isPointInside(p))
881                         return true;
882
883                 if (event.MouseInput.isLeftPressed() &&
884                                 (isPointInside(p) ||
885                                  event.MouseInput.Event == EMIE_MOUSE_MOVED)) {
886                         s32 sel_column = 0;
887                         bool sel_doubleclick = (event.MouseInput.Event
888                                         == EMIE_LMOUSE_DOUBLE_CLICK);
889                         bool plusminus_clicked = false;
890
891                         // For certain events (left click), report column
892                         // Also open/close subtrees when the +/- is clicked
893                         if (cell && (
894                                         event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN ||
895                                         event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK ||
896                                         event.MouseInput.Event == EMIE_LMOUSE_TRIPLE_CLICK)) {
897                                 sel_column = cell->reported_column;
898                                 if (cell->content_type == COLUMN_TYPE_TREE)
899                                         plusminus_clicked = true;
900                         }
901
902                         if (plusminus_clicked) {
903                                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
904                                         toggleVisibleTree(row_i, 0, false);
905                                 }
906                         }
907                         else {
908                                 // Normal selection
909                                 s32 old_selected = m_selected;
910                                 m_selected = row_i;
911                                 autoScroll();
912
913                                 if (m_selected != old_selected ||
914                                                 sel_column >= 1 ||
915                                                 sel_doubleclick) {
916                                         sendTableEvent(sel_column, sel_doubleclick);
917                                 }
918
919                                 // Treeview: double click opens/closes trees
920                                 if (m_has_tree_column && sel_doubleclick) {
921                                         toggleVisibleTree(m_selected, 0, false);
922                                 }
923                         }
924                 }
925                 return true;
926         }
927         if (event.EventType == EET_GUI_EVENT &&
928                         event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED &&
929                         event.GUIEvent.Caller == m_scrollbar) {
930                 // Don't pass events from our scrollbar to the parent
931                 return true;
932         }
933
934         return IGUIElement::OnEvent(event);
935 }
936
937 /******************************************************************************/
938 /* GUITable helper functions                                                  */
939 /******************************************************************************/
940
941 s32 GUITable::allocString(const std::string &text)
942 {
943         std::map<std::string, s32>::iterator it = m_alloc_strings.find(text);
944         if (it == m_alloc_strings.end()) {
945                 s32 id = m_strings.size();
946                 std::wstring wtext = utf8_to_wide(text);
947                 m_strings.emplace_back(wtext.c_str());
948                 m_alloc_strings.insert(std::make_pair(text, id));
949                 return id;
950         }
951
952         return it->second;
953 }
954
955 s32 GUITable::allocImage(const std::string &imagename)
956 {
957         std::map<std::string, s32>::iterator it = m_alloc_images.find(imagename);
958         if (it == m_alloc_images.end()) {
959                 s32 id = m_images.size();
960                 m_images.push_back(m_tsrc->getTexture(imagename));
961                 m_alloc_images.insert(std::make_pair(imagename, id));
962                 return id;
963         }
964
965         return it->second;
966 }
967
968 void GUITable::allocationComplete()
969 {
970         // Called when done with creating rows and cells from table data,
971         // i.e. when allocString and allocImage won't be called anymore
972         m_alloc_strings.clear();
973         m_alloc_images.clear();
974 }
975
976 const GUITable::Row* GUITable::getRow(s32 i) const
977 {
978         if (i >= 0 && i < (s32) m_visible_rows.size())
979                 return &m_rows[m_visible_rows[i]];
980
981         return NULL;
982 }
983
984 bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const
985 {
986         if (row == NULL)
987                 return false;
988
989         for (s32 j = 0; j < row->cellcount; ++j) {
990                 Cell *cell = &row->cells[j];
991                 if (cell->content_type == COLUMN_TYPE_TEXT) {
992                         const core::stringw &cellstr = m_strings[cell->content_index];
993                         if (cellstr.size() >= str.size() &&
994                                         str.equals_ignore_case(cellstr.subString(0, str.size())))
995                                 return true;
996                 }
997         }
998         return false;
999 }
1000
1001 s32 GUITable::getRowAt(s32 y, bool &really_hovering) const
1002 {
1003         really_hovering = false;
1004
1005         s32 rowcount = m_visible_rows.size();
1006         if (rowcount == 0)
1007                 return -1;
1008
1009         // Use arithmetic to find row
1010         s32 rel_y = y - AbsoluteRect.UpperLeftCorner.Y - 1;
1011         s32 i = (rel_y + m_scrollbar->getPos()) / m_rowheight;
1012
1013         if (i >= 0 && i < rowcount) {
1014                 really_hovering = true;
1015                 return i;
1016         }
1017         if (i < 0)
1018                 return 0;
1019
1020         return rowcount - 1;
1021 }
1022
1023 s32 GUITable::getCellAt(s32 x, s32 row_i) const
1024 {
1025         const Row *row = getRow(row_i);
1026         if (row == NULL)
1027                 return -1;
1028
1029         // Use binary search to find cell in row
1030         s32 rel_x = x - AbsoluteRect.UpperLeftCorner.X - 1;
1031         s32 jmin = 0;
1032         s32 jmax = row->cellcount - 1;
1033         while (jmin < jmax) {
1034                 s32 pivot = jmin + (jmax - jmin) / 2;
1035                 assert(pivot >= 0 && pivot < row->cellcount);
1036                 const Cell *cell = &row->cells[pivot];
1037
1038                 if (rel_x >= cell->xmin && rel_x <= cell->xmax)
1039                         return pivot;
1040
1041                 if (rel_x < cell->xmin)
1042                         jmax = pivot - 1;
1043                 else
1044                         jmin = pivot + 1;
1045         }
1046
1047         if (jmin >= 0 && jmin < row->cellcount &&
1048                         rel_x >= row->cells[jmin].xmin &&
1049                         rel_x <= row->cells[jmin].xmax)
1050                 return jmin;
1051
1052         return -1;
1053 }
1054
1055 void GUITable::autoScroll()
1056 {
1057         if (m_selected >= 0) {
1058                 s32 pos = m_scrollbar->getPos();
1059                 s32 maxpos = m_selected * m_rowheight;
1060                 s32 minpos = maxpos - (AbsoluteRect.getHeight() - m_rowheight);
1061                 if (pos > maxpos)
1062                         m_scrollbar->setPos(maxpos);
1063                 else if (pos < minpos)
1064                         m_scrollbar->setPos(minpos);
1065         }
1066 }
1067
1068 void GUITable::updateScrollBar()
1069 {
1070         s32 totalheight = m_rowheight * m_visible_rows.size();
1071         s32 scrollmax = MYMAX(0, totalheight - AbsoluteRect.getHeight());
1072         m_scrollbar->setVisible(scrollmax > 0);
1073         m_scrollbar->setMax(scrollmax);
1074         m_scrollbar->setSmallStep(m_rowheight);
1075         m_scrollbar->setLargeStep(2 * m_rowheight);
1076 }
1077
1078 void GUITable::sendTableEvent(s32 column, bool doubleclick)
1079 {
1080         m_sel_column = column;
1081         m_sel_doubleclick = doubleclick;
1082         if (Parent) {
1083                 SEvent e;
1084                 memset(&e, 0, sizeof e);
1085                 e.EventType = EET_GUI_EVENT;
1086                 e.GUIEvent.Caller = this;
1087                 e.GUIEvent.Element = 0;
1088                 e.GUIEvent.EventType = gui::EGET_TABLE_CHANGED;
1089                 Parent->OnEvent(e);
1090         }
1091 }
1092
1093 void GUITable::getOpenedTrees(std::set<s32> &opened_trees) const
1094 {
1095         opened_trees.clear();
1096         s32 rowcount = m_rows.size();
1097         for (s32 i = 0; i < rowcount - 1; ++i) {
1098                 if (m_rows[i].indent < m_rows[i+1].indent &&
1099                                 m_rows[i+1].visible_index != -2)
1100                         opened_trees.insert(i);
1101         }
1102 }
1103
1104 void GUITable::setOpenedTrees(const std::set<s32> &opened_trees)
1105 {
1106         s32 old_selected = -1;
1107         if (m_selected >= 0)
1108                 old_selected = m_visible_rows[m_selected];
1109
1110         std::vector<s32> parents;
1111         std::vector<s32> closed_parents;
1112
1113         m_visible_rows.clear();
1114
1115         for (size_t i = 0; i < m_rows.size(); ++i) {
1116                 Row *row = &m_rows[i];
1117
1118                 // Update list of ancestors
1119                 while (!parents.empty() && m_rows[parents.back()].indent >= row->indent)
1120                         parents.pop_back();
1121                 while (!closed_parents.empty() &&
1122                                 m_rows[closed_parents.back()].indent >= row->indent)
1123                         closed_parents.pop_back();
1124
1125                 assert(closed_parents.size() <= parents.size());
1126
1127                 if (closed_parents.empty()) {
1128                         // Visible row
1129                         row->visible_index = m_visible_rows.size();
1130                         m_visible_rows.push_back(i);
1131                 }
1132                 else if (parents.back() == closed_parents.back()) {
1133                         // Invisible row, direct parent is closed
1134                         row->visible_index = -2;
1135                 }
1136                 else {
1137                         // Invisible row, direct parent is open, some ancestor is closed
1138                         row->visible_index = -1;
1139                 }
1140
1141                 // If not a leaf, add to parents list
1142                 if (i < m_rows.size()-1 && row->indent < m_rows[i+1].indent) {
1143                         parents.push_back(i);
1144
1145                         s32 content_index = 0; // "-", open
1146                         if (opened_trees.count(i) == 0) {
1147                                 closed_parents.push_back(i);
1148                                 content_index = 1; // "+", closed
1149                         }
1150
1151                         // Update all cells of type "tree"
1152                         for (s32 j = 0; j < row->cellcount; ++j)
1153                                 if (row->cells[j].content_type == COLUMN_TYPE_TREE)
1154                                         row->cells[j].content_index = content_index;
1155                 }
1156         }
1157
1158         updateScrollBar();
1159
1160         // m_selected must be updated since it is a visible row index
1161         if (old_selected >= 0)
1162                 m_selected = m_rows[old_selected].visible_index;
1163 }
1164
1165 void GUITable::openTree(s32 to_open)
1166 {
1167         std::set<s32> opened_trees;
1168         getOpenedTrees(opened_trees);
1169         opened_trees.insert(to_open);
1170         setOpenedTrees(opened_trees);
1171 }
1172
1173 void GUITable::closeTree(s32 to_close)
1174 {
1175         std::set<s32> opened_trees;
1176         getOpenedTrees(opened_trees);
1177         opened_trees.erase(to_close);
1178         setOpenedTrees(opened_trees);
1179 }
1180
1181 // The following function takes a visible row index (hidden rows skipped)
1182 // dir: -1 = left (close), 0 = auto (toggle), 1 = right (open)
1183 void GUITable::toggleVisibleTree(s32 row_i, int dir, bool move_selection)
1184 {
1185         // Check if the chosen tree is currently open
1186         const Row *row = getRow(row_i);
1187         if (row == NULL)
1188                 return;
1189
1190         bool was_open = false;
1191         for (s32 j = 0; j < row->cellcount; ++j) {
1192                 if (row->cells[j].content_type == COLUMN_TYPE_TREE) {
1193                         was_open = row->cells[j].content_index == 0;
1194                         break;
1195                 }
1196         }
1197
1198         // Check if the chosen tree should be opened
1199         bool do_open = !was_open;
1200         if (dir < 0)
1201                 do_open = false;
1202         else if (dir > 0)
1203                 do_open = true;
1204
1205         // Close or open the tree; the heavy lifting is done by setOpenedTrees
1206         if (was_open && !do_open)
1207                 closeTree(m_visible_rows[row_i]);
1208         else if (!was_open && do_open)
1209                 openTree(m_visible_rows[row_i]);
1210
1211         // Change selected row if requested by caller,
1212         // this is useful for keyboard navigation
1213         if (move_selection) {
1214                 s32 sel = row_i;
1215                 if (was_open && do_open) {
1216                         // Move selection to first child
1217                         const Row *maybe_child = getRow(sel + 1);
1218                         if (maybe_child && maybe_child->indent > row->indent)
1219                                 sel++;
1220                 }
1221                 else if (!was_open && !do_open) {
1222                         // Move selection to parent
1223                         assert(getRow(sel) != NULL);
1224                         while (sel > 0 && getRow(sel - 1)->indent >= row->indent)
1225                                 sel--;
1226                         sel--;
1227                         if (sel < 0)  // was root already selected?
1228                                 sel = row_i;
1229                 }
1230                 if (sel != m_selected) {
1231                         m_selected = sel;
1232                         autoScroll();
1233                         sendTableEvent(0, false);
1234                 }
1235         }
1236 }
1237
1238 void GUITable::alignContent(Cell *cell, s32 xmax, s32 content_width, s32 align)
1239 {
1240         // requires that cell.xmin, cell.xmax are properly set
1241         // align = 0: left aligned, 1: centered, 2: right aligned, 3: inline
1242         if (align == 0) {
1243                 cell->xpos = cell->xmin;
1244                 cell->xmax = xmax;
1245         }
1246         else if (align == 1) {
1247                 cell->xpos = (cell->xmin + xmax - content_width) / 2;
1248                 cell->xmax = xmax;
1249         }
1250         else if (align == 2) {
1251                 cell->xpos = xmax - content_width;
1252                 cell->xmax = xmax;
1253         }
1254         else {
1255                 // inline alignment: the cells of the column don't have an aligned
1256                 // right border, the right border of each cell depends on the content
1257                 cell->xpos = cell->xmin;
1258                 cell->xmax = cell->xmin + content_width;
1259         }
1260 }