aboutsummaryrefslogtreecommitdiff
path: root/src/gui/guiTable.cpp
blob: cab2e19fd9af040c6e5a27c2ae34948a5072dba5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732static void ll_unloadlib (void *lib);
static void *ll_load (lua_State *L, const char *path);
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);



#if defined(LUA_DL_DLOPEN)
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.
** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
** NetBSD, AIX 4.2, HPUX 11, and  probably most other Unix flavors, at least
** as an emulation layer on top of native functions.
** =========================================================================
*/

#include <dlfcn.h>

static void ll_unloadlib (void *lib) {
  dlclose(lib);
}


static void *ll_load (lua_State *L, const char *path) {
  void *lib = dlopen(path, RTLD_NOW);
  if (lib == NULL) lua_pushstring(L, dlerror());
  return lib;
}


static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
  if (f == NULL) lua_pushstring(L, dlerror());
  return f;
}

/* }====================================================== */



#elif defined(LUA_DL_DLL)
/*
** {======================================================================
** This is an implementation of loadlib for Windows using native functions.
** =======================================================================
*/

#include <windows.h>


#undef setprogdir

static void setprogdir (lua_State *L) {
  char buff[MAX_PATH + 1];
  char *lb;
  DWORD nsize = sizeof(buff)/sizeof(char);
  DWORD n = GetModuleFileNameA(NULL, buff, nsize);
  if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
    luaL_error(L, "unable to get ModuleFileName");
  else {
    *lb = '\0';
    luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
    lua_remove(L, -2);  /* remove original string */
  }
}


static void pusherror (lua_State *L) {
  int error = GetLastError();
  char buffer[128];
  if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
      NULL, error, 0, buffer, sizeof(buffer), NULL))
    lua_pushstring(L, buffer);
  else
    lua_pushfstring(L, "system error %d\n", error);
}

static void ll_unloadlib (void *lib) {
  FreeLibrary((HINSTANCE)lib);
}


static void *ll_load (lua_State *L, const char *path) {
  HINSTANCE lib = LoadLibraryA(path);
  if (lib == NULL) pusherror(L);
  return lib;
}


static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
  if (f == NULL) pusherror(L);
  return f;
}

/* }====================================================== */



#elif defined(LUA_DL_DYLD)
/*
** {======================================================================
** Native Mac OS X / Darwin Implementation
** =======================================================================
*/

#include <mach-o/dyld.h>


/* Mac appends a `_' before C function names */
#undef POF
#define POF	"_" LUA_POF


static void pusherror (lua_State *L) {
  const char *err_str;
  const char *err_file;
  NSLinkEditErrors err;
  int err_num;
  NSLinkEditError(&err, &err_num, &err_file, &err_str);
  lua_pushstring(L, err_str);
}


static const char *errorfromcode (NSObjectFileImageReturnCode ret) {
  switch (ret) {
    case NSObjectFileImageInappropriateFile:
      return "file is not a bundle";
    case NSObjectFileImageArch:
      return "library is for wrong CPU type";
    case NSObjectFileImageFormat:
      return "bad format";
    case NSObjectFileImageAccess:
      return "cannot access file";
    case NSObjectFileImageFailure:
    default:
      return "unable to load library";
  }
}


static void ll_unloadlib (void *lib) {
  NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
}


static void *ll_load (lua_State *L, const char *path) {
  NSObjectFileImage img;
  NSObjectFileImageReturnCode ret;
  /* this would be a rare case, but prevents crashing if it happens */
  if(!_dyld_present()) {
    lua_pushliteral(L, "dyld not present");
    return NULL;
  }
  ret = NSCreateObjectFileImageFromFile(path, &img);
  if (ret == NSObjectFileImageSuccess) {
    NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE |
                       NSLINKMODULE_OPTION_RETURN_ON_ERROR);
    NSDestroyObjectFileImage(img);
    if (mod == NULL) pusherror(L);
    return mod;
  }
  lua_pushstring(L, errorfromcode(ret));
  return NULL;
}


static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
  if (nss == NULL) {
    lua_pushfstring(L, "symbol " LUA_QS " not found", sym);
    return NULL;
  }
  return (lua_CFunction)NSAddressOfSymbol(nss);
}

/* }====================================================== */



#else
/*
** {======================================================
** Fallback for other systems
** =======================================================
*/

#undef LIB_FAIL
#define LIB_FAIL	"absent"


#define DLMSG	"dynamic libraries not enabled; check your Lua installation"


static void ll_unloadlib (void *lib) {
  (void)lib;  /* to avoid warnings */
}


static void *ll_load (lua_State *L, const char *path) {
  (void)path;  /* to avoid warnings */
  lua_pushliteral(L, DLMSG);
  return NULL;
}


static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  (void)lib; (void)sym;  /* to avoid warnings */
  lua_pushliteral(L, DLMSG);
  return NULL;
}

/* }====================================================== */
#endif



