aboutsummaryrefslogtreecommitdiff
path: root/lib/lua/src/lstrlib.c
blob: 7a03489bebd451c725690a4ab6da220e5e0f0311 (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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
/*
** $Id: lstrlib.c,v 1.132.1.5 2010/05/14 15:34:19 roberto Exp $
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/


#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define lstrlib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"


/* macro to `unsign' a character */
#define uchar(c)        ((unsigned char)(c))



static int str_len (lua_State *L) {
  size_t l;
  luaL_checklstring(L, 1, &l);
  lua_pushinteger(L, l);
  return 1;
}


static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
  /* relative string position: negative means back from end */
  if (pos < 0) pos += (ptrdiff_t)len + 1;
  return (pos >= 0) ? pos : 0;
}


static int str_sub (lua_State *L) {
  size_t l;
  const char *s = luaL_checklstring(L, 1, &l);
  ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
  ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
  if (start < 1) start = 1;
  if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
  if (start <= end)
    lua_pushlstring(L, s+start-1, end-start+1);
  else lua_pushliteral(L, "");
  return 1;
}


static int str_reverse (lua_State *L) {
  size_t l;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  while (l--) luaL_addchar(&b, s[l]);
  luaL_pushresult(&b);
  return 1;
}


static int str_lower (lua_State *L) {
  size_t l;
  size_t i;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  for (i=0; i<l; i++)
    luaL_addchar(&b, tolower(uchar(s[i])));
  luaL_pushresult(&b);
  return 1;
}


static int str_upper (lua_State *L) {
  size_t l;
  size_t i;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  for (i=0; i<l; i++)
    luaL_addchar(&b, toupper(uchar(s[i])));
  luaL_pushresult(&b);
  return 1;
}

static int str_rep (lua_State *L) {
  size_t l;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  int n = luaL_checkint(L, 2);
  luaL_buffinit(L, &b);
  while (n-- > 0)
    luaL_addlstring(&b, s, l);
  luaL_pushresult(&b);
  return 1;
}


static int str_byte (lua_State *L) {
  size_t l;
  const char *s = luaL_checklstring(L, 1, &l);
  ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  int n, i;
  if (posi <= 0) posi = 1;
  if ((size_t)pose > l) pose = l;
  if (posi > pose) return 0;  /* empty interval; return no values */
  n = (int)(pose -  posi + 1);
  if (posi + n <= pose)  /* overflow? */
    luaL_error(L, "string slice too long");
  luaL_checkstack(L, n, "string slice too long");
  for (i=0; i<n; i++)
    lua_pushinteger(L, uchar(s[posi+i-1]));
  return n;
}


static int str_char (lua_State *L) {
  int n = lua_gettop(L);  /* number of arguments */
  int i;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  for (i=1; i<=n; i++) {
    int c = luaL_checkint(L, i);
    luaL_argcheck(L, uchar(c) == c, i, "invalid value");
    luaL_addchar(&b, uchar(c));
  }
  luaL_pushresult(&b);
  return 1;
}


static int writer (lua_State *L, const void* b, size_t size, void* B) {
  (void)L;
  luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  return 0;
}


static int str_dump (lua_State *L) {
  luaL_Buffer b;
  luaL_checktype(L, 1, LUA_TFUNCTION);
  lua_settop(L, 1);
  luaL_buffinit(L,&b);
  if (lua_dump(L, writer, &b) != 0)
    luaL_error(L, "unable to dump given function");
  luaL_pushresult(&b);
  return 1;
}



/*
** {======================================================
** PATTERN MATCHING
** =======================================================
*/


#define CAP_UNFINISHED	(-1)
#define CAP_POSITION	(-2)

typedef struct MatchState {
  const char *src_init;  /* init of source string */
  const char *src_end;  /* end (`\0') of source string */
  lua_State *L;
  int level;  /* total number of captures (finished or unfinished) */
  struct {
    const char *init;
    ptrdiff_t len;
  } capture[LUA_MAXCAPTURES];
} MatchState;


#define L_ESC		'%'
#define SPECIALS	"^$*+?.([%-"


static int check_capture (MatchState *ms, int l) {
  l -= '1';
  if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
    return luaL_error(ms->L, "invalid capture index");
  return l;
}


static int capture_to_close (MatchState *ms) {
  int level = ms->level;
  for (level--; level>=0; level--)
    if (ms->capture[level].len == CAP_UNFINISHED) return level;
  return luaL_error(ms->L, "invalid pattern capture");
}


static const char *classend (MatchState *ms, const char *p) {
  switch (*p++) {
    case L_ESC: {
      if (*p == '\0')
        luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
      return p+1;
    }
    case '[': {
      if (*p == '^') p++;
      do {  /* look for a `]' */
        if (*p == '\0')
          luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
        if (*(p++) == L_ESC && *p != '\0')
          p++;  /* skip escapes (e.g. `%]') */
      } while (*p != ']');
      return p+1;
    }
    default: {
      return p;
    }
  }
}


static int match_class (int c, int cl) {
  int res;
  switch (tolower(cl)) {
    case 'a' : res = isalpha(c); break;
    case 'c' : res = iscntrl(c); break;
    case 'd' : res = isdigit(c); break;
    case 'l' : res = islower(c); break;
    case 'p' : res = ispunct(c); break;
    case 's' : res = isspace(c); break;
    case 'u' : res = isupper(c); break;
    case 'w' : res = isalnum(c); break;
    case 'x' : res = isxdigit(c); break;
    case 'z' : res = (c == 0); break;
    default: return (cl == c);
  }
  return (islower(cl) ? res : !res);
}


static int matchbracketclass (int c, const char *p, const char *ec) {
  int sig = 1;
  if (*(p+1) == '^') {
    sig = 0;
    p++;  /* skip the `^' */
  }
  while (++p < ec) {
    if (*p == L_ESC) {
      p++;
      if (match_class(c, uchar(*p)))
        return sig;
    }
    else if ((*(p+1) == '-') && (p+2 < ec)) {
      p+=2;
      if (uchar(*(p-2)) <= c && c <= uchar(*p))
        return sig;
    }
    else if (uchar(*p) == c) return sig;
  }
  return !sig;
}


static int singlematch (int c, const char *p, const char *ep) {
  switch (*p) {
    case '.': return 1;  /* matches any char */
    case L_ESC: return match_class(c, uchar(*(p+1)));
    case '[': return matchbracketclass(c, p, ep-1);
    default:  return (uchar(*p) == c);
  }
}


static const char *match (MatchState *ms, const char *s, const char *p);


static const char *matchbalance (MatchState *ms, const char *s,
                                   const char *p) {
  if (*p == 0 || *(p+1) == 0)
    luaL_error(ms->L, "unbalanced pattern");
  if (*s != *p) return NULL;
  else {
    int b = *p;
    int e = *(p+1);
    int cont = 1;
    while (++s < ms->src_end) {
      if (*s == e) {
        if (--cont == 0) return s+1;
      }
      else if (*s == b) cont++;
    }
  }
  return NULL;  /* string ends out of balance */
}


static const char *max_expand (MatchState *ms, const char *s,
                                 const char *p, const char *ep) {
  ptrdiff_t i = 0;  /* counts maximum expand for item */
  while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
    i++;
  /* keeps trying to match with the maximum repetitions */
  while (i>=0) {
    const char *res = match(ms, (s+i), ep+1);
    if (res) return res;
    i--;  /* else didn't match; reduce 1 repetition to try again */
  }
  return NULL;
}


