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