static void **ll_register (lua_State *L, const char *path) {
  void **plib;
  lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  lua_gettable(L#include "client/tile.h"
#include "gettime.h"
#include "util/string.h"
#include "util/numeric.h"
#include "util/string.h" // for parseColorString()
#include "settings.h" // for settings
#include "porting.h" // for dpi
#include "client/guiscalingfilter.h"

/*
	GUITable
*/

GUITable::GUITable(gui::IGUIEnvironment *env,
		gui::IGUIElement* parent, s32 id,
		core::rect<s32> rectangle,
		ISimpleTextureSource *tsrc
):
	gui::IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, rectangle),
	m_tsrc(tsrc)
{
	assert(tsrc != NULL);

	gui::IGUISkin* skin = Environment->getSkin();

	m_font = skin->getFont();
	if (m_font) {
		m_font->grab();
		m_rowheight = m_font->getDimension(L"Ay").Height + 4;
		m_rowheight = MYMAX(m_rowheight, 1);
	}

	const s32 s = skin->getSize(gui::EGDS_SCROLLBAR_SIZE);
	m_scrollbar = new GUIScrollBar(Environment, this, -1,
			core::rect<s32>(RelativeRect.getWidth() - s
  if (*reg == NULL)
    return ERRLIB;  /* unable to load library */
  else {
    lua_CFunction f = ll_sym(L, *reg, sym);
    if (f == NULL)
      return ERRFUNC;  /* unable to find function */
    lua_pushcfunction(L, f);
    return 0;  /* return function */
  }
}


static int ll_loadlib (lua_State *L) {
  const char *path = luaL_checkstring(L, 1);
  const char *init = luaL_checkstring(L, 2);
  int stat = ll_loadfunc(L, path, init);
  if (stat == 0)  /* no errors? */
    return 1;  /* return the loaded function */
  else {  /* error; error message is on stack top */
    lua_pushnil(L);
    lua_insert(L, -2);
    lua_pushstring(L, (stat == ERRLIB) ?  LIB_FAIL : "init");
    return 3;  /* return nil, error message, and where */
  }
}



/*
** {======================================================
** 'require' function
** =======================================================
*/


static int readable (const char *filename) {
  FILE *f = fopen(filename, "r");  /* try to open file */
  if (f == NULL) return 0;  /* open failed */
  fclose(f);
  return 1;
}


static const char *pushnexttemplate (lua_State *L, const char *path) {
  const char *l;
  while (*path == *LUA_PATHSEP) path++;  /* skip separators */
  if (*path == '\0') return NULL;  /* no more templates */
  l = strchr(path, *LUA_PATHSEP);  /* find next separator */
  if (l == NULL) l = path + strlen(path);
  lua_pushlstring(L, path, l - path);  /* template */
  return l;
}


static const char *findfile (lua_State *L, const char *name,
                                           const char *pname) {
  const char *path;
  name = luaL_gsub(L, name, ".", LUA_DIRSEP);
  lua_getfield(L, LUA_ENVIRONINDEX, pname);
  path = lua_tostring(L, -1);
  if (path == NULL)
    luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
  lua_pushliteral(L, "");  /* error accumulator */
  while ((path = pushnexttemplate(L, path)) != NULL) {
    const char *filename;
    filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name);
    lua_remove(L, -2);  /* remove path template */
    if (readable(filename))  /* does file exist and is readable? */
      return filename;  /* return that file name */
    lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
    lua_remove(L, -2);  /* remove file name */
    lua_concat(L, 2);  /* add entry to possible error message */
  }
  return NULL;  /* not found */
}


static void loaderror (lua_State *L, const char *filename) {
  luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
                lua_tostring(L, 1), filename, lua_tostring(L, -1));
}


static int loader_Lua (lua_State *L
			cell->content_index = allocString(s.substr(2));
		}
		else if (s[0] == '#' && s.size() >= 7 &&
				parseColorString(
					s.substr(0,7), cell->color, false)) {
			// single # for color
			cell->color_defined = true;
			cell->content_index = allocString(s.substr(7));
		}
		else {
			// no #, just text
			cell->content_index = allocString(s);
		}

	}

	allocationComplete();

	// Clamp scroll bar position
	updateScrollBar();
}