static const char *min_expand (MatchState *ms, const char *s,
                                 const char *p, const char *ep) {
  for (;;) {
    const char *res = match(ms, s, ep+1);
    if (res != NULL)
      return res;
    else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
      s++;  /* try with one more repetition */
    else return NULL;
  }
}


static const char *start_capture (MatchState *ms, const char *s,
                                    const char *p, int what) {
  const char *res;
  int level = ms->level;
  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  ms->capture[level].init = s;
  ms->capture[level].len = what;
  ms->level = level+1;
  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
    ms->level--;  /* undo capture */
  return res;
}


static const char *end_capture (MatchState *ms, const char *s,
                                  const char *p) {
  int l = capture_to_close(ms);
  const char *res;
  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
  return res;
}


static const char *match_capture (MatchState *ms, const char *s, int l) {
  size_t len;
  l = check_capture(ms, l);
  len = ms->capture[l].len;
  if ((size_t)(ms->src_end-s) >= len &&
      memcmp(ms->capture[l].init, s, len) == 0)
    return s+len;
  else return NULL;
}


static const char *match (MatchState *ms, const char *s, const char *p) {
  init: /* using goto's to optimize tail recursion */
  switch (*p) {
    case '(': {  /* start capture */
      if (*(p+1) == ')')  /* position capture? */
        return start_capture(ms, s, p+2, CAP_POSITION);
      else
        return start_capture(ms, s, p+1, CAP_UNFINISHED);
    }
    case ')': {  /* end capture */
      return end_capture(ms, s, p+1);
    }
    case L_ESC: {
      switch (*(p+1)) {
        case 'b': {  /* balanced string? */
          s = matchbalance(ms, s, p+2);
          if (s == NULL) return NULL;
          p+=4; goto init;  /* else return match(ms, s, p+4); */
        }
        case 'f': {  /* frontier? */
          const char *ep; char previous;
          p += 2;
          if (*p != '[')
            luaL_error(ms->L, "missing " LUA_QL("[") " after "
                               LUA_QL("%%f") " in pattern");
          ep = classend(ms, p);  /* points to what is next */
          previous = (s == ms->src_init) ? '\0' : *(s-1);
          if (matchbracketclass(uchar(previous), p, ep-1) ||
             !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
          p=ep; goto init;  /* else return match(ms, s, ep); */
        }
        default: {
          if (isdigit(uchar(*(p+1)))) {  /* capture results (%0-%9)? */
            s = match_capture(ms, s, uchar(*(p+1)));
            if (s == NULL) return NULL;
            p+=2; goto init;  /* else return match(ms, s, p+2) */
          }
          goto dflt;  /* case default */
        }
      }
    }
    case '\0': {  /* end of pattern */
      return s;  /* match succeeded */
    }
    case '$': {
      if (*(p+1) == '\0')  /* is the `$' the last char in pattern? */
        return (s == ms->src_end) ? s : NULL;  /* check end of string */
      else goto dflt;
    }
    default: dflt: {  /* it is a pattern item */
      const char *ep = classend(ms, p);  /* points to what is next */
      int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
      switch (*ep) {
        case '?': {  /* optional */
          const char *res;
          if (m && ((res=match(ms, s+1, ep+1)) != NULL))
            return res;
          p=ep+1; goto init;  /* else return match(ms, s, ep+1); */
        }
        case '*': {  /* 0 or more repetitions */
          return max_expand(ms, s, p, ep);
        }
        case '+': {  /* 1 or more repetitions */
          return (m ? max_expand(ms, s+1, p, ep) : NULL);
        }
        case '-': {  /* 0 or more repetitions (minimum) */
          return min_expand(ms, s, p, ep);
        }
        default: {
          if (!m) return NULL;
          s++; p=ep; goto init;  /* else return match(ms, s+1, ep); */
        }
      }
    }
  }
}



static const char *lmemfind (const char *s1, size_t l1,
                               const char *s2, size_t l2) {
  if (l2 == 0) return s1;  /* empty strings are everywhere */
  else if (l2 > l1) return NULL;  /* avoids a negative `l1' */
  else {
    const char *init;  /* to search for a `*s2' inside `s1' */
    l2--;  /* 1st char will be checked by `memchr' */
    l1 = l1-l2;  /* `s2' cannot be found after that */
    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
      init++;   /* 1st char is already checked */
      if (memcmp(init, s2+1, l2) == 0)
        return init-1;
      else {  /* correct `l1' and `s1' to try again */
        l1 -= init-s1;
        s1 = init;
      }
    }
    return NULL;  /* not found */
  }
}


static void push_onecapture (MatchState *ms, int i, const char *s,
                                                    const char *e) {
  if (i >= ms->level) {
    if (i == 0)  /* ms->level == 0, too */
      lua_pushlstring(ms->L, s, e - s);  /* add whole match */
    else
      luaL_error(ms->L, "invalid capture index");
  }
  else {
    ptrdiff_t l = ms->capture[i].len;
    if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
    if (l == CAP_POSITION)
      lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
    else
      lua_pushlstring(ms->L, ms->capture[i].init, l);
  }
}


static int push_captures (MatchState *ms, const char *s, const char *e) {
  int i;
  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  luaL_checkstack(ms->L, nlevels, "too many captures");
  for (i = 0; i < nlevels; i++)
    push_onecapture(ms, i, s, e);
  return nlevels;  /* number of strings pushed */
}


static int str_find_aux (lua_State *L, int find) {
  size_t l1, l2;
  const char *s = luaL_checklstring(L, 1, &l1);
  const char *p = luaL_checklstring(L, 2, &l2);
  ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
  if (init < 0) init = 0;
  else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
  if (find && (lua_toboolean(L, 4) ||  /* explicit request? */
      strpbrk(p, SPECIALS) == NULL)) {  /* or no special characters? */
    /* do a plain search */
    const char *s2 = lmemfind(s+init, l1-init, p, l2);
    if (s2) {
      lua_pushinteger(L, s2-s+1);
      lua_pushinteger(L, s2-s+l2);
      return 2;
    }
  }
  else {
    MatchState ms;
    int anchor = (*p == '^') ? (p++, 1) : 0;
    const char *s1=s+init;
    ms.L = L;
    ms.src_init = s;
    ms.src_end = s+l1;
    do {
      const char *res;
      ms.level = 0;
      if ((res=match(&ms, s1, p)) != NULL) {
        if (find) {
          lua_pushinteger(L, s1-s+1);  /* start */
          lua_pushinteger(L, res-s);   /* end */
          return push_captures(&ms, NULL, 0) + 2;
        }
        else
          return push_captures(&ms, s1, res);
      }
    } while (s1++ < ms.src_end && !anchor);
  }
  lua_pushnil(L);  /* not found */
  return 1;
}


static int str_find (lua_State *L) {
  return str_find_aux(L, 1);
}


static int str_match (lua_State *L) {
  return str_find_aux(L, 0);
}


static int gmatch_aux (lua_State *L) {
  MatchState ms;
  size_t ls;
  const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  const char *p = lua_tostring(L, lua_upvalueindex(2));
  const char *src;
  ms.L = L;
  ms.src_init = s;
  ms.src_end = s+ls;
  for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
       src <= ms.src_end;
       src++) {
    const char *e;
    ms.level = 0;
    if ((e = match(&ms, src, p)) != NULL) {
      lua_Integer newstart = e-s;
      if (e == src) newstart++;  /* empty match? go at least one position */
      lua_pushinteger(L, newstart);
      lua_replace(L, lua_upvalueindex(3));
      return push_captures(&ms, src, e);
    }
  }
  return 0;  /* not found */
}


