summaryrefslogtreecommitdiff
path: root/iup/srclua5/iuplua.c
blob: 240d599fe41a344e122155b6495363c0a1477d3e (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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
/** \file
* \brief IUP binding for Lua 5.
*
* See Copyright Notice in "iup.h"
*/

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

#include "iup.h"
#include "iup_str.h"

#include <lua.h>
#include <lauxlib.h>

#include "iuplua.h"
#include "il.h"


/*****************************************************************************
* Auxiliary functions                                                       *
****************************************************************************/


             /*************************************/
             /* iuplua_dostring and iuplua_dofile */

/* report, traceback and docall were adapted from "lua.c" */

static void error_message(lua_State *L, const char *msg, const char* traceback)
{
  lua_getglobal(L, "iup");
  lua_pushstring(L, "_ERRORMESSAGE");
  lua_gettable(L, -2);
  lua_remove(L, -2);  /* remove "iup" from stack */

  if(lua_isnil(L, -1))
  {
    /* Panic mode */
    if (traceback != NULL)
      fprintf(stderr, "%s\n%s\n", msg, traceback);
    else
      fprintf(stderr, "%s\n", msg);
    fflush(stderr);
    return;
  }

  lua_pushstring(L, msg);
  lua_pushstring(L, traceback);
  lua_call(L, 2, 0);  /* iup._ERRORMESSAGE(msg, traceback) */
}

static int report (lua_State *L, int status, int concat_traceback)
{
  if (status != LUA_OK && !lua_isnil(L, -1)) 
  {
    const char *msg = lua_tostring(L, -2);

    const char *traceback;
    if (msg == NULL) {
      msg = "(error with no message)";
      traceback = NULL;
    }
    else if (concat_traceback) {
      lua_concat(L, 2);
      msg = lua_tostring(L, -1);
      traceback = NULL;
    }
    else {
      traceback = lua_tostring(L, -1);
    }
    error_message(L, msg, traceback);
    lua_pop(L, 2);  /* remove msg and traceback from stack */
  }
  return status;
}

static int traceback (lua_State *L) 
{
  lua_getglobal(L, "debug");
  if (!lua_istable(L, -1)) {
    lua_pop(L, 1);
    return 1;
  }
  lua_getfield(L, -1, "traceback");
  if (!lua_isfunction(L, -1)) {
    lua_pop(L, 2);
    return 1;
  }

  lua_remove(L, 2);
  lua_pushliteral(L, "");
  lua_pushinteger(L, 2);  /* skip this function */
  lua_call(L, 2, 1);  /* call debug.traceback */

  lua_getglobal(L, "iup"); /* store traceback in iup._LASTTRACEBACK */
  lua_pushstring(L, "_LASTTRACEBACK");
  lua_pushvalue(L, -3);
  lua_settable(L, -3);

  lua_pop(L, 2);  /* remove "iup" and "iup._LASTTRACEBACK" from stack */
  return 1;
}

static int docall (lua_State *L, int narg, int nret) 
{
  int status;
  int base = lua_gettop(L) - narg;  /* function index */
  lua_pushcfunction(L, traceback);  /* push traceback function */
  lua_insert(L, base);  /* put it under chunk and args */
  status = lua_pcall(L, narg, nret, base);
  lua_remove(L, base);  /* remove traceback function */
  if (status != LUA_OK) 
  {
    /* force a complete garbage collection in case of errors */
    lua_gc(L, LUA_GCCOLLECT, 0);

    /* put _LASTTRACEBACK at stack position 2 */
    lua_getglobal(L, "iup");
    lua_pushliteral(L, "_LASTTRACEBACK");
    lua_gettable(L, -2);
    lua_remove(L, -2);  /* remove "iup" from stack */

    if (!lua_isstring(L, -1)) 
    {
      lua_pop(L, 1);
      lua_pushliteral(L, "");

      /* set _LASTTRACEBACK as nil */
      lua_getglobal(L, "iup");
      lua_pushliteral(L, "_LASTTRACEBACK");
      lua_pushnil(L);
      lua_settable(L, -3);

      lua_pop(L, 1);  /* remove "iup" from stack */
    }
  }
  return status;
}

int iuplua_dofile(lua_State *L, const char *filename)
{
  int status = luaL_loadfile(L, filename);
  if (status == LUA_OK)
    status = docall(L, 0, 0);
  else if (status == LUA_ERRFILE)
  {
    char *dir = getenv("IUPLUA_DIR");
    if (dir)
    {
      char* full_name = iupStrFileMakeFileName(dir, filename);
      if (full_name)
      {
        /* remove the error string from the stack, and try again */
        lua_remove(L, -1);

        status = luaL_loadfile(L, full_name);
        free(full_name);
        if (status == LUA_OK)
          status = docall(L, 0, 0);
      }
    }
  }
  return report(L, status, 1);
}

int iuplua_dostring(lua_State *L, const char *s, const char *name)
{
  int status = luaL_loadbuffer(L, s, strlen(s), name);
  if (status == LUA_OK)
    status = docall(L, 0, 0);
  return report(L, status, 1);
}

             /*************************************/
             /*              Utilities        */

Ihandle *iuplua_checkihandleornil(lua_State *L, int pos)
{
  if (lua_isnil(L, pos))
    return NULL;
  else
    return iuplua_checkihandle(L, pos);
}

Ihandle *iuplua_checkihandle(lua_State *L, int pos)
{
  lua_getmetatable(L, pos);   /* t2 = metatable(stack(pos)) */
  lua_pushstring(L, "iup handle");
  lua_gettable(L, LUA_REGISTRYINDEX);  /* t = registry["iup handle"] */
  if (lua_rawequal(L, -2, -1))   /* check (t2==t)? */
  {
    lua_pop (L, 2);
    return *(Ihandle**)lua_touserdata(L, pos);
  } 
  else 
  {
    luaL_argerror(L, pos, "iup handle expected");
    return NULL;
  }
}

void iuplua_pushihandle_raw(lua_State *L, Ihandle *ih)
{
  if (ih) 
  {
    Ihandle** new_pointer = (Ihandle**)lua_newuserdata(L, sizeof(Ihandle*));
    *new_pointer = ih;
  } 
  else 
    lua_pushnil(L);
}

void iuplua_pushihandle(lua_State *L, Ihandle *ih)
{
  if (ih) 
  {
    /* not created in Lua? */
    char* sref = IupGetAttribute(ih, "_IUPLUA_WIDGET_TABLE_REF");
    if (!sref)
    {
      lua_getglobal(L, "iup");
      lua_pushstring(L,"RegisterHandle");
      lua_gettable(L, -2);
      lua_remove(L, -2);  /* remove "iup" from stack */

      iuplua_pushihandle_raw(L, ih);
      lua_pushstring(L, IupGetClassName(ih));
      lua_call(L, 2, 1);  /* iup.RegisterHandle(ih, type) */
    }
    else
    {
      iuplua_pushihandle_raw(L, ih);
      lua_pushstring(L, "iup handle");
      lua_gettable(L, LUA_REGISTRYINDEX);  /* t = registry["iup handle"] */
      lua_setmetatable(L, -2);    /* metatable(ih) = t */
    }
  } 
  else 
    lua_pushnil(L);
}

void iuplua_removeihandle(lua_State *L, Ihandle *ih)
{
  char* sref;

  /* called from Destroy.
     must also remove references from the children. */
  Ihandle* child = IupGetNextChild(ih, NULL);
  while(child)
  {
    iuplua_removeihandle(L, child);
    child = IupGetNextChild(ih, child);
  }

  sref = IupGetAttribute(ih, "_IUPLUA_WIDGET_TABLE_REF");
  if (sref)
  {
    int ref = atoi(sref);

    /* removes the ihandle reference in the lua table */
    /* object.handle = nil */
    lua_getref(L, ref);  /* push object */
    lua_pushstring(L, "handle");
    lua_pushnil(L);
    lua_settable(L, -3);
    lua_pop(L,1);

    /* removes the association of the ihandle with the lua table */
    lua_unref(L, ref);  /* this is the complement of SetWidget */
    IupSetAttribute(ih, "_IUPLUA_WIDGET_TABLE_REF", NULL);
  }
}

char ** iuplua_checkstring_array(lua_State *L, int pos)
{
  int i,n;
  char **v;
  n = iuplua_getn(L,pos);
  v = (char **) malloc (n*sizeof(char *));
  for(i=1; i<=n; i++)
  {
    lua_pushinteger(L,i);
    lua_gettable(L,pos);
    v[i-1] = (char*)lua_tostring(L, -1);
    lua_pop(L,1);
  }
  return v;
}

int * iuplua_checkint_array(lua_State *L, int pos)
{
  int i,n;
  int *v;
  n = iuplua_getn(L,pos);
  v = (int *) malloc (n*sizeof(int));
  for(i=1; i<=n; i++)
  {
    lua_pushinteger(L,i);
    lua_gettable(L,pos);
    v[i-1] = lua_tointeger(L, -1);
    lua_pop(L,1);
  }
  return v;
}

unsigned char* iuplua_checkuchar_array(lua_State *L, int pos, int count)
{
  int i,n;
  unsigned char *v;
  n = iuplua_getn(L,pos);
  if (n != count)
  {
    lua_pushstring(L, "invalid number of elements in array");
    lua_error(L);
  }
  v = (unsigned char *) malloc (n*sizeof(unsigned char));
  for(i=1; i<=n; i++)
  {
    lua_pushinteger(L,i);
    lua_gettable(L,pos);
    v[i-1] = (unsigned char)lua_tointeger(L, -1);
    lua_pop(L,1);
  }
  return v;
}

Ihandle ** iuplua_checkihandle_array(lua_State *L, int pos)
{
  Ihandle **v;
  int i, n = iuplua_getn(L, pos);
  v = (Ihandle **) malloc ((n+1)*sizeof(Ihandle *));
  for (i=1; i<=n; i++)
  {
    lua_pushinteger(L,i);
    lua_gettable(L,pos);
    v[i-1] = iuplua_checkihandle(L, -1);
    lua_pop(L,1);
  }
  v[i-1] = NULL;
  return v;
}

             /*************************************/
             /*         used by callbacks         */

void iuplua_plugstate(lua_State *L, Ihandle *ih)
{
  IupSetAttribute(ih, "_IUPLUA_STATE_CONTEXT",(char *) L);
}

lua_State* iuplua_getstate(Ihandle *ih)
{
  return (lua_State *) IupGetAttribute(ih, "_IUPLUA_STATE_CONTEXT");
}

lua_State* iuplua_call_start(Ihandle *ih, const char* name)
{
  lua_State *L = iuplua_getstate(ih);

  /* prepare to call iup.CallMethod(name, handle, ...) */
  lua_getglobal(L, "iup");
  lua_pushstring(L,"CallMethod");
  lua_gettable(L, -2);
  lua_remove(L, -2);  /* remove "iup" from stack */

  lua_pushstring(L, name);
  iuplua_pushihandle(L, ih);
  return L;
}

int iuplua_call(lua_State* L, int nargs)
{
  int status = docall(L, nargs+2, 1);
  report(L, status, 0);

  if (status != LUA_OK)
    return IUP_DEFAULT;
  else
  {
    int tmp = (int) lua_isnil(L, -1) ? IUP_DEFAULT : (int)lua_tonumber(L,-1);
    lua_pop(L, 1);
    return tmp;    
  }
}

char* iuplua_call_rs(lua_State *L, int nargs)
{
  int status = docall(L, nargs+2, 1);
  report(L, status, 0);

  if (status != LUA_OK)
    return NULL;
  else
  {
    char* tmp = lua_isnil(L, -1) ? NULL: (char*)lua_tostring(L,-1);
    lua_pop(L, 1);
    return tmp;    
  }
}

int iuplua_call_raw(lua_State* L, int nargs, int nresults)
{
  int status = docall(L, nargs, nresults);
  report(L, status, 0);
  return status;
}

void iuplua_register_cb(lua_State *L, const char* name, lua_CFunction func, const char* type)
{
  lua_getglobal(L, "iup");
  lua_pushstring(L,"RegisterCallback");
  lua_gettable(L, -2);
  lua_remove(L, -2);  /* remove "iup" from stack */

  lua_pushstring(L, name);
  lua_pushcfunction(L, func);
  lua_pushstring(L, type);
  lua_call(L, 3, 0);  /* iup.RegisterCallback(name, func, type) */
}

/* iup.SetCallback(handle, name, func, value) */
static int SetCallback(lua_State *L)
{
  Icallback func;

  Ihandle* ih = iuplua_checkihandle(L, 1);
  const char* name = luaL_checkstring(L, 2);

  if (!lua_iscfunction(L, 3))
  {
    lua_pushstring(L, "invalid function when set callback");
    lua_error(L);
  }
  func = (Icallback)lua_tocfunction(L, 3);

  if (lua_isnil(L, 4))  /* value is only used here to remove the callback */
    IupSetCallback(ih, name, (Icallback)NULL);
  else
    IupSetCallback(ih, name, func);

  /* value, when not nil, is always the same name of a C callback in lowercase */

  return 0;
}

             /*************************************/
             /*        metatable                  */

/* iup.NewClass(class_name) 
  Calls:
    iup.NewClass("iup handle")
    iup.NewClass("iup widget")
*/
static int NewClass(lua_State *L)
{
  lua_newtable(L);     /* push t */
  lua_pushstring(L, "class");  /* push "class" */
  lua_pushvalue(L, 1); /* push again the class_name to the stack, because settable will remove it */
  lua_settable(L, -3); /* t.class = class_name */
  lua_settable(L, LUA_REGISTRYINDEX);  /* registry[class_name] = t */
  return 0;
}

/* iup.SetClass(t, class_name) 
  Calls:
    iup.SetClass(handle, "iup handle")  --Used only in iup.RegisterHandle and WIDGET.constructor
    iup.SetClass(object, "iup widget")  --Used whenever a new control class is created.
*/
static int SetClass(lua_State *L)
{
  lua_gettable(L, LUA_REGISTRYINDEX);  /* t2 = registry[class_name] */
  if (lua_isnil(L, -1))
  {
    lua_pushstring(L, "invalid class name");
    lua_error(L);
  }
  lua_setmetatable(L, -2);  /* metatable(t) = t2 */
  return 0;
}

/* class_name = iup.GetClass(t) */
static int GetClass(lua_State *L)
{
  if (lua_istable(L, 1) || lua_isuserdata(L, 1)) 
  {
    lua_getmetatable(L, 1); /* t2 = metatable(t) */
    if (lua_istable(L, -1)) 
    {
      lua_pushstring(L, "class");
      lua_gettable(L, -2);    /* class_name = t2.class */ 
      return 1;
    }
  }
  lua_pushnil(L);
  return 1;
}

/* iup.SetMethod(class_name, method, function)
   For ex:
     iup.SetMethod("iup handle", "__index", ihandle_gettable)
*/
static int SetMethod(lua_State *L)
{
  lua_pushvalue(L, 1); /* push class_name */
  lua_gettable(L, LUA_REGISTRYINDEX);  /* t = registry[class_name] */
  if (lua_isnil(L, -1)) 
  {
    lua_pushstring(L, "invalid class name");
    lua_error(L);
  }
  lua_pushvalue(L, -3); /* push method */
  lua_pushvalue(L, -3); /* push function */
  lua_settable(L, -3);  /* t.method = function */
  return 0;
}

static int ihandle_tostring (lua_State *L) 
{
  Ihandle *ih = iuplua_checkihandle(L, 1);
  if (!ih)
    lua_pushstring (L, "(not an IUP handle)");
  else
    lua_pushfstring (L, "IUP(%s): %p", IupGetClassName(ih), ih);
  return 1;
}

static int ihandle_compare(lua_State *L)
{
  Ihandle *a = iuplua_checkihandle(L, 1);
  Ihandle *b = iuplua_checkihandle(L, 2);
  if(a == b)
    lua_pushboolean(L, 1);
  else
    lua_pushboolean(L, 0);
  return 1;
}

             /*************************************/
             /*       table <-> ihandle           */

/* local object = iup.GetWidget(handle) */
static int GetWidget(lua_State *L)
{
  /* Pushes a table that is associanted with an ihandle */
  /* Used by the "__index" metamethod of the "iup handle" */
  Ihandle * ih = iuplua_checkihandle(L,1);
  char* sref = IupGetAttribute(ih, "_IUPLUA_WIDGET_TABLE_REF");
  if (!sref)
    lua_pushnil(L);
  else
    lua_getref(L, atoi(sref));
  return 1;
}

/* iup.SetWidget(handle, object) */
static int SetWidget(lua_State *L)
{
  /* Saves the object table reference as an attribute, 
     i.e. associates a table with the ihandle.
     Used by the "iup widget" constructor and by RegisterHandle */
  Ihandle * ih = iuplua_checkihandle(L,1);
  char* sref = IupGetAttribute(ih, "_IUPLUA_WIDGET_TABLE_REF");
  if (!sref)
  {
    int ref = lua_ref(L, 1);
    IupSetfAttribute(ih, "_IUPLUA_WIDGET_TABLE_REF", "%d", ref);  /* this must be a non-inheritable attribute */
  }
  return 0;
}

             /*************************************/
             /*          registration             */

void iuplua_get_env(lua_State *L)
{
  lua_getglobal(L, "iup");
}

int iuplua_opencall_internal(lua_State * L)
{
  int ret = 0;
  const char* s;
  lua_getglobal(L, "iup");
  lua_pushliteral(L,"_IUPOPEN_CALL");
  lua_gettable(L, -2);
  s = lua_tostring(L, -1);
  if (s && strcmp(s, "INTERNAL")==0)
    ret = 1;
  lua_pop(L,2);  /* remove "iup" and "iup._IUPOPEN_CALL" from stack */
  return ret;
}

/* iup[name] = func */ 
void iuplua_register(lua_State *L, lua_CFunction func, const char* name)
{
  lua_pushcfunction(L, func);
  lua_setfield(L, -2, name);
}

/* iup[name] = s */ 
void iuplua_regstring(lua_State *L, const char* s, const char* name)
{
  lua_pushstring(L, s); 
  lua_setfield(L, -2, name);
}

/*****************************************************************************
* Common Callbacks                                                     *
****************************************************************************/

static int help_cb(Ihandle *self)
{
  lua_State *L = iuplua_call_start(self, "help_cb");
  return iuplua_call(L, 0);
}

static int getfocus_cb(Ihandle *self)
{
  lua_State *L = iuplua_call_start(self, "getfocus_cb");
  return iuplua_call(L, 0);
}

static int k_any(Ihandle *self, int c)
{
  lua_State *L = iuplua_call_start(self, "k_any");
  lua_pushinteger(L, c);
  return iuplua_call(L, 1);
}

static int killfocus_cb(Ihandle *self)
{
  lua_State *L = iuplua_call_start(self, "killfocus_cb");
  return iuplua_call(L, 0);
}

static int Idlecall(void)
{
  int ret = 0;
  lua_State *L = (lua_State *) IupGetGlobal("_IUP_LUA_DEFAULT_STATE");
  lua_getglobal(L, "_IUP_LUA_IDLE_FUNC_"); 
  lua_call(L, 0, 1);  /* _IUP_LUA_IDLE_FUNC_() */
  ret = lua_tointeger(L, -1);
  lua_pop(L, 1);
  return ret;
}

static int SetIdle(lua_State *L)
{
  if lua_isnoneornil(L,1)
    IupSetFunction("IDLE_ACTION", NULL);
  else
  {
    luaL_checktype(L, 1, LUA_TFUNCTION);
    lua_pushvalue(L,1);
    lua_setglobal(L, "_IUP_LUA_IDLE_FUNC_");
    IupSetFunction("IDLE_ACTION", (Icallback) Idlecall);
  }
  return 0;
}

/*****************************************************************************
* Iuplua bind functions                                                     *
****************************************************************************/


static int GetFromC(lua_State *L)
{
  Ihandle *n;
  const char *a;
  if (!lua_istable(L, -1)) 
  {
    lua_pushstring(L, "iup.GetFromC: wrong arguments to function"); 
    lua_error(L);
    return 0;
  }
  lua_pushinteger(L, 1);
  lua_gettable(L, -2);
  if (!lua_isstring(L, -1)) 
  {
    lua_pushstring(L, "iup.GetFromC: wrong arguments to function"); 
    lua_error(L);
    return 0;
  }
  a = lua_tostring(L, -1);
  n = IupGetHandle((char*)a);
  if(n)
    iuplua_pushihandle(L, n);
  else
    lua_pushnil(L);
  return 1;
}


/*****************************************************************************
 *   iupkey                                                                  *
 ****************************************************************************/


static void register_key(char *name, int code, void* user_data)
{
  lua_State *L = (lua_State*)user_data;
  lua_pushinteger(L, code); 
  lua_setfield(L, -2, name);
}

/* from iupkey.c */
void iupKeyForEach(void (*func)(char *name, int code, void* user_data), void* user_data);

int iupkey_open(lua_State *L)
{
  (void)L;
  /* does nothing, kept for backward compatibility */
  return 0;
}


/*****************************************************************************
* iuplua_open                                                               *
****************************************************************************/


static int il_open(lua_State * L)
{
  int ret, argc = 0; 
  char **argv = NULL;

  lua_getglobal(L, "arg");
  if (lua_istable(L, -1))
  {
    int i;
    argc = iuplua_getn(L, -1);
    argv = malloc(sizeof(char*)*argc);
    for(i=1; i<=argc; i++)
    {
      lua_pushinteger(L,i);
      lua_gettable(L,-2);
      argv[i-1] = (char*)lua_tostring(L, -1);
      lua_pop(L,1);
    }
  }
  lua_pop(L, 1);

  ret = IupOpen(&argc, &argv);
  if (ret == IUP_ERROR)
  {
    if (argv) free(argv);
    lua_pushstring(L, "IupOpen: could not initialize"); 
    lua_error(L);
    return 0;
  }

  if (argv) free(argv);
  lua_pushinteger(L, ret);
  return 1;
}

int iuplua_close(lua_State * L)
{
  if (iuplua_opencall_internal(L))
    IupClose();
  return 0; /* nothing in stack */
}

static void setinfo (lua_State *L) 
{
  /* table "iup" is at the stack */

  lua_pushliteral (L, IUP_COPYRIGHT);
  lua_setfield(L, -2, "_COPYRIGHT");

  lua_pushliteral (L, IUP_DESCRIPTION);
  lua_setfield(L, -2, "_DESCRIPTION");

  lua_pushliteral (L, IUP_NAME);
  lua_setfield(L, -2, "_NAME");

  lua_pushstring (L, IupVersion());
  lua_setfield(L, -2, "_VERSION");

  lua_pushliteral (L, IUP_VERSION_DATE);
  lua_setfield(L, -2, "_VERSION_DATE");

  lua_pushinteger (L, IupVersionNumber());
  lua_setfield(L, -2, "_VERSION_NUMBER");
}

int iuplua_open(lua_State * L)
{
  int ret;

  struct luaL_reg funcs[] = {
    {"key_open", iupkey_open},
    {"Open", il_open},
    {"Close", iuplua_close},
    {"SetIdle", SetIdle},
    {"GetFromC", GetFromC},
    {"GetWidget", GetWidget},
    {"SetWidget", SetWidget},
    {"NewClass", NewClass},
    {"SetClass", SetClass},
    {"GetClass", GetClass},
    {"SetMethod", SetMethod},
    {"SetCallback", SetCallback},
    {"ihandle_compare", ihandle_compare},
    {"ihandle_tostring", ihandle_tostring},
    {NULL, NULL},
  };

  if (!il_open(L))
    return 0;

  ret = lua_tointeger(L, -1); /* retrieve IupOpen return value */
  lua_pop(L, -1);

  /* Registers functions in iup namespace */
  luaL_register(L, "iup", funcs);  /* leave "iup" table at the top of the stack */
  iupluaapi_open(L);

  /* set version info */
  setinfo(L);

  /* register if IupOpen was called here or from outside IupLua */
  /* iup._IUPOPEN_CALL = EXTERNAL|INTERNAL                      */
  if (ret == IUP_OPENED) lua_pushliteral (L, "EXTERNAL");
  else                   lua_pushliteral (L, "INTERNAL");
  lua_setfield(L, -2, "_IUPOPEN_CALL");

  /* used by Idle in Lua */
  IupSetGlobal("_IUP_LUA_DEFAULT_STATE", (char *) L);  

#include "clua/iuplua.clua"
#include "clua/constants.clua"

  /* Register the common callbacks */
  iuplua_register_cb(L, "HELP_CB", (lua_CFunction)help_cb, NULL);
  iuplua_register_cb(L, "GETFOCUS_CB", (lua_CFunction)getfocus_cb, NULL);
  iuplua_register_cb(L, "K_ANY", (lua_CFunction)k_any, NULL);
  iuplua_register_cb(L, "KILLFOCUS_CB", (lua_CFunction)killfocus_cb, NULL);

  /* Register Keys */
  iupKeyForEach(register_key, (void*)L);

  /* Iup Modules initialization */
  iupbuttonlua_open(L);
  iupcanvaslua_open(L);
  iupdialoglua_open(L);
  iupfilllua_open(L);
  iupframelua_open(L);
  iupfiledlglua_open(L);
  iuphboxlua_open(L);
  iupitemlua_open(L);
  iupimagelua_open(L);
  iuplabellua_open(L);
  iuplistlua_open(L);
  iupmenulua_open(L);
  iupmultilinelua_open(L);
  iupradiolua_open(L);
  iupseparatorlua_open(L);
  iupsubmenulua_open(L);
  iuptextlua_open(L);
  iuptogglelua_open(L);
  iupvboxlua_open(L);
  iupzboxlua_open(L);
  iuptimerlua_open(L);
  iupsboxlua_open(L);
  iupsplitlua_open(L);
  iupspinlua_open(L);
  iupspinboxlua_open(L);
  iupcboxlua_open(L);
  iupgclua_open(L);
  iupgetparamlua_open(L);
  iupvallua_open(L);
  iuptabslua_open(L);
  iupfontdlglua_open(L);
  iupmessagedlglua_open(L);
  iupcolordlglua_open(L);
  iupimagergbalua_open(L);
  iupimagergblua_open(L);
  iupprogressbarlua_open(L);
  iupnormalizerlua_open(L);
  iupuserlua_open(L);
  iuptreelua_open(L);
  iupclipboardlua_open(L);

  return 0; /* nothing in stack */
}

/* obligatory to use require"iuplua" */
int luaopen_iuplua(lua_State* L)
{
  return iuplua_open(L);
}