void GUITable::setTable(const TableOptions &options,
		const TableColumns &columns,
		std::vector<std::string> &content)
{
	clear();

	// Naming conventions:
	// i is always a row index, 0-based
	// j is always a column index, 0-based
	// k is another index, for example an option index

	// Handle a stupid error case... (issue #1187)
	if (columns.empty()) {
		TableColumn text_column;
		text_column.type = "text";
		TableColumns new_columns;
		new_columns
  const char *filename = findfile(L, name, "cpath");
  if (filename == NULL) return 1;  /* library not found in this path */
  funcname = mkfuncname(L, name);
  if (ll_loadfunc(L, filename, funcname) != 0)
    loaderror(L, filename);
  return 1;  /* library loaded successfully */
}


static int loader_Croot (lua_State *L) {
  const char *funcname;
  const char *filename;
  const char *name = luaL_checkstring(L, 1);
  const char *p = strchr(name, '.');
  int stat;
  if (p == NULL) return 0;  /* is root */
  lua_pushlstring(L, name, p - name);
  filename = findfile(L, lua_tostring(L, -1), "cpath");
  if (filename == NULL) return 1;  /* root not found */
  funcname = mkfuncname(L, name);
  if ((stat = ll_loadfunc(L, filename, funcname)) != 0) {
    if (stat != ERRFUNC) loaderror(<<" (value=\""<<value<<"\")"<<std::endl;
	}

	// Get number of columns and rows
	// note: error case columns.size() == 0 was handled above
	s32 colcount = columns.size();
	assert(colcount >= 1);
	// rowcount = ceil(cellcount / colcount) but use integer arithmetic
	s32 rowcount = (content.size() + colcount - 1) / colcount;
	assert(rowcount >= 0);
	// Append empty strings to content if there is an incomplete row
	s32 cellcount = rowcount * colcount;
	while (content.size() < (u32) cellcount)
		content.emplace_back("");

	// Create temporary rows (for processing columns)
	struct TempRow {
		// Current horizontal position (may different between rows due
		// to indent/tree columns, or text/image columns with width<0)
		s32 x;
		lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
  return 1;
}


static const int sentinel_ = 0;
#define sentinel	((void *)&sentinel_)


static int ll_require (lua_State *L) {
  const char *name = luaL_checkstring(L, 1);
  int i;
  lua_settop(L, 1);  /* _LOADED table will be at index 2 */
  lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  lua_getfield(L, 2, name);
  if (lua_toboolean(L, -1)) {  /* is it there? */
    if (lua_touserdata(L, -1) == sentinel)  /* check loops */
      luaL_error(L, "loop or previous error loading module " LUA_QS, name);
    return 1;  /* package is already loaded */
  }
  /* else must load it; iterate over available loaders */
  lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  if (!lua_istable(L, -1))
    luaL_error(L, LUA_QL("package.loaders") " must be a table");
  lua_pushliteral(L, "");  /* error message accumulator */
  for (i=1; ; i++) {
    lua_rawgeti(L, -2, i);  /* get a loader */
    if (lua_isnil(L, -1))
      luaL_error(L, "module " LUA_QS " not found:%s",
                    name, lua_tostring(L, -2));
    lua_pushstring(L, name);
    lua_call(L, 1, 1);  /* call it */
    if (lua_isfunction(L, -1))  /* did it find module? */
      break;  /* module loaded successfully */
    else if (lua_isstring(L, -1))  /* loader returned error message? */
      lua_concat(L, 2);  /* accumulate it */
    else
      lua_pop(L, 1);
  }
  lua_pushlightuserdata(L, sentinel);
  lua_setfield(L, 2, name);  /* _LOADED[name] = sentinel */
  lua_pushstring(L, name);  /* pass name as argument to module */
  lua_call(L, 1, 1);  /* run loaded module */
  if (!lua_isnil(L, -1))  /* non-nil return? */
    lua_setfield(L, 2, name);  /* _LOADED[name] = returned value */
  lua_getfield(L, 2, name);
  if (lua_touserdata(L, -1) == sentinel) {   /* module did not set a value? */
    lua_pushboolean(L, 1);  /* use true as result */
    lua_pushvalue(L, -1);  /* extra copy to be returned */
    lua_setfield(L, 2, name);  /* _LOADED[name] = true */
  }
  return 1;
}

/* }====================================================== */



/*
** {======================================================
** 'module' function
** =======================================================
*/
  

static void setfenv (lua_State *L) {
  lua_Debug ar;
  if (lua_getstack(L, 1, &ar) == 0 ||
      lua_getinfo(L, "f", &ar) == 0 ||  /* get calling function */
      lua_iscfunction(L, -1))
    luaL_error(L, LUA_QL("module") " not called from a Lua function");
  lua_pushvalue(L, -2);
  lua_setfenv(L, -2);
  lua_pop(L, 1);
}


static void dooptions (lua_State *L, int n) {
  int i;
  for (i = 2; i <= n; i++) {
    lua_pushvalue(L, i);  /* get option (a function) */
    lua_pushvalue(L, -2);  /* module */
    lua_call(L, 1, 0);
  }
}


static void modinit (lua_State *L, const char *modname) {
  const char *dot;
  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "_M");  /* module._M = module */
  lua_pushstring(L, modname);
  lua_setfield(L, -2, "_NAME");
  dot = strrchr(modname, '.');  /* look for last dot in module name */
  if (dot == NULL) dot = modname;
  else dot++;
  /* set _PACKAGE as package name (full module name minus last part) */
  lua_pushlstring(L, modname, dot - modname);
  lua_setfield(L, -2, "_PACKAGE");
}


static int ll_module (lua_State *L) {
  const char *modname = luaL_checkstring(L, 1);
  int loaded = lua_gettop(L) + 1;  /* index of _LOADED table */
  lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  lua_getfield(L, loaded, modname);  /* get _LOADED[modname] */
  if (!lua_istable(L, -1)) {  /* not found? */
    lua_pop(L, 1);  /* remove previous result */
    /* try global variable (and create one if it does not exist) */
    if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL)
      return luaL_error(L, "name conflict for module " LUA_QS, modname);
    lua_pushvalue(L, -1);
    lua_setfield(L, loaded, modname);  /* _LOADED[modname] = new table */
  }
  /* check whether table already has a _NAME field */
  lua_getfield(L, -1, "_NAME");
  if (!lua_isnil(L, -1))  /* is table an initialized module? */
    lua_pop(L, 1);
  else {  /* no; initialize it */
    lua_pop(L, 1);
    modinit(L, modname);
  }
  lua_pushvalue(L, -1);
  setfenv(L);
  dooptions(L, loaded - 1);
  return 0;
}


static int ll_seeall (lua_State *L) {
  luaL_checktype(L, 1, LUA_TTABLE);
  if (!lua_getmetatable(L, 1)) {
    lua_createtable(L, 0, 1); /* create new metatable */
    lua_pushvalue(L, -1);
    lua_setmetatable(L, 1);
  }
  lua_pushvalue(L, LUA_GLOBALSINDEX);
  lua_setfield(L, -2, "__index");  /* mt.__index = _G */
  return 0;
}


/* }====================================================== */



/* auxiliary mark (for internal use) */
#define AUXMARK		"\1"

static void setpath (lua_State *L, const char *fieldname, const char *envname,
                                   const char *def) {
  const char *path = getenv(envname);
  if (path == NULL)  /* no environment variable? */
    lua_pushstring(L, def);  /* use default */
  else {
    /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
    path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
                              LUA_PATHSEP AUXMARK LUA_PATHSEP);
    luaL_gsub(L, path, AUXMARK, def);
    lua_remove(L, -2);
  }
  setprogdir(L);
  lua_setfield(L, -2, fieldname);
}