static int gmatch (lua_State *L) {
  luaL_checkstring(L, 1);
  luaL_checkstring(L, 2);
  lua_settop(L, 2);
  lua_pushinteger(L, 0);
  lua_pushcclosure(L, gmatch_aux, 3);
  return 1;
}


static int gfind_nodef (lua_State *L) {
  return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
                       LUA_QL("string.gmatch"));
}


static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
                                                   const char *e) {
  size_t l, i;
  const char *news = lua_tolstring(ms->L, 3, &l);
  for (i = 0; i < l; i++) {
    if (news[i] != L_ESC)
      luaL_addchar(b, news[i]);
    else {
      i++;  /* skip ESC */
      if (!isdigit(uchar(news[i])))
        luaL_addchar(b, news[i]);
      else if (news[i] == '0')
          luaL_addlstring(b, s, e - s);
      else {
        push_onecapture(ms, news[i] - '1', s, e);
        luaL_addvalue(b);  /* add capture to accumulated result */
      }
    }
  }
}


static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
                                                       const char *e) {
  lua_State *L = ms->L;
  switch (lua_type(L, 3)) {
    case LUA_TNUMBER:
    case LUA_TSTRING: {
      add_s(ms, b, s, e);
      return;
    }
    case LUA_TFUNCTION: {
      int n;
      lua_pushvalue(L, 3);
      n = push_captures(ms, s, e);
      lua_call(L, n, 1);
      break;
    }
    case LUA_TTABLE: {
      push_onecapture(ms, 0, s, e);
      lua_gettable(L, 3);
      break;
    }
  }
  if (!lua_toboolean(L, -1)) {  /* nil or false? */
    lua_pop(L, 1);
    lua_pushlstring(L, s, e - s);  /* keep original text */
  }
  else if (!lua_isstring(L, -1))
    luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); 
  luaL_addvalue(b);  /* add result to accumulator */
}


static int str_gsub (lua_State *L) {
  size_t srcl;
  const char *src = luaL_checklstring(L, 1, &srcl);
  const char *p = luaL_checkstring(L, 2);
  int  tr = lua_type(L, 3);
  int max_s = luaL_optint(L, 4, srcl+1);
  int anchor = (*p == '^') ? (p++, 1) : 0;
  int n = 0;
  MatchState ms;
  luaL_Buffer b;
  luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
                      "string/function/table expected");
  luaL_buffinit(L, &b);
  ms.L = L;
  ms.src_init = src;
  ms.src_end = src+srcl;
  while (n < max_s) {
    const char *e;
    ms.level = 0;
    e = match(&ms, src, p);
    if (e) {
      n++;
      add_value(&ms, &b, src, e);
    }
    if (e && e>src) /* non empty match? */
      src = e;  /* skip it */
    else if (src < ms.src_end)
      luaL_addchar(&b, *src++);
    else break;
    if (anchor) break;
  }
  luaL_addlstring(&b, src, ms.src_end-src);
  luaL_pushresult(&b);
  lua_pushinteger(L, n);  /* number of substitutions */
  return 2;
}

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


/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
#define MAX_ITEM	512
/* valid flags in a format specification */
#define FLAGS	"-+ #0"
/*
** maximum size of each format specification (such as '%-099.99d')
** (+10 accounts for %99.99x plus margin of error)
*/
#define MAX_FORMAT	(sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)


static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  size_t l;
  const char *s = luaL_checklstring(L, arg, &l);
  luaL_addchar(b, '"');
  while (l--) {
    switch (*s) {
      case '"': case '\\': case '\n': {
        luaL_addchar(b, '\\');
        luaL_addchar(b, *s);
        break;
      }
      case '\r': {
        luaL_addlstring(b, "\\r", 2);
        break;
      }
      case '\0': {
        luaL_addlstring(b, "\\000", 4);
        break;
      }
      default: {
        luaL_addchar(b, *s);
        break;
      }
    }
    s++;
  }
  luaL_addchar(b, '"');
}

static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  const char *p = strfrmt;
  while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++;  /* skip flags */
  if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
    luaL_error(L, "invalid format (repeated flags)");
  if (isdigit(uchar(*p))) p++;  /* skip width */
  if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
  if (*p == '.') {
    p++;
    if (isdigit(uchar(*p))) p++;  /* skip precision */
    if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
  }
  if (isdigit(uchar(*p)))
    luaL_error(L, "invalid format (width or precision too long)");
  *(form++) = '%';
  strncpy(form, strfrmt, p - strfrmt + 1);
  form += p - strfrmt + 1;
  *form = '\0';
  return p;
}


static void addintlen (char *form) {
  size_t l = strlen(form);
  char spec = form[l - 1];
  strcpy(form + l - 1, LUA_INTFRMLEN);
  form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
  form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
}


static int str_format (lua_State *L) {
  int top = lua_gettop(L);
  int arg = 1;
  size_t sfl;
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  const char *strfrmt_end = strfrmt+sfl;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  while (strfrmt < strfrmt_end) {
    if (*strfrmt != L_ESC)
      luaL_addchar(&b, *strfrmt++);
    else if (*++strfrmt == L_ESC)
      luaL_addchar(&b, *strfrmt++);  /* %% */
    else { /* format item */
      char form[MAX_FORMAT];  /* to store the format (`%...') */
      char buff[MAX_ITEM];  /* to store the formatted item */
      if (++arg > top)
        luaL_argerror(L, arg, "no value");
      strfrmt = scanformat(L, strfrmt, form);
      switch (*strfrmt++) {
        case 'c': {
          sprintf(buff, form, (int)luaL_checknumber(L, arg));
          break;
        }
        case 'd':  case 'i': {
          addintlen(form);
          sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
          break;
        }
        case 'o':  case 'u':  case 'x':  case 'X': {
          addintlen(form);
          sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
          break;
        }
        case 'e':  case 'E': case 'f':
        case 'g': case 'G': {
          sprintf(buff, form, (double)luaL_checknumber(L, arg));
          break;
        }
        case 'q': {
          addquoted(L, &b, arg);
          continue;  /* skip the 'addsize' at the end */
        }
        case 's': {
          size_t l;
          const char *s = luaL_checklstring(L, arg, &l);
          if (!strchr(form, '.') && l >= 100) {
            /* no precision and string is too long to be formatted;
               keep original string */
            lua_pushvalue(L, arg);
            luaL_addvalue(&b);
            continue;  /* skip the `addsize' at the end */
          }
          else {
            sprintf(buff, form, s);
            break;
          }
        }
        default: {  /* also treat cases `pnLlh' */
          return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
                               LUA_QL("format"), *(strfrmt - 1));
        }
      }
      luaL_addlstring(&b, buff, strlen(buff));
    }
  }
  luaL_pushresult(&b);
  return 1;
}


static const luaL_Reg strlib[] = {
  {"byte", str_byte},
  {"char", str_char},
  {"dump", str_dump},
  {"find", str_find},
  {"format", str_format},
  {"gfind", gfind_nodef},
  {"gmatch", gmatch},
  {"gsub", str_gsub},
  {"len", str_len},
  {"lower", str_lower},
  {"match", str_match},
  {"rep", str_rep},
  {"reverse", str_reverse},
  {"sub", str_sub},
  {"upper", str_upper},
  {NULL, NULL}
};


static void createmetatable (lua_State *L) {
  lua_createtable(L, 0, 1);  /* create metatable for strings */
  lua_pushliteral(L, "");  /* dummy string */
  lua_pushvalue(L, -2);
  lua_setmetatable(L, -2);  /* set string metatable */
  lua_pop(L, 1);  /* pop dummy string */
  lua_pushvalue(L, -2);  /* string library... */
  lua_setfield(L, -2, "__index");  /* ...is the __index metamethod */
  lua_pop(L, 1);  /* pop metatable */
}


/*
** Open string library
*/
LUALIB_API int luaopen_string (lua_State *L) {
  luaL_register(L, LUA_STRLIBNAME, strlib);
#if defined(LUA_COMPAT_GFIND)
  lua_getfield(L, -1, "gmatch");
  lua_setfield(L, -2, "gfind");
#endif
  createmetatable(L);
  return 1;
}

ss="hl num">2]; std::string selected = ""; if (parts.size() == 4) selected = parts[3]; MY_CHECKPOS("checkbox",0); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float) spacing.X; pos.Y += stof(v_pos[1]) * (float) spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15)); bool fselected = false; if (selected == "true") fselected = true; std::wstring wlabel = narrow_to_wide(label.c_str()); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), L"", wlabel, 258+m_fields.size() ); spec.ftype = f_CheckBox; spec.flabel = wlabel; //Needed for displaying text on MSVC gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } m_checkboxes.push_back(std::pair<FieldSpec,gui::IGUICheckBox*>(spec,e)); m_fields.push_back(spec); return; } errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseImage(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 3) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = unescape_string(parts[2]); MY_CHECKPOS("image",0); MY_CHECKGEOM("image",1); v2s32 pos = padding + AbsoluteRect.UpperLeftCorner; pos.X += stof(v_pos[0]) * (float) spacing.X; pos.Y += stof(v_pos[1]) * (float) spacing.Y; v2s32 geom; geom.X = stof(v_geom[0]) * (float)imgsize.X; geom.Y = stof(v_geom[1]) * (float)imgsize.Y; if(data->bp_set != 2) errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl; m_images.push_back(ImageDrawSpec(name, pos, geom)); return; } if (parts.size() == 2) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = unescape_string(parts[1]); MY_CHECKPOS("image",0); v2s32 pos = padding + AbsoluteRect.UpperLeftCorner; pos.X += stof(v_pos[0]) * (float) spacing.X; pos.Y += stof(v_pos[1]) * (float) spacing.Y; if(data->bp_set != 2) errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl; m_images.push_back(ImageDrawSpec(name, pos)); return; } errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseItemImage(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 3) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; MY_CHECKPOS("itemimage",0); MY_CHECKGEOM("itemimage",1); v2s32 pos = padding + AbsoluteRect.UpperLeftCorner; pos.X += stof(v_pos[0]) * (float) spacing.X; pos.Y += stof(v_pos[1]) * (float) spacing.Y; v2s32 geom; geom.X = stoi(v_geom[0]) * (float)imgsize.X; geom.Y = stoi(v_geom[1]) * (float)imgsize.Y; if(data->bp_set != 2) errorstream<<"WARNING: invalid use of item_image without a size[] element"<<std::endl; m_itemimages.push_back(ImageDrawSpec(name, pos, geom)); return; } errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseButton(parserData* data,std::string element, std::string type) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 4) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; MY_CHECKPOS("button",0); MY_CHECKGEOM("button",1); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X); pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15); if(data->bp_set != 2) errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl; label = unescape_string(label); std::wstring wlabel = narrow_to_wide(label.c_str()); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), wlabel, L"", 258+m_fields.size() ); spec.ftype = f_Button; if(type == "button_exit") spec.is_exit = true; gui::IGUIButton* e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } m_fields.push_back(spec); return; } errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseBackground(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 3) || (parts.size() == 4)) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = unescape_string(parts[2]); MY_CHECKPOS("background",0); MY_CHECKGEOM("background",1); v2s32 pos = padding + AbsoluteRect.UpperLeftCorner; pos.X += stof(v_pos[0]) * (float)spacing.X - ((float)spacing.X-(float)imgsize.X)/2; pos.Y += stof(v_pos[1]) * (float)spacing.Y - ((float)spacing.Y-(float)imgsize.Y)/2; v2s32 geom; geom.X = stof(v_geom[0]) * (float)spacing.X; geom.Y = stof(v_geom[1]) * (float)spacing.Y; if (parts.size() == 4) { m_clipbackground = is_yes(parts[3]); if (m_clipbackground) { pos.X = stoi(v_pos[0]); //acts as offset pos.Y = stoi(v_pos[1]); //acts as offset } } if(data->bp_set != 2) errorstream<<"WARNING: invalid use of background without a size[] element"<<std::endl; m_backgrounds.push_back(ImageDrawSpec(name, pos, geom)); return; } errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTableOptions(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); data->table_options.clear(); for (size_t i = 0; i < parts.size(); ++i) { // Parse table option std::string opt = unescape_string(parts[i]); data->table_options.push_back(GUITable::splitOption(opt)); } } void GUIFormSpecMenu::parseTableColumns(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); data->table_columns.clear(); for (size_t i = 0; i < parts.size(); ++i) { std::vector<std::string> col_parts = split(parts[i],','); GUITable::TableColumn column; // Parse column type if (!col_parts.empty()) column.type = col_parts[0]; // Parse column options for (size_t j = 1; j < col_parts.size(); ++j) { std::string opt = unescape_string(col_parts[j]); column.options.push_back(GUITable::splitOption(opt)); } data->table_columns.push_back(column); } } void GUIFormSpecMenu::parseTable(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 4) || (parts.size() == 5)) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::vector<std::string> items = split(parts[3],','); std::string str_initial_selection = ""; std::string str_transparent = "false"; if (parts.size() >= 5) str_initial_selection = parts[4]; MY_CHECKPOS("table",0); MY_CHECKGEOM("table",1); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = stof(v_geom[0]) * (float)spacing.X; geom.Y = stof(v_geom[1]) * (float)spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); std::wstring fname_w = narrow_to_wide(name.c_str()); FieldSpec spec = FieldSpec( fname_w, L"", L"", 258+m_fields.size() ); spec.ftype = f_Table; for (unsigned int i = 0; i < items.size(); ++i) { items[i] = unescape_string(items[i]); } //now really show table GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc); e->drop(); // IGUIElement maintains the remaining reference if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setTable(data->table_options, data->table_columns, items); if (data->table_dyndata.find(fname_w) != data->table_dyndata.end()) { e->setDynamicData(data->table_dyndata[fname_w]); } if ((str_initial_selection != "") && (str_initial_selection != "0")) e->setSelected(stoi(str_initial_selection.c_str())); m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e)); m_fields.push_back(spec); return; } errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTextList(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::vector<std::string> items = split(parts[3],','); std::string str_initial_selection = ""; std::string str_transparent = "false"; if (parts.size() >= 5) str_initial_selection = parts[4]; if (parts.size() >= 6) str_transparent = parts[5]; MY_CHECKPOS("textlist",0); MY_CHECKGEOM("textlist",1); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = stof(v_geom[0]) * (float)spacing.X; geom.Y = stof(v_geom[1]) * (float)spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); std::wstring fname_w = narrow_to_wide(name.c_str()); FieldSpec spec = FieldSpec( fname_w, L"", L"", 258+m_fields.size() ); spec.ftype = f_Table; for (unsigned int i = 0; i < items.size(); ++i) { items[i] = unescape_string(items[i]); } //now really show list GUITable *e = new GUITable(Environment, this, spec.fid, rect, m_tsrc); e->drop(); // IGUIElement maintains the remaining reference if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setTextList(items, is_yes(str_transparent)); if (data->table_dyndata.find(fname_w) != data->table_dyndata.end()) { e->setDynamicData(data->table_dyndata[fname_w]); } if ((str_initial_selection != "") && (str_initial_selection != "0")) e->setSelected(stoi(str_initial_selection.c_str())); m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e)); m_fields.push_back(spec); return; } errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 5) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = parts[2]; std::vector<std::string> items = split(parts[3],','); std::string str_initial_selection = ""; str_initial_selection = parts[4]; MY_CHECKPOS("dropdown",0); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; s32 width = stof(parts[1]) * (float)spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+width, pos.Y+30); std::wstring fname_w = narrow_to_wide(name.c_str()); FieldSpec spec = FieldSpec( fname_w, L"", L"", 258+m_fields.size() ); spec.ftype = f_DropDown; spec.send = true; //now really show list gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } for (unsigned int i=0; i < items.size(); i++) { e->addItem(narrow_to_wide(items[i]).c_str()); } if (str_initial_selection != "") e->setSelected(stoi(str_initial_selection.c_str())-1); m_fields.push_back(spec); return; } errorstream << "Invalid dropdown element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 4) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; MY_CHECKPOS("pwdfield",0); MY_CHECKGEOM("pwdfield",1); v2s32 pos; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X); pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; pos.Y -= 15; geom.Y = 30; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); label = unescape_string(label); std::wstring wlabel = narrow_to_wide(label.c_str()); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), wlabel, L"", 258+m_fields.size() ); spec.send = true; gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } if (label.length() >= 1) { rect.UpperLeftCorner.Y -= 15; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15; Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0); } e->setPasswordBox(true,L'*'); irr::SEvent evt; evt.EventType = EET_KEY_INPUT_EVENT; evt.KeyInput.Key = KEY_END; evt.KeyInput.Char = 0; evt.KeyInput.Control = 0; evt.KeyInput.Shift = 0; evt.KeyInput.PressedDown = true; e->OnEvent(evt); m_fields.push_back(spec); return; } errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseSimpleField(parserData* data, std::vector<std::string> &parts) { std::string name = parts[0]; std::string label = parts[1]; std::string default_val = parts[2]; core::rect<s32> rect; if(!data->bp_set) { rect = core::rect<s32>( data->screensize.X/2 - 580/2, data->screensize.Y/2 - 300/2, data->screensize.X/2 + 580/2, data->screensize.Y/2 + 300/2 ); DesiredRect = rect; recalculateAbsolutePosition(false); data->basepos = getBasePos(); data->bp_set = 1; } else if(data->bp_set == 2) errorstream<<"WARNING: invalid use of unpositioned \"field\" in inventory"<<std::endl; v2s32 pos = padding + AbsoluteRect.UpperLeftCorner; pos.Y = ((m_fields.size()+2)*60); v2s32 size = DesiredRect.getSize(); rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30); if(m_form_src) default_val = m_form_src->resolveText(default_val); default_val = unescape_string(default_val); label = unescape_string(label); std::wstring wlabel = narrow_to_wide(label.c_str()); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), wlabel, narrow_to_wide(default_val.c_str()), 258+m_fields.size() ); if (name == "") { // spec field id to 0, this stops submit searching for a value that isn't there Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid); } else { spec.send = true; gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } irr::SEvent evt; evt.EventType = EET_KEY_INPUT_EVENT; evt.KeyInput.Key = KEY_END; evt.KeyInput.Char = 0; evt.KeyInput.Control = 0; evt.KeyInput.Shift = 0; evt.KeyInput.PressedDown = true; e->OnEvent(evt); if (label.length() >= 1) { rect.UpperLeftCorner.Y -= 15; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15; Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0); } } m_fields.push_back(spec); } void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,std::string type) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string name = parts[2]; std::string label = parts[3]; std::string default_val = parts[4]; MY_CHECKPOS(type,0); MY_CHECKGEOM(type,1); v2s32 pos; pos.X = stof(v_pos[0]) * (float) spacing.X; pos.Y = stof(v_pos[1]) * (float) spacing.Y; v2s32 geom; geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X); if (type == "textarea") { geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y); pos.Y += 15; } else { pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2; pos.Y -= 15; geom.Y = 30; } core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); if(data->bp_set != 2) errorstream<<"WARNING: invalid use of positioned "<<type<<" without a size[] element"<<std::endl; if(m_form_src) default_val = m_form_src->resolveText(default_val); default_val = unescape_string(default_val); label = unescape_string(label); std::wstring wlabel = narrow_to_wide(label.c_str()); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), wlabel, narrow_to_wide(default_val.c_str()), 258+m_fields.size() ); if (name == "") { // spec field id to 0, this stops submit searching for a value that isn't there Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid); } else { spec.send = true; gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } if (type == "textarea") { e->setMultiLine(true); e->setWordWrap(true); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT); } else { irr::SEvent evt; evt.EventType = EET_KEY_INPUT_EVENT; evt.KeyInput.Key = KEY_END; evt.KeyInput.Char = 0; evt.KeyInput.Control = 0; evt.KeyInput.Shift = 0; evt.KeyInput.PressedDown = true; e->OnEvent(evt); } if (label.length() >= 1) { rect.UpperLeftCorner.Y -= 15; rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15; Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0); } } m_fields.push_back(spec); } void GUIFormSpecMenu::parseField(parserData* data,std::string element, std::string type) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 3) { parseSimpleField(data,parts); return; } if (parts.size() == 5) { parseTextArea(data,parts,type); return; } errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseLabel(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 2) { std::vector<std::string> v_pos = split(parts[0],','); std::string text = parts[1]; MY_CHECKPOS("label",0); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15)); if(data->bp_set != 2) errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl; text = unescape_string(text); std::wstring wlabel = narrow_to_wide(text.c_str()); FieldSpec spec = FieldSpec( L"", wlabel, L"", 258+m_fields.size() ); Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid); m_fields.push_back(spec); return; } errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 2) { std::vector<std::string> v_pos = split(parts[0],','); std::wstring text = narrow_to_wide(unescape_string(parts[1])); MY_CHECKPOS("vertlabel",1); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+15, pos.Y+300); if(data->bp_set != 2) errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl; std::wstring label = L""; for (unsigned int i=0; i < text.length(); i++) { label += text[i]; label += L"\n"; } FieldSpec spec = FieldSpec( L"", label, L"", 258+m_fields.size() ); gui::IGUIStaticText *t = Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid); t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); m_fields.push_back(spec); return; } errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element, std::string type) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 5) || (parts.size() == 7) || (parts.size() == 8)) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string image_name = parts[2]; std::string name = parts[3]; std::string label = parts[4]; MY_CHECKPOS("imagebutton",0); MY_CHECKGEOM("imagebutton",1); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X); geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y); bool noclip = false; bool drawborder = true; if ((parts.size() >= 7)) { if (parts[5] == "true") noclip = true; if (parts[6] == "false") drawborder = false; } std::string pressed_image_name = ""; if ((parts.size() == 8)) { pressed_image_name = parts[7]; } core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); if(data->bp_set != 2) errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl; image_name = unescape_string(image_name); pressed_image_name = unescape_string(pressed_image_name); label = unescape_string(label); std::wstring wlabel = narrow_to_wide(label.c_str()); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), wlabel, narrow_to_wide(image_name.c_str()), 258+m_fields.size() ); spec.ftype = f_Button; if(type == "image_button_exit") spec.is_exit = true; video::ITexture *texture = 0; video::ITexture *pressed_texture = 0; texture = m_tsrc->getTexture(image_name); if (parts.size() == 8) pressed_texture = m_tsrc->getTexture(pressed_image_name); else pressed_texture = texture; gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setUseAlphaChannel(true); e->setImage(texture); e->setPressedImage(pressed_texture); e->setScaleImage(true); e->setNotClipped(noclip); e->setDrawBorder(drawborder); m_fields.push_back(spec); return; } errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 4) || (parts.size() == 6)) { std::vector<std::string> v_pos = split(parts[0],','); std::string name = parts[1]; std::vector<std::string> buttons = split(parts[2],','); std::string str_index = parts[3]; bool show_background = true; bool show_border = true; int tab_index = stoi(str_index) -1; MY_CHECKPOS("tabheader",0); if (parts.size() == 6) { if (parts[4] == "true") show_background = false; if (parts[5] == "false") show_border = false; } FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), L"", L"", 258+m_fields.size() ); spec.ftype = f_TabHeader; v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = data->screensize.Y; geom.Y = 30; core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); gui::IGUITabControl *e = Environment->addTabControl(rect,this,show_background,show_border,spec.fid); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setNotClipped(true); for (unsigned int i=0; i< buttons.size(); i++) { wchar_t* wbutton = 0; std::wstring wlabel = narrow_to_wide(buttons[i]); //Needed for displaying text on windows wbutton = (wchar_t*) wlabel.c_str(); e->addTab(wbutton,-1); } if ((tab_index >= 0) && (buttons.size() < INT_MAX) && (tab_index < (int) buttons.size())) e->setActiveTab(tab_index); m_fields.push_back(spec); return; } errorstream<< "Invalid TabHeader element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element) { if (m_gamedef == 0) { errorstream<<"WARNING: invalid use of item_image_button with m_gamedef==0"<<std::endl; return; } std::vector<std::string> parts = split(element,';'); if (parts.size() == 5) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); std::string item_name = parts[2]; std::string name = parts[3]; std::string label = parts[4]; MY_CHECKPOS("itemimagebutton",0); MY_CHECKGEOM("itemimagebutton",1); v2s32 pos = padding; pos.X += stof(v_pos[0]) * (float)spacing.X; pos.Y += stof(v_pos[1]) * (float)spacing.Y; v2s32 geom; geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X); geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y); core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y); if(data->bp_set != 2) errorstream<<"WARNING: invalid use of item_image_button without a size[] element"<<std::endl; IItemDefManager *idef = m_gamedef->idef(); ItemStack item; item.deSerialize(item_name, idef); video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef); std::string tooltip = item.getDefinition(idef).description; label = unescape_string(label); FieldSpec spec = FieldSpec( narrow_to_wide(name.c_str()), narrow_to_wide(label.c_str()), narrow_to_wide(item_name.c_str()), 258+m_fields.size() ); gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str()); if (spec.fname == data->focused_fieldname) { Environment->setFocus(e); } e->setUseAlphaChannel(true); e->setImage(texture); e->setPressedImage(texture); e->setScaleImage(true); spec.ftype = f_Button; rect+=data->basepos-padding; spec.rect=rect; if (tooltip!="") spec.tooltip=tooltip; m_fields.push_back(spec); return; } errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseBox(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if (parts.size() == 3) { std::vector<std::string> v_pos = split(parts[0],','); std::vector<std::string> v_geom = split(parts[1],','); MY_CHECKPOS("box",0); MY_CHECKGEOM("box",1); v2s32 pos = padding + AbsoluteRect.UpperLeftCorner; pos.X += stof(v_pos[0]) * (float) spacing.X; pos.Y += stof(v_pos[1]) * (float) spacing.Y; v2s32 geom; geom.X = stof(v_geom[0]) * (float)spacing.X; geom.Y = stof(v_geom[1]) * (float)spacing.Y; video::SColor tmp_color; if (parseColor(parts[2], tmp_color, false)) { BoxDrawSpec spec(pos, geom, tmp_color); m_boxes.push_back(spec); } else { errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "' INVALID COLOR" << std::endl; } return; } errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 1) || (parts.size() == 2)) { parseColor(parts[0],m_bgcolor,false); if (parts.size() == 2) { std::string fullscreen = parts[1]; m_bgfullscreen = is_yes(fullscreen); } return; } errorstream<< "Invalid bgcolor element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseListColors(parserData* data,std::string element) { std::vector<std::string> parts = split(element,';'); if ((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) { parseColor(parts[0], m_slotbg_n, false); parseColor(parts[1], m_slotbg_h, false); if (parts.size() >= 3) { if (parseColor(parts[2], m_slotbordercolor, false)) { m_slotborder = true; } } if (parts.size() == 5) { video::SColor tmp_color; if (parseColor(parts[3], tmp_color, false)) m_tooltip_element->setBackgroundColor(tmp_color); if (parseColor(parts[4], tmp_color, false)) m_tooltip_element->setOverrideColor(tmp_color); } return; } errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl; } void GUIFormSpecMenu::parseElement(parserData* data,std::string element) { //some prechecks if (element == "") return; std::vector<std::string> parts = split(element,'['); // ugly workaround to keep compatibility if (parts.size() > 2) { if (trim(parts[0]) == "image") { for (unsigned int i=2;i< parts.size(); i++) { parts[1] += "[" + parts[i]; } } else { return; } } if (parts.size() < 2) { return; } std::string type = trim(parts[0]); std::string description = trim(parts[1]); if (type == "size") { parseSize(data,description); return; } if (type == "invsize") { log_deprecated("Deprecated formspec element \"invsize\" is used"); parseSize(data,description); return; } if (type == "list") { parseList(data,description); return; } if (type == "checkbox") { parseCheckbox(data,description); return; } if (type == "image") { parseImage(data,description); return; } if (type == "item_image") { parseItemImage(data,description); return; } if ((type == "button") || (type == "button_exit")) { parseButton(data,description,type); return; } if (type == "background") { parseBackground(data,description); return; } if (type == "tableoptions"){ parseTableOptions(data,description); return; } if (type == "tablecolumns"){ parseTableColumns(data,description); return; } if (type == "table"){ parseTable(data,description); return; } if (type == "textlist"){ parseTextList(data,description); return; } if (type == "dropdown"){ parseDropDown(data,description); return; } if (type == "pwdfield") { parsePwdField(data,description); return; } if ((type == "field") || (type == "textarea")){ parseField(data,description,type); return; } if (type == "label") { parseLabel(data,description); return; } if (type == "vertlabel") { parseVertLabel(data,description); return; } if (type == "item_image_button") { parseItemImageButton(data,description); return; } if ((type == "image_button") || (type == "image_button_exit")) { parseImageButton(data,description,type); return; } if (type == "tabheader") { parseTabHeader(data,description); return; } if (type == "box") { parseBox(data,description); return; } if (type == "bgcolor") { parseBackgroundColor(data,description); return; } if (type == "listcolors") { parseListColors(data,description); return; } // Ignore others infostream << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\"" <<std::endl; } void GUIFormSpecMenu::regenerateGui(v2u32 screensize) { parserData mydata; //preserve tables for (u32 i = 0; i < m_tables.size(); ++i) { std::wstring tablename = m_tables[i].first.fname; GUITable *table = m_tables[i].second; mydata.table_dyndata[tablename] = table->getDynamicData(); } //preserve focus gui::IGUIElement *focused_element = Environment->getFocus(); if (focused_element && focused_element->getParent() == this) { s32 focused_id = focused_element->getID(); if (focused_id > 257) { for (u32 i=0; i<m_fields.size(); i++) { if (m_fields[i].fid == focused_id) { mydata.focused_fieldname = m_fields[i].fname; break; } } } } // Remove children removeChildren(); mydata.size= v2s32(100,100); mydata.helptext_h = 15; mydata.screensize = screensize; // Base position of contents of form mydata.basepos = getBasePos(); // State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element // Used to adjust form size automatically if needed // A proceed button is added if there is no size[] element mydata.bp_set = 0; /* Convert m_init_draw_spec to m_inventorylists */ m_inventorylists.clear(); m_images.clear(); m_backgrounds.clear(); m_itemimages.clear(); m_tables.clear(); m_checkboxes.clear(); m_fields.clear(); m_boxes.clear(); // Set default values (fits old formspec values) m_bgcolor = video::SColor(140,0,0,0); m_bgfullscreen = false; m_slotbg_n = video::SColor(255,128,128,128); m_slotbg_h = video::SColor(255,192,192,192); m_slotbordercolor = video::SColor(200,0,0,0); m_slotborder = false; m_clipbackground = false; // Add tooltip { // Note: parent != this so that the tooltip isn't clipped by the menu rectangle m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18)); m_tooltip_element->enableOverrideColor(true); m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60)); m_tooltip_element->setDrawBackground(true); m_tooltip_element->setDrawBorder(true); m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255)); m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER); m_tooltip_element->setWordWrap(false); //we're not parent so no autograb for this one! m_tooltip_element->grab(); } std::vector<std::string> elements = split(m_formspec_string,']'); for (unsigned int i=0;i< elements.size();i++) { parseElement(&mydata,elements[i]); } // If there's fields, add a Proceed button if (m_fields.size() && mydata.bp_set != 2) { // if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields mydata.rect = core::rect<s32>( mydata.screensize.X/2 - 580/2, mydata.screensize.Y/2 - 300/2, mydata.screensize.X/2 + 580/2, mydata.screensize.Y/2 + 240/2+(m_fields.size()*60) ); DesiredRect = mydata.rect; recalculateAbsolutePosition(false); mydata.basepos = getBasePos(); { v2s32 pos = mydata.basepos; pos.Y = ((m_fields.size()+2)*60); v2s32 size = DesiredRect.getSize(); mydata.rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y+30); wchar_t* text = wgettext("Proceed"); Environment->addButton(mydata.rect, this, 257, text); delete[] text; } } //set initial focus if parser didn't set it focused_element = Environment->getFocus(); if (!focused_element || !isMyChild(focused_element) || focused_element->getType() == gui::EGUIET_TAB_CONTROL) setInitialFocus(); } GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const { core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); for(u32 i=0; i<m_inventorylists.size(); i++) { const ListDrawSpec &s = m_inventorylists[i]; for(s32 i=0; i<s.geom.X*s.geom.Y; i++) { s32 item_i = i + s.start_item_i; s32 x = (i%s.geom.X) * spacing.X; s32 y = (i/s.geom.X) * spacing.Y; v2s32 p0(x,y); core::rect<s32> rect = imgrect + s.pos + p0; if(rect.isPointInside(p)) { return ItemSpec(s.inventoryloc, s.listname, item_i); } } } return ItemSpec(InventoryLocation(), "", -1); } void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase) { video::IVideoDriver* driver = Environment->getVideoDriver(); // Get font gui::IGUIFont *font = NULL; gui::IGUISkin* skin = Environment->getSkin(); if (skin) font = skin->getFont(); Inventory *inv = m_invmgr->getInventory(s.inventoryloc); if(!inv){ infostream<<"GUIFormSpecMenu::drawList(): WARNING: " <<"The inventory location " <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist" <<std::endl; return; } InventoryList *ilist = inv->getList(s.listname); if(!ilist){ infostream<<"GUIFormSpecMenu::drawList(): WARNING: " <<"The inventory list \""<<s.listname<<"\" @ \"" <<s.inventoryloc.dump()<<"\" doesn't exist" <<std::endl; return; } core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); for(s32 i=0; i<s.geom.X*s.geom.Y; i++) { s32 item_i = i + s.start_item_i; if(item_i >= (s32) ilist->getSize()) break; s32 x = (i%s.geom.X) * spacing.X; s32 y = (i/s.geom.X) * spacing.Y; v2s32 p(x,y); core::rect<s32> rect = imgrect + s.pos + p; ItemStack item; if(ilist) item = ilist->getItem(item_i); bool selected = m_selected_item && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv && m_selected_item->listname == s.listname && m_selected_item->i == item_i; bool hovering = rect.isPointInside(m_pointer); if(phase == 0) { if(hovering) driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect); else driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect); } //Draw inv slot borders if (m_slotborder) { s32 x1 = rect.UpperLeftCorner.X; s32 y1 = rect.UpperLeftCorner.Y; s32 x2 = rect.LowerRightCorner.X; s32 y2 = rect.LowerRightCorner.Y; s32 border = 1; driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x1 - border, y1 - border), v2s32(x2 + border, y1)), NULL); driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x1 - border, y2), v2s32(x2 + border, y2 + border)), NULL); driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x1 - border, y1), v2s32(x1, y2)), NULL); driver->draw2DRectangle(m_slotbordercolor, core::rect<s32>(v2s32(x2, y1), v2s32(x2 + border, y2)), NULL); } if(phase == 1) { // Draw item stack if(selected) { item.takeItem(m_selected_amount); } if(!item.empty()) { drawItemStack(driver, font, item, rect, &AbsoluteClippingRect, m_gamedef); } // Draw tooltip std::string tooltip_text = ""; if(hovering && !m_selected_item) tooltip_text = item.getDefinition(m_gamedef->idef()).description; if(tooltip_text != "") { m_tooltip_element->setVisible(true); this->bringToFront(m_tooltip_element); m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str()); s32 tooltip_x = m_pointer.X + 15; s32 tooltip_y = m_pointer.Y + 15; s32 tooltip_width = m_tooltip_element->getTextWidth() + 15; s32 tooltip_height = m_tooltip_element->getTextHeight() + 5; m_tooltip_element->setRelativePosition(core::rect<s32>( core::position2d<s32>(tooltip_x, tooltip_y), core::dimension2d<s32>(tooltip_width, tooltip_height))); } } } } void GUIFormSpecMenu::drawSelectedItem() { if(!m_selected_item) return; video::IVideoDriver* driver = Environment->getVideoDriver(); // Get font gui::IGUIFont *font = NULL; gui::IGUISkin* skin = Environment->getSkin(); if (skin) font = skin->getFont(); Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc); assert(inv); InventoryList *list = inv->getList(m_selected_item->listname); assert(list); ItemStack stack = list->getItem(m_selected_item->i); stack.count = m_selected_amount; core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y); core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter()); drawItemStack(driver, font, stack, rect, NULL, m_gamedef); } void GUIFormSpecMenu::drawMenu() { if(m_form_src){ std::string newform = m_form_src->getForm(); if(newform != m_formspec_string){ m_formspec_string = newform; regenerateGui(m_screensize_old); } } m_pointer = m_device->getCursorControl()->getPosition(); updateSelectedItem(); gui::IGUISkin* skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver* driver = Environment->getVideoDriver(); v2u32 screenSize = driver->getScreenSize(); core::rect<s32> allbg(0, 0, screenSize.X , screenSize.Y); if (m_bgfullscreen) driver->draw2DRectangle(m_bgcolor, allbg, &allbg); else driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect); m_tooltip_element->setVisible(false); /* Draw backgrounds */ for(u32 i=0; i<m_backgrounds.size(); i++) { const ImageDrawSpec &spec = m_backgrounds[i]; video::ITexture *texture = m_tsrc->getTexture(spec.name); if (texture != 0) { // Image size on screen core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y); // Image rectangle on screen core::rect<s32> rect = imgrect + spec.pos; if (m_clipbackground) { core::dimension2d<s32> absrec_size = AbsoluteRect.getSize(); rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X, AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y, AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X, AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y); } const video::SColor color(255,255,255,255); const video::SColor colors[] = {color,color,color,color}; driver->draw2DImage(texture, rect, core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(texture->getOriginalSize())), NULL/*&AbsoluteClippingRect*/, colors, true); } else { errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl; errorstream << "\t" << spec.name << std::endl; } } /* Draw Boxes */ for(u32 i=0; i<m_boxes.size(); i++) { const BoxDrawSpec &spec = m_boxes[i]; irr::video::SColor todraw = spec.color; todraw.setAlpha(140); core::rect<s32> rect(spec.pos.X,spec.pos.Y, spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y); driver->draw2DRectangle(todraw, rect, 0); } /* Draw images */ for(u32 i=0; i<m_images.size(); i++) { const ImageDrawSpec &spec = m_images[i]; video::ITexture *texture = m_tsrc->getTexture(spec.name); if (texture != 0) { const core::dimension2d<u32>& img_origsize = texture->getOriginalSize(); // Image size on screen core::rect<s32> imgrect; if (spec.scale) imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y); else { imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height); } // Image rectangle on screen core::rect<s32> rect = imgrect + spec.pos; const video::SColor color(255,255,255,255); const video::SColor colors[] = {color,color,color,color}; driver->draw2DImage(texture, rect, core::rect<s32>(core::position2d<s32>(0,0),img_origsize), NULL/*&AbsoluteClippingRect*/, colors, true); } else { errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl; errorstream << "\t" << spec.name << std::endl; } } /* Draw item images */ for(u32 i=0; i<m_itemimages.size(); i++) { if (m_gamedef == 0) break; const ImageDrawSpec &spec = m_itemimages[i]; IItemDefManager *idef = m_gamedef->idef(); ItemStack item; item.deSerialize(spec.name, idef); video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef); // Image size on screen core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y); // Image rectangle on screen core::rect<s32> rect = imgrect + spec.pos; const video::SColor color(255,255,255,255); const video::SColor colors[] = {color,color,color,color}; driver->draw2DImage(texture, rect, core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(texture->getOriginalSize())), NULL/*&AbsoluteClippingRect*/, colors, true); } /* Draw items Phase 0: Item slot rectangles Phase 1: Item images; prepare tooltip */ int start_phase=0; for(int phase=start_phase; phase<=1; phase++) for(u32 i=0; i<m_inventorylists.size(); i++) { drawList(m_inventorylists[i], phase); } /* Call base class */ gui::IGUIElement::draw(); /* Draw fields/buttons tooltips */ for(u32 i=0; i<m_fields.size(); i++) { const FieldSpec &spec = m_fields[i]; if (spec.tooltip != "") { core::rect<s32> rect = spec.rect; if (rect.isPointInside(m_pointer)) { m_tooltip_element->setVisible(true); this->bringToFront(m_tooltip_element); m_tooltip_element->setText(narrow_to_wide(spec.tooltip).c_str()); s32 tooltip_x = m_pointer.X + 15; s32 tooltip_y = m_pointer.Y + 15; s32 tooltip_width = m_tooltip_element->getTextWidth() + 15; s32 tooltip_height = m_tooltip_element->getTextHeight() + 5; m_tooltip_element->setRelativePosition(core::rect<s32>( core::position2d<s32>(tooltip_x, tooltip_y), core::dimension2d<s32>(tooltip_width, tooltip_height))); } } } /* Draw dragged item stack */ drawSelectedItem(); } void GUIFormSpecMenu::updateSelectedItem() { // If the selected stack has become empty for some reason, deselect it. // If the selected stack has become inaccessible, deselect it. // If the selected stack has become smaller, adjust m_selected_amount. ItemStack selected = verifySelectedItem(); // WARNING: BLACK MAGIC // See if there is a stack suited for our current guess. // If such stack does not exist, clear the guess. if(m_selected_content_guess.name != "" && selected.name == m_selected_content_guess.name && selected.count == m_selected_content_guess.count){ // Selected item fits the guess. Skip the black magic. } else if(m_selected_content_guess.name != ""){ bool found = false; for(u32 i=0; i<m_inventorylists.size() && !found; i++){ const ListDrawSpec &s = m_inventorylists[i]; Inventory *inv = m_invmgr->getInventory(s.inventoryloc); if(!inv) continue; InventoryList *list = inv->getList(s.listname); if(!list) continue; for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){ u32 item_i = i + s.start_item_i; if(item_i >= list->getSize()) continue; ItemStack stack = list->getItem(item_i); if(stack.name == m_selected_content_guess.name && stack.count == m_selected_content_guess.count){ found = true; infostream<<"Client: Changing selected content guess to " <<s.inventoryloc.dump()<<" "<<s.listname <<" "<<item_i<<std::endl; delete m_selected_item; m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i); m_selected_amount = stack.count; } } } if(!found){ infostream<<"Client: Discarding selected content guess: " <<m_selected_content_guess.getItemString()<<std::endl; m_selected_content_guess.name = ""; } } // If craftresult is nonempty and nothing else is selected, select it now. if(!m_selected_item) { for(u32 i=0; i<m_inventorylists.size(); i++) { const ListDrawSpec &s = m_inventorylists[i]; if(s.listname == "craftpreview") { Inventory *inv = m_invmgr->getInventory(s.inventoryloc); InventoryList *list = inv->getList("craftresult"); if(list && list->getSize() >= 1 && !list->getItem(0).empty()) { m_selected_item = new ItemSpec; m_selected_item->inventoryloc = s.inventoryloc; m_selected_item->listname = "craftresult"; m_selected_item->i = 0; m_selected_amount = 0; m_selected_dragging = false; break; } } } } // If craftresult is selected, keep the whole stack selected if(m_selected_item && m_selected_item->listname == "craftresult") { m_selected_amount = verifySelectedItem().count; } } ItemStack GUIFormSpecMenu::verifySelectedItem() { // If the selected stack has become empty for some reason, deselect it. // If the selected stack has become inaccessible, deselect it. // If the selected stack has become smaller, adjust m_selected_amount. // Return the selected stack. if(m_selected_item) { if(m_selected_item->isValid()) { Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc); if(inv) { InventoryList *list = inv->getList(m_selected_item->listname);