Fix session-open after selecting new, template, then back
[ardour.git] / tools / luadevel / devel.cc
1 #include <stdint.h>
2 #include <cstdio>
3 #include <iostream>
4 #include <string>
5 #include <list>
6 #include <vector>
7
8 #define LIBPBD_API
9 #include "../../libs/pbd/pbd/reallocpool.h"
10 #include "../../libs/pbd/reallocpool.cc"
11
12 #include <readline/readline.h>
13 #include <readline/history.h>
14
15 #include "lua/luastate.h"
16 #include "LuaBridge/LuaBridge.h"
17
18 static void my_lua_print (std::string s) {
19         std::cout << s << "\n";
20 }
21
22 luabridge::LuaRef::Proxy&
23 luabridge::LuaRef::Proxy::clone_instance (const void* classkey, void* p) {
24   lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_tableRef);
25   lua_rawgeti (m_L, LUA_REGISTRYINDEX, m_keyRef);
26
27         luabridge::UserdataPtr::push_raw (m_L, p, classkey);
28
29   lua_rawset (m_L, -3);
30   lua_pop (m_L, 1);
31   return *this;
32 }
33
34
35
36 class A {
37         public:
38                 A() { printf ("CTOR %p\n", this); _int = 4; for (int i = 0; i < 256; ++i) {arr[i] = i; ar2[i] = i/256.0; ar3[i] = i;} }
39                 ~A() { printf ("DTOR\n"); }
40
41                 void set_int (int a) { _int = a; }
42                 int  get_int () const { return _int; }
43
44                 int& get_ref () { return _int; }
45                 int get_arg (int &a) { printf ("a = %d\n", a);  a = _int; printf ("a = %d\n", a); return 1; }
46                 void get_arg2 (int &a, int& b) {  a = _int; b = 100; }
47                 void get_args (std::string &a) {  a = "hello"; }
48                 void set_ref (int const &a) { _int = a; }
49
50                 float * get_arr () { return arr; }
51                 float * get_ar2 () { return ar2; }
52                 int * get_ar3 () { return ar3; }
53
54                 void set_list (std::list<std::string> sl) { _sl = sl; }
55                 std::list<std::string>& get_list () { return _sl; }
56
57                 uint32_t minone() { return -1; }
58                 void pointer (float*f) const { printf ("PTR %p", f); }
59
60                 enum EN {
61                         RV1 = 1, RV2, RV3
62                 };
63
64                 enum EN ret_enum () { return _en;}
65                 void set_enum (enum EN en) { _en = en; }
66
67         private:
68                 std::list<std::string> _sl;
69                 int _int;
70                 enum EN _en;
71                 float arr[256];
72                 float ar2[256];
73                 int ar3[256];
74 };
75
76
77 class LuaTableRef {
78         public:
79                 LuaTableRef () {}
80                 ~LuaTableRef () {}
81
82                 int get (lua_State* L) {
83                         luabridge::LuaRef rv (luabridge::newTable (L));
84                         for (std::vector<LuaTableEntry>::const_iterator i = _data.begin (); i != _data.end (); ++i) {
85                                 switch ((*i).keytype) {
86                                         case LUA_TSTRING:
87                                                 assign(&rv, i->k_s, *i);
88                                                 break;
89                                         case LUA_TNUMBER:
90                                                 assign(&rv, i->k_n, *i);
91                                                 break;
92                                 }
93                         }
94                         luabridge::push (L, rv);
95                         return 1;
96                 }
97
98                 int set (lua_State* L) {
99                         if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
100                         _data.clear ();
101
102                         lua_pushvalue (L, -1);
103                         lua_pushnil (L);
104                         while (lua_next (L, -2)) {
105                                 lua_pushvalue (L, -2);
106
107                                 LuaTableEntry s (lua_type(L, -1), lua_type(L, -2));
108                                 switch (lua_type(L, -1)) {
109                                         case LUA_TSTRING:
110                                                 s.k_s = luabridge::Stack<std::string>::get (L, -1);
111                                                 break;
112                                                 ;
113                                         case LUA_TNUMBER:
114                                                 s.k_n = luabridge::Stack<unsigned int>::get (L, -1);
115                                                 break;
116                                         default:
117                                                 // invalid key
118                                                 lua_pop (L, 2);
119                                                 continue;
120                                 }
121
122                                 switch(lua_type(L, -2)) {
123                                         case LUA_TSTRING:
124                                                 s.s = luabridge::Stack<std::string>::get (L, -2);
125                                                 break;
126                                         case LUA_TBOOLEAN:
127                                                 s.b = lua_toboolean (L, -2);
128                                                 break;
129                                         case LUA_TNUMBER:
130                                                 s.n = lua_tonumber (L, -2);
131                                                 break;
132                                         case LUA_TUSERDATA:
133                                                 {
134                                                         bool ok = false;
135                                                         lua_getmetatable (L, -2);
136                                                         lua_rawgetp (L, -1, luabridge::getIdentityKey ());
137                                                         if (lua_isboolean (L, -1)) {
138                                                                 lua_pop (L, 1);
139                                                                 const void* key = lua_topointer (L, -1);
140                                                                 lua_pop (L, 1);
141                                                                 void const* classkey = findclasskey (L, key);
142
143                                                                 if (classkey) {
144                                                                         ok = true;
145                                                                         s.c = classkey;
146                                                                         s.p = luabridge::Userdata::get_ptr (L, -2);
147                                                                 }
148                                                         }  else {
149                                                                 lua_pop (L, 2);
150                                                         }
151
152                                                         if (ok) {
153                                                                 break;
154                                                         }
155                                                         // invalid userdata -- fall through
156                                                 }
157                                                 // no break
158                                         case LUA_TFUNCTION: // no support -- we could... string.format("%q", string.dump(value, true))
159                                         case LUA_TTABLE: // no nested tables, sorry.
160                                         case LUA_TNIL: // fallthrough
161                                         default:
162                                                 // invalid value
163                                                 lua_pop (L, 2);
164                                                 continue;
165                                 }
166
167                                 _data.push_back(s);
168                                 lua_pop (L, 2);
169                         }
170                         return 0;
171                 }
172
173                 static void* findclasskey (lua_State *L, const void* key)
174                 {
175                         lua_pushvalue(L, LUA_REGISTRYINDEX);
176                         lua_pushnil (L);
177                         while (lua_next (L, -2)) {
178                                 lua_pushvalue (L, -2);
179                                 if (lua_topointer(L, -2) == key) {
180                                         void* rv = lua_touserdata (L, -1);
181                                         lua_pop (L, 4);
182                                         return rv;
183                                 }
184                                 lua_pop (L, 2);
185                         }
186                         lua_pop (L, 1);
187                         return NULL;
188                 }
189
190         private:
191                 struct LuaTableEntry {
192                         LuaTableEntry (int kt, int vt)
193                                 : keytype (kt)
194                                 , valuetype (vt)
195                         { }
196
197                         int keytype;
198                         std::string k_s;
199                         unsigned int k_n;
200
201                         int valuetype;
202                         // LUA_TUSERDATA
203                         const void* c;
204                         void* p;
205                         // LUA_TBOOLEAN
206                         bool b;
207                         // LUA_TSTRING:
208                         std::string s;
209                         // LUA_TNUMBER:
210                         double n;
211                 };
212
213                 template<typename T>
214                 static void assign (luabridge::LuaRef* rv, T key, const LuaTableEntry& s)
215                 {
216                         switch (s.valuetype) {
217                                 case LUA_TSTRING:
218                                         (*rv)[key] = s.s;
219                                         break;
220                                 case LUA_TBOOLEAN:
221                                         (*rv)[key] = s.b;
222                                         break;
223                                 case LUA_TNUMBER:
224                                         (*rv)[key] = s.n;
225                                         break;
226                                 case LUA_TUSERDATA:
227                                         (*rv)[key].clone_instance (s.c, s.p);
228                                         break;
229                                 default:
230                                         assert (0);
231                                         break;
232                         }
233                 }
234
235                 std::vector<LuaTableEntry> _data;
236 };
237
238
239 #if 0
240 static void* findclasskey (lua_State *L, const void* key)
241 {
242         lua_pushvalue(L, LUA_REGISTRYINDEX);
243         lua_pushnil (L);
244         while (lua_next (L, -2)) {
245                 lua_pushvalue (L, -2);
246                 if (lua_topointer(L, -2) == key) {
247                         void* rv = lua_touserdata (L, -1);
248                         lua_pop (L, 4);
249                         return rv;
250                 }
251                 lua_pop (L, 2);
252         }
253         lua_pop (L, 1);
254         return NULL;
255 }
256
257 static int tableSerialize (lua_State *L)
258 {
259         if (!lua_istable (L, -1)) { return luaL_error (L, "argument is not a table"); }
260
261         luabridge::LuaRef rv (luabridge::newTable (L));
262         std::cout << "CLASS A KEY: " << luabridge::ClassInfo <A>::getClassKey () << "\n";
263         lua_rawgetp (L, LUA_REGISTRYINDEX, luabridge::ClassInfo <A>::getClassKey ());
264         std::cout << " CLASS A TABLE PTR=" << lua_topointer (L, -1) << "\n";
265         lua_pop (L, 1);
266         // for k,v in pairs (debug.getregistry ()) do print (k,v) end
267
268         lua_pushvalue (L, -1);
269         lua_pushnil (L);
270         while (lua_next (L, -2)) {
271                 lua_pushvalue (L, -2);
272                 unsigned int const i = luabridge::Stack<unsigned int>::get (L, -1);
273                 int t = lua_type(L, -2);
274                 switch(t) {
275                         case LUA_TSTRING:
276                                 std::cout << "  " << i << ": '" << lua_tostring(L, -2) << "'\n";
277                                 rv[i] = lua_tostring(L, -2);
278                                 break;
279                         case LUA_TBOOLEAN:
280                                 std::cout << "  " << i << ": " <<
281                                         (lua_toboolean(L, -2) ? "true" : "false") << "\n";
282                                 rv[i] = lua_toboolean(L, -2);
283                                 break;
284                         case LUA_TNUMBER:
285                                 std::cout << "  " << i << ": " << lua_tonumber(L, -2) << "\n";
286                                 rv[i] = lua_tonumber(L, -2);
287                                 break;
288                         case LUA_TUSERDATA:
289                                 {
290                                         lua_getmetatable (L, -2);
291                                         lua_rawgetp (L, -1, luabridge::getIdentityKey ());
292                                         if (lua_isboolean (L, -1)) {
293                                                 lua_pop (L, 1);
294                                                 const void* key = lua_topointer (L, -1);
295                                                 lua_pop (L, 1);
296                                                 void const* classkey = findclasskey (L, key);
297
298                                                 if (classkey) {
299                                                         void* p = luabridge::Userdata::get_ptr (L, -2);
300                                                         rv[i].clone_instance (classkey, p);
301                                                 }
302                                         }  else {
303                                                 lua_pop (L, 2);
304                                         }
305                                 }
306                                 break;
307                         case LUA_TNIL:
308                         case LUA_TTABLE:
309                         case LUA_TFUNCTION:
310                         case LUA_TLIGHTUSERDATA:
311                         default:
312                                 std::cout << "  " << i << ": TYPE=" << t << ": " << lua_topointer(L, -2)<< "\n";
313                                 break;
314                 }
315                 lua_pop (L, 2);
316         }
317         lua_pop (L, 1);
318         lua_pop (L, 2);
319
320         luabridge::push (L, rv);
321         return 1;
322 }
323 #endif
324
325 LuaTableRef globalref;
326
327 int runone (LuaState& lua)
328 {
329 #if 0
330         LuaState lua (*new LuaState);
331 #elif 0
332         PBD::ReallocPool _mempool ("Devel", 1048576);
333         LuaState lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool));
334 #endif
335         lua.Print.connect (&my_lua_print);
336         lua_State* L = lua.getState();
337
338
339 #if 1
340         luabridge::getGlobalNamespace (L)
341                 .beginNamespace ("Test")
342                 .beginStdList <std::string> ("StringList")
343                 .endClass ()
344                 .endNamespace ();
345
346         luabridge::getGlobalNamespace (L)
347                 .beginNamespace ("Test")
348                 .beginStdVector <std::string> ("StringVector")
349                 .endClass ()
350                 .endNamespace ();
351
352         luabridge::getGlobalNamespace (L)
353                 .beginNamespace ("Test")
354                 .beginStdMap <std::string,std::string> ("StringStringMap")
355                 .endClass ()
356                 .endNamespace ();
357
358         luabridge::getGlobalNamespace (L)
359                 .beginNamespace ("Test")
360                 .beginStdSet <std::string> ("StringSet")
361                 .endClass ()
362                 .endNamespace ();
363
364
365         luabridge::getGlobalNamespace (L)
366                 .beginNamespace ("Test")
367                 .registerArray <float> ("FloatArray")
368                 .registerArray <int> ("IntArray")
369                 .beginClass <A> ("A")
370                 .addConstructor <void (*) ()> ()
371                 .addFunction ("set_int", &A::set_int)
372                 .addFunction ("get_int", &A::get_int)
373                 .addRefFunction ("get_arg", &A::get_arg)
374                 .addRefFunction ("get_arg2", &A::get_arg2)
375                 .addRefFunction ("get_args", &A::get_args)
376                 .addFunction ("set_ref", &A::set_ref)
377                 .addFunction ("get_list", &A::get_list)
378                 .addFunction ("set_list", &A::set_list)
379                 .addFunction ("ret_enum", &A::ret_enum)
380                 .addFunction ("set_enum", &A::set_enum)
381                 .addFunction ("get_arr", &A::get_arr)
382                 .addFunction ("get_ar2", &A::get_ar2)
383                 .addFunction ("get_ar3", &A::get_ar3)
384                 .endClass ()
385                 .endNamespace ();
386
387         luabridge::getGlobalNamespace (L)
388                 .beginNamespace ("Test")
389                 .beginClass <A> ("A")
390                 .addFunction ("pointer", &A::pointer)
391                 .addFunction ("minone", &A::minone)
392                 .addConst ("cologne", 4711)
393                 .endClass ()
394                 .addConst ("koln", 4711)
395                 .endNamespace ();
396 #endif
397         luabridge::getGlobalNamespace (L)
398                 .beginNamespace ("Dump")
399
400                 .beginClass <LuaTableRef> ("TableRef")
401                 .addCFunction ("get", &LuaTableRef::get)
402                 .addCFunction ("set", &LuaTableRef::set)
403                 .endClass ()
404
405                 //.addCFunction ("dump", tableSerialize)
406                 .endNamespace ();
407
408         luabridge::push <LuaTableRef *> (L, &globalref);
409         lua_setglobal (L, "ref");
410
411
412 #if 0 // session  script test
413         lua.do_command (
414                         "function ArdourSession ()"
415                         "  local self = { scripts = {}, instances = {} }"
416                         ""
417                         "  local foreach = function (fn)"
418                         "   for n, s in pairs (self.scripts) do"
419                         "    fn (n, s)"
420                         "   end"
421                         "  end"
422                         ""
423                         "  local run = function ()"
424                         "   for n, s in pairs (self.instances) do"
425                         "     local status, err = pcall (s)"
426                         "     if not status then print ('fn \"'.. n .. '\": ', err) end"
427                         "   end"
428                         "   collectgarbage()"
429                         "  end"
430                         ""
431                         "  local add = function (n, f, a)"
432                         "   assert(type(n) == 'string', 'function-name must be string')"
433                         "   assert(type(f) == 'function', 'Given script is a not a function')"
434                         "   assert(type(a) == 'table' or type(a) == 'nil', 'Given argument is invalid')"
435                         "   assert(self.scripts[n] == nil, 'Callback \"'.. n ..'\" already exists.')"
436                         "   self.scripts[n] = { ['f'] = f, ['a'] = a }"
437                         "   local env = { print = print, Session = Session, tostring = tostring, assert = assert, ipairs = ipairs, error = error, string = string, type = type, tonumber = tonumber, collectgarbage = collectgarbage, pairs = pairs, math = math, table = table, pcall = pcall }"
438                         "   self.instances[n] = load (string.dump(f), nil, nil, env)(a)"
439                         "  end"
440                         ""
441                         "  local remove = function (n)"
442                         "   self.scripts[n] = nil"
443                         "  end"
444                         ""
445                         "  local list = function ()"
446                         "   local rv = {}"
447                         "   foreach (function (n) rv[n] = true end)"
448                         "   return rv"
449                         "  end"
450                         ""
451                         "  local function basic_serialize (o)"
452                         "    if type(o) == \"number\" then"
453                         "     return tostring(o)"
454                         "    else"
455                         "     return string.format(\"%q\", o)"
456                         "    end"
457                         "  end"
458                         ""
459                         "  local function serialize (name, value)"
460                         "   local rv = name .. ' = '"
461                         "   if type(value) == \"number\" or type(value) == \"string\" or type(value) == \"nil\" then"
462                         "    return rv .. basic_serialize(value) .. ' '"
463                         "   elseif type(value) == \"table\" then"
464                         "    rv = rv .. '{} '"
465                         "    for k,v in pairs(value) do"
466                         "     local fieldname = string.format(\"%s[%s]\", name, basic_serialize(k))"
467                         "     rv = rv .. serialize(fieldname, v) .. ' '"
468                         "    end"
469                         "    return rv;"
470                         "   elseif type(value) == \"function\" then"
471                         "     return rv .. string.format(\"%q\", string.dump(value))"
472                         "   else"
473                         "    error('cannot save a ' .. type(value))"
474                         "   end"
475                         "  end"
476                         ""
477                         ""
478                         "  local save = function ()"
479                         "   return (serialize('scripts', self.scripts))"
480                         "  end"
481                         ""
482                         "  local restore = function (state)"
483                         "   self.scripts = {}"
484                         "   load (state)()"
485                         "   print (scripts)"
486                         "   for n, s in pairs (scripts) do"
487                         "    add (n, load(s['f']), s['a'])"
488                         "   end"
489                         "  end"
490                         ""
491                         " return { run = run, add = add, remove = remove,"
492                   "          list = list, foreach = foreach,"
493                         "          restore = restore, save = save}"
494                         " end"
495                         " "
496                         " sess = ArdourSession ()"
497                         " ArdourSession = nil"
498                         );
499
500         luabridge::LuaRef *lua_run;
501         luabridge::LuaRef *lua_add;
502         luabridge::LuaRef *lua_del;
503         luabridge::LuaRef *lua_save;
504         luabridge::LuaRef *lua_load;
505         {
506                 luabridge::LuaRef lua_sess = luabridge::getGlobal (L, "sess");
507                 lua.do_command ("sess = nil"); // hide it.
508                 lua.do_command ("collectgarbage()");
509
510                 lua_run = new luabridge::LuaRef(lua_sess["run"]);
511                 lua_add = new luabridge::LuaRef(lua_sess["add"]);
512                 lua_del = new luabridge::LuaRef(lua_sess["remove"]);
513                 lua_save = new luabridge::LuaRef(lua_sess["save"]);
514                 lua_load = new luabridge::LuaRef(lua_sess["restore"]);
515         }
516         lua.do_command ("collectgarbage()");
517
518 #if 1
519         lua.do_command ("function factory (t) return function () local p = t or { } local a = t[1] or 'Nibor' print ('Hello ' .. a) end end");
520         luabridge::LuaRef lua_fact = luabridge::getGlobal (L, "factory");
521         luabridge::LuaRef tbl_arg (luabridge::newTable(L));
522         //tbl_arg[1] = "Robin";
523         (*lua_add)("t2", lua_fact, tbl_arg);
524 #else
525         lua.do_command ("function factory (t) return function () print ('Boo') end end");
526         luabridge::LuaRef lua_fact = luabridge::getGlobal (L, "factory");
527         (*lua_add)("t2", lua_fact());
528 #endif
529
530         lua.do_command ("function factory (t) return function () print ('Ahoy') end end");
531         luabridge::LuaRef lua_fact2 = luabridge::getGlobal (L, "factory");
532         (*lua_add)("t1", lua_fact2);
533
534         luabridge::LuaRef savedstate ((*lua_save)());
535         std::string saved = savedstate.cast<std::string>();
536
537         (*lua_del)("t2");
538
539         try {
540                 (*lua_run)();
541         } catch (luabridge::LuaException const& e) { printf ("LuaException: %s\n", e.what ()); }
542
543         (*lua_load)(saved);
544
545         for (int i = 0; i < 2; ++i) {
546         lua.do_command ("collectgarbage()");
547         lua.collect_garbage ();
548         try {
549                 (*lua_run)();
550         } catch (luabridge::LuaException const& e) { printf ("LuaException: %s\n", e.what ()); }
551         }
552
553 #endif
554
555         add_history("a = Test:A() b = 2 c = 3 d = 'a'");
556         add_history("x = a:get_arg(b)  y = a:get_arg2(b, c)  z = a:get_args(d) ");
557         add_history("for i,n in ipairs(y) do print (i, n); end");
558         add_history("t = {} t[2] = 7; t[3] = Test:A() t[4] = Test:A() ref:set (t);  f = ref:get()");
559
560         /////////////////////////////////////////////////////////////////////////////
561         char *line;
562         while ((line = readline ("> "))) {
563                 if (!strcmp (line, "quit")) {
564                         break;
565                 }
566                 if (strlen(line) == 0) {
567                         //lua.do_command("collectgarbage();");
568                         continue;
569                 }
570                 if (!lua.do_command (line)) {
571                         add_history(line); // OK
572                 } else {
573                         add_history(line); // :)
574                 }
575         }
576         printf("\n");
577         return 0;
578 }
579
580 int main (int argc, char **argv)
581 {
582         LuaState lua1;
583         LuaState lua2;
584         runone (lua1);
585         printf ("=====\n");
586         runone (lua2);
587 }