static const luaL_Reg pk_funcs[] = {
  {"loadlib", ll_loadlib},
  {"seeall", ll_seeall},
  {NULL, NULL}
};


static const luaL_Reg ll_funcs[] = {
  {"module", ll_module},
  {"require", ll_require},
  {NULL, NULL}
};


static const lua_CFunction loaders[] =
  {loader_preload, loader_Lua, loader_C, loader_Croot, NULL};


LUALIB_API int luaopen_package (lua_State *L) {
  int i;
  /* create new type _LOADLIB */
  luaL_newmetatable(L, "_LOADLIB");
  lua_pushcfunction(L, gctm);
  lua_setfield(L, -2, "__gc");
  /* create `package' table */
  luaL_register(L, LUA_LOADLIBNAME, pk_funcs);
#if defined(LUA_COMPAT_LOADLIB) 
  lua_getfield(L, -1, "loadlib");
  lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
#endif
  lua_pushvalue(L, -1);
  lua_replace(L, LUA_ENVIRONINDEX);
  /* create `loaders' table */
  lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0);
  /* fill it with pre-defined loaders */
  for (i=0; loaders[i] != NULL; i++) {
    lua_pushcfunction(L, loaders[i]);
    lua_rawseti(L, -2, i+1);
  }
  lua_setfield(L, -2, "loaders");  /* put it in field `loaders' */
  setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT);  /* set field `path' */
  setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */
  /* store config information */
  lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n"
                     LUA_EXECDIR "\n" LUA_IGMARK);
  lua_setfield(L, -2, "config");
  /* set field `loaded' */
  luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2);
  lua_setfield(L, -2, "loaded");
  /* set field `preload' */
  lua_newtable(L);
  lua_setfield(L, -2, "preload");
  lua_pushvalue(L, LUA_GLOBALSINDEX);
  luaL_register(L, NULL, ll_funcs);  /* open lib into global table */
  lua_pop(L, 1);
  return 1;  /* return 'package' table */
}

opt">); } } if (m_has_tree_column) { // Treeview: convert tree to indent cells on leaf rows for (s32 i = 0; i < rowcount; ++i) { if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent) for (s32 j = 0; j < m_rows[i].cellcount; ++j) if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE) m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT; } // Treeview: close rows according to opendepth option std::set<s32> opened_trees; for (s32 i = 0; i < rowcount; ++i) if (m_rows[i].indent < opendepth) opened_trees.insert(i); setOpenedTrees(opened_trees); } // Delete temporary information used only during setTable() delete[] rows; allocationComplete(); // Clamp scroll bar position updateScrollBar(); } void GUITable::clear() { // Clean up cells and rows for (GUITable::Row &row : m_rows) delete[] row.cells; m_rows.clear(); m_visible_rows.clear(); // Get colors from skin gui::IGUISkin *skin = Environment->getSkin(); m_color = skin->getColor(gui::EGDC_BUTTON_TEXT); m_background = skin->getColor(gui::EGDC_3D_HIGH_LIGHT); m_highlight = skin->getColor(gui::EGDC_HIGH_LIGHT); m_highlight_text = skin->getColor(gui::EGDC_HIGH_LIGHT_TEXT); // Reset members m_is_textlist = false; m_has_tree_column = false; m_selected = -1; m_sel_column = 0; m_sel_doubleclick = false; m_keynav_time = 0; m_keynav_buffer = L""; m_border = true; m_strings.clear(); m_images.clear(); m_alloc_strings.clear(); m_alloc_images.clear(); } std::string GUITable::checkEvent() { s32 sel = getSelected(); assert(sel >= 0); if (sel == 0) { return "INV"; } std::ostringstream os(std::ios::binary); if (m_sel_doubleclick) { os<<"DCL:"; m_sel_doubleclick = false; } else { os<<"CHG:"; } os<<sel; if (!m_is_textlist) { os<<":"<<m_sel_column; } return os.str(); } s32 GUITable::getSelected() const { if (m_selected < 0) return 0; assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); return m_visible_rows[m_selected] + 1; } void GUITable::setSelected(s32 index) { s32 old_selected = m_selected; m_selected = -1; m_sel_column = 0; m_sel_doubleclick = false; --index; // Switch from 1-based indexing to 0-based indexing s32 rowcount = m_rows.size(); if (rowcount == 0 || index < 0) { return; } if (index >= rowcount) { index = rowcount - 1; } // If the selected row is not visible, open its ancestors to make it visible bool selection_invisible = m_rows[index].visible_index < 0; if (selection_invisible) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); s32 indent = m_rows[index].indent; for (s32 j = index - 1; j >= 0; --j) { if (m_rows[j].indent < indent) { opened_trees.insert(j); indent = m_rows[j].indent; } } setOpenedTrees(opened_trees); } if (index >= 0) { m_selected = m_rows[index].visible_index; assert(m_selected >= 0 && m_selected < (s32) m_visible_rows.size()); } if (m_selected != old_selected || selection_invisible) { autoScroll(); } } void GUITable::setOverrideFont(IGUIFont *font) { if (m_font == font) return; if (font == nullptr) font = Environment->getSkin()->getFont(); if (m_font) m_font->drop(); m_font = font; m_font->grab(); m_rowheight = m_font->getDimension(L"Ay").Height + 4; m_rowheight = MYMAX(m_rowheight, 1); updateScrollBar(); } IGUIFont *GUITable::getOverrideFont() const { return m_font; } GUITable::DynamicData GUITable::getDynamicData() const { DynamicData dyndata; dyndata.selected = getSelected(); dyndata.scrollpos = m_scrollbar->getPos(); dyndata.keynav_time = m_keynav_time; dyndata.keynav_buffer = m_keynav_buffer; if (m_has_tree_column) getOpenedTrees(dyndata.opened_trees); return dyndata; } void GUITable::setDynamicData(const DynamicData &dyndata) { if (m_has_tree_column) setOpenedTrees(dyndata.opened_trees); m_keynav_time = dyndata.keynav_time; m_keynav_buffer = dyndata.keynav_buffer; setSelected(dyndata.selected); m_sel_column = 0; m_sel_doubleclick = false; m_scrollbar->setPos(dyndata.scrollpos); } const c8* GUITable::getTypeName() const { return "GUITable"; } void GUITable::updateAbsolutePosition() { IGUIElement::updateAbsolutePosition(); updateScrollBar(); } void GUITable::draw() { if (!IsVisible) return; gui::IGUISkin *skin = Environment->getSkin(); // draw background bool draw_background = m_background.getAlpha() > 0; if (m_border) skin->draw3DSunkenPane(this, m_background, true, draw_background, AbsoluteRect, &AbsoluteClippingRect); else if (draw_background) skin->draw2DRectangle(this, m_background, AbsoluteRect, &AbsoluteClippingRect); // get clipping rect core::rect<s32> client_clip(AbsoluteRect); client_clip.UpperLeftCorner.Y += 1; client_clip.UpperLeftCorner.X += 1; client_clip.LowerRightCorner.Y -= 1; client_clip.LowerRightCorner.X -= 1; if (m_scrollbar->isVisible()) { client_clip.LowerRightCorner.X = m_scrollbar->getAbsolutePosition().UpperLeftCorner.X; } client_clip.clipAgainst(AbsoluteClippingRect); // draw visible rows s32 scrollpos = m_scrollbar->getPos(); s32 row_min = scrollpos / m_rowheight; s32 row_max = (scrollpos + AbsoluteRect.getHeight() - 1) / m_rowheight + 1; row_max = MYMIN(row_max, (s32) m_visible_rows.size()); core::rect<s32> row_rect(AbsoluteRect); if (m_scrollbar->isVisible()) row_rect.LowerRightCorner.X -= skin->getSize(gui::EGDS_SCROLLBAR_SIZE); row_rect.UpperLeftCorner.Y += row_min * m_rowheight - scrollpos; row_rect.LowerRightCorner.Y = row_rect.UpperLeftCorner.Y + m_rowheight; for (s32 i = row_min; i < row_max; ++i) { Row *row = &m_rows[m_visible_rows[i]]; bool is_sel = i == m_selected; video::SColor color = m_color; if (is_sel) { skin->draw2DRectangle(this, m_highlight, row_rect, &client_clip); color = m_highlight_text; } for (s32 j = 0; j < row->cellcount; ++j) drawCell(&row->cells[j], color, row_rect, client_clip); row_rect.UpperLeftCorner.Y += m_rowheight; row_rect.LowerRightCorner.Y += m_rowheight; } // Draw children IGUIElement::draw(); } void GUITable::drawCell(const Cell *cell, video::SColor color, const core::rect<s32> &row_rect, const core::rect<s32> &client_clip) { if ((cell->content_type == COLUMN_TYPE_TEXT) || (cell->content_type == COLUMN_TYPE_TREE)) { core::rect<s32> text_rect = row_rect; text_rect.UpperLeftCorner.X = row_rect.UpperLeftCorner.X + cell->xpos; text_rect.LowerRightCorner.X = row_rect.UpperLeftCorner.X + cell->xmax; if (cell->color_defined) color = cell->color; if (m_font) { if (cell->content_type == COLUMN_TYPE_TEXT) m_font->draw(m_strings[cell->content_index], text_rect, color, false, true, &client_clip); else // tree m_font->draw(cell->content_index ? L"+" : L"-", text_rect, color, false, true, &client_clip); } } else if (cell->content_type == COLUMN_TYPE_IMAGE) { if (cell->content_index < 0) return; video::IVideoDriver *driver = Environment->getVideoDriver(); video::ITexture *image = m_images[cell->content_index]; if (image) { core::position2d<s32> dest_pos = row_rect.UpperLeftCorner; dest_pos.X += cell->xpos; core::rect<s32> source_rect( core::position2d<s32>(0, 0), image->getOriginalSize()); s32 imgh = source_rect.LowerRightCorner.Y; s32 rowh = row_rect.getHeight(); if (imgh < rowh) dest_pos.Y += (rowh - imgh) / 2; else source_rect.LowerRightCorner.Y = rowh; video::SColor color(255, 255, 255, 255); driver->draw2DImage(image, dest_pos, source_rect, &client_clip, color, true); } } } bool GUITable::OnEvent(const SEvent &event) { if (!isEnabled()) return IGUIElement::OnEvent(event); if (event.EventType == EET_KEY_INPUT_EVENT) { if (event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_DOWN || event.KeyInput.Key == KEY_UP || event.KeyInput.Key == KEY_HOME || event.KeyInput.Key == KEY_END || event.KeyInput.Key == KEY_NEXT || event.KeyInput.Key == KEY_PRIOR)) { s32 offset = 0; switch (event.KeyInput.Key) { case KEY_DOWN: offset = 1; break; case KEY_UP: offset = -1; break; case KEY_HOME: offset = - (s32) m_visible_rows.size(); break; case KEY_END: offset = m_visible_rows.size(); break; case KEY_NEXT: offset = AbsoluteRect.getHeight() / m_rowheight; break; case KEY_PRIOR: offset = - (s32) (AbsoluteRect.getHeight() / m_rowheight); break; default: break; } s32 old_selected = m_selected; s32 rowcount = m_visible_rows.size(); if (rowcount != 0) { m_selected = rangelim(m_selected + offset, 0, rowcount-1); autoScroll(); } if (m_selected != old_selected) sendTableEvent(0, false); return true; } if (event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT)) { // Open/close subtree via keyboard if (m_selected >= 0) { int dir = event.KeyInput.Key == KEY_LEFT ? -1 : 1; toggleVisibleTree(m_selected, dir, true); } return true; } else if (!event.KeyInput.PressedDown && ( event.KeyInput.Key == KEY_RETURN || event.KeyInput.Key == KEY_SPACE)) { sendTableEvent(0, true); return true; } else if (event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_SPACE) { // pass to parent } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed u64 now = porting::getTimeMs(); if (now - m_keynav_time >= 500) m_keynav_buffer = L""; m_keynav_time = now; // add to key buffer if not a key repeat if (!(m_keynav_buffer.size() == 1 && m_keynav_buffer[0] == event.KeyInput.Char)) { m_keynav_buffer.append(event.KeyInput.Char); } // find the selected item, starting at the current selection // don't change selection if the key buffer matches the current item s32 old_selected = m_selected; s32 start = MYMAX(m_selected, 0); s32 rowcount = m_visible_rows.size(); for (s32 k = 1; k < rowcount; ++k) { s32 current = start + k; if (current >= rowcount) current -= rowcount; if (doesRowStartWith(getRow(current), m_keynav_buffer)) { m_selected = current; break; } } autoScroll(); if (m_selected != old_selected) sendTableEvent(0, false); return true; } } if (event.EventType == EET_MOUSE_INPUT_EVENT) { core::position2d<s32> p(event.MouseInput.X, event.MouseInput.Y); if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { m_scrollbar->setPos(m_scrollbar->getPos() + (event.MouseInput.Wheel < 0 ? -3 : 3) * - (s32) m_rowheight / 2); return true; } // Find hovered row and cell bool really_hovering = false; s32 row_i = getRowAt(p.Y, really_hovering); const Cell *cell = NULL; if (really_hovering) { s32 cell_j = getCellAt(p.X, row_i); if (cell_j >= 0) cell = &(getRow(row_i)->cells[cell_j]); } // Update tooltip setToolTipText(cell ? m_strings[cell->tooltip_index].c_str() : L""); // Fix for #1567/#1806: // IGUIScrollBar passes double click events to its parent, // which we don't want. Detect this case and discard the event if (event.MouseInput.Event != EMIE_MOUSE_MOVED && m_scrollbar->isVisible() && m_scrollbar->isPointInside(p)) return true; if (event.MouseInput.isLeftPressed() && (isPointInside(p) || event.MouseInput.Event == EMIE_MOUSE_MOVED)) { s32 sel_column = 0; bool sel_doubleclick = (event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK); bool plusminus_clicked = false; // For certain events (left click), report column // Also open/close subtrees when the +/- is clicked if (cell && ( event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN || event.MouseInput.Event == EMIE_LMOUSE_DOUBLE_CLICK || event.MouseInput.Event == EMIE_LMOUSE_TRIPLE_CLICK)) { sel_column = cell->reported_column; if (cell->content_type == COLUMN_TYPE_TREE) plusminus_clicked = true; } if (plusminus_clicked) { if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) { toggleVisibleTree(row_i, 0, false); } } else { // Normal selection s32 old_selected = m_selected; m_selected = row_i; autoScroll(); if (m_selected != old_selected || sel_column >= 1 || sel_doubleclick) { sendTableEvent(sel_column, sel_doubleclick); } // Treeview: double click opens/closes trees if (m_has_tree_column && sel_doubleclick) { toggleVisibleTree(m_selected, 0, false); } } } return true; } if (event.EventType == EET_GUI_EVENT && event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED && event.GUIEvent.Caller == m_scrollbar) { // Don't pass events from our scrollbar to the parent return true; } return IGUIElement::OnEvent(event); } /******************************************************************************/ /* GUITable helper functions */ /******************************************************************************/ s32 GUITable::allocString(const std::string &text) { std::map<std::string, s32>::iterator it = m_alloc_strings.find(text); if (it == m_alloc_strings.end()) { s32 id = m_strings.size(); std::wstring wtext = utf8_to_wide(text); m_strings.emplace_back(wtext.c_str()); m_alloc_strings.insert(std::make_pair(text, id)); return id; } return it->second; } s32 GUITable::allocImage(const std::string &imagename) { std::map<std::string, s32>::iterator it = m_alloc_images.find(imagename); if (it == m_alloc_images.end()) { s32 id = m_images.size(); m_images.push_back(m_tsrc->getTexture(imagename)); m_alloc_images.insert(std::make_pair(imagename, id)); return id; } return it->second; } void GUITable::allocationComplete() { // Called when done with creating rows and cells from table data, // i.e. when allocString and allocImage won't be called anymore m_alloc_strings.clear(); m_alloc_images.clear(); } const GUITable::Row* GUITable::getRow(s32 i) const { if (i >= 0 && i < (s32) m_visible_rows.size()) return &m_rows[m_visible_rows[i]]; return NULL; } bool GUITable::doesRowStartWith(const Row *row, const core::stringw &str) const { if (row == NULL) return false; for (s32 j = 0; j < row->cellcount; ++j) { Cell *cell = &row->cells[j]; if (cell->content_type == COLUMN_TYPE_TEXT) { const core::stringw &cellstr = m_strings[cell->content_index]; if (cellstr.size() >= str.size() && str.equals_ignore_case(cellstr.subString(0, str.size()))) return true; } } return false; } s32 GUITable::getRowAt(s32 y, bool &really_hovering) const { really_hovering = false; s32 rowcount = m_visible_rows.size(); if (rowcount == 0) return -1; // Use arithmetic to find row s32 rel_y = y - AbsoluteRect.UpperLeftCorner.Y - 1; s32 i = (rel_y + m_scrollbar->getPos()) / m_rowheight; if (i >= 0 && i < rowcount) { really_hovering = true; return i; } if (i < 0) return 0; return rowcount - 1; } s32 GUITable::getCellAt(s32 x, s32 row_i) const { const Row *row = getRow(row_i); if (row == NULL) return -1; // Use binary search to find cell in row s32 rel_x = x - AbsoluteRect.UpperLeftCorner.X - 1; s32 jmin = 0; s32 jmax = row->cellcount - 1; while (jmin < jmax) { s32 pivot = jmin + (jmax - jmin) / 2; assert(pivot >= 0 && pivot < row->cellcount); const Cell *cell = &row->cells[pivot]; if (rel_x >= cell->xmin && rel_x <= cell->xmax) return pivot; if (rel_x < cell->xmin) jmax = pivot - 1; else jmin = pivot + 1; } if (jmin >= 0 && jmin < row->cellcount && rel_x >= row->cells[jmin].xmin && rel_x <= row->cells[jmin].xmax) return jmin; return -1; } void GUITable::autoScroll() { if (m_selected >= 0) { s32 pos = m_scrollbar->getPos(); s32 maxpos = m_selected * m_rowheight; s32 minpos = maxpos - (AbsoluteRect.getHeight() - m_rowheight); if (pos > maxpos) m_scrollbar->setPos(maxpos); else if (pos < minpos) m_scrollbar->setPos(minpos); } } void GUITable::updateScrollBar() { s32 totalheight = m_rowheight * m_visible_rows.size(); s32 scrollmax = MYMAX(0, totalheight - AbsoluteRect.getHeight()); m_scrollbar->setVisible(scrollmax > 0); m_scrollbar->setMax(scrollmax); m_scrollbar->setSmallStep(m_rowheight); m_scrollbar->setLargeStep(2 * m_rowheight); m_scrollbar->setPageSize(totalheight); } void GUITable::sendTableEvent(s32 column, bool doubleclick) { m_sel_column = column; m_sel_doubleclick = doubleclick; if (Parent) { SEvent e; memset(&e, 0, sizeof e); e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; e.GUIEvent.Element = 0; e.GUIEvent.EventType = gui::EGET_TABLE_CHANGED; Parent->OnEvent(e); } } void GUITable::getOpenedTrees(std::set<s32> &opened_trees) const { opened_trees.clear(); s32 rowcount = m_rows.size(); for (s32 i = 0; i < rowcount - 1; ++i) { if (m_rows[i].indent < m_rows[i+1].indent && m_rows[i+1].visible_index != -2) opened_trees.insert(i); } } void GUITable::setOpenedTrees(const std::set<s32> &opened_trees) { s32 old_selected = -1; if (m_selected >= 0) old_selected = m_visible_rows[m_selected]; std::vector<s32> parents; std::vector<s32> closed_parents; m_visible_rows.clear(); for (size_t i = 0; i < m_rows.size(); ++i) { Row *row = &m_rows[i]; // Update list of ancestors while (!parents.empty() && m_rows[parents.back()].indent >= row->indent) parents.pop_back(); while (!closed_parents.empty() && m_rows[closed_parents.back()].indent >= row->indent) closed_parents.pop_back(); assert(closed_parents.size() <= parents.size()); if (closed_parents.empty()) { // Visible row row->visible_index = m_visible_rows.size(); m_visible_rows.push_back(i); } else if (parents.back() == closed_parents.back()) { // Invisible row, direct parent is closed row->visible_index = -2; } else { // Invisible row, direct parent is open, some ancestor is closed row->visible_index = -1; } // If not a leaf, add to parents list if (i < m_rows.size()-1 && row->indent < m_rows[i+1].indent) { parents.push_back(i); s32 content_index = 0; // "-", open if (opened_trees.count(i) == 0) { closed_parents.push_back(i); content_index = 1; // "+", closed } // Update all cells of type "tree" for (s32 j = 0; j < row->cellcount; ++j) if (row->cells[j].content_type == COLUMN_TYPE_TREE) row->cells[j].content_index = content_index; } } updateScrollBar(); // m_selected must be updated since it is a visible row index if (old_selected >= 0) m_selected = m_rows[old_selected].visible_index; } void GUITable::openTree(s32 to_open) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); opened_trees.insert(to_open); setOpenedTrees(opened_trees); } void GUITable::closeTree(s32 to_close) { std::set<s32> opened_trees; getOpenedTrees(opened_trees); opened_trees.erase(to_close); setOpenedTrees(opened_trees); } // The following function takes a visible row index (hidden rows skipped) // dir: -1 = left (close), 0 = auto (toggle), 1 = right (open) void GUITable::toggleVisibleTree(s32 row_i, int dir, bool move_selection) { // Check if the chosen tree is currently open const Row *row = getRow(row_i); if (row == NULL) return; bool was_open = false; for (s32 j = 0; j < row->cellcount; ++j) { if (row->cells[j].content_type == COLUMN_TYPE_TREE) { was_open = row->cells[j].content_index == 0; break; } } // Check if the chosen tree should be opened bool do_open = !was_open; if (dir < 0) do_open = false; else if (dir > 0) do_open = true; // Close or open the tree; the heavy lifting is done by setOpenedTrees if (was_open && !do_open) closeTree(m_visible_rows[row_i]); else if (!was_open && do_open) openTree(m_visible_rows[row_i]); // Change selected row if requested by caller, // this is useful for keyboard navigation if (move_selection) { s32 sel = row_i; if (was_open && do_open) { // Move selection to first child const Row *maybe_child = getRow(sel + 1); if (maybe_child && maybe_child->indent > row->indent) sel++; } else if (!was_open && !do_open) { // Move selection to parent assert(getRow(sel) != NULL); while (sel > 0 && getRow(sel - 1)->indent >= row->indent) sel--; sel--; if (sel < 0) // was root already selected? sel = row_i; } if (sel != m_selected) { m_selected = sel; autoScroll(); sendTableEvent(0, false); } } } void GUITable::alignContent(Cell *cell, s32 xmax, s32 content_width, s32 align) { // requires that cell.xmin, cell.xmax are properly set // align = 0: left aligned, 1: centered, 2: right aligned, 3: inline if (align == 0) { cell->xpos = cell->xmin; cell->xmax = xmax; } else if (align == 1) { cell->xpos = (cell->xmin + xmax - content_width) / 2; cell->xmax = xmax; } else if (align == 2) { cell->xpos = xmax - content_width; cell->xmax = xmax; } else { // inline alignment: the cells of the column don't have an aligned // right border, the right border of each cell depends on the content cell->xpos = cell->xmin; cell->xmax = cell->xmin + content_width; } }