-
Notifications
You must be signed in to change notification settings - Fork 4
/
quikmultibridge.cpp
762 lines (725 loc) · 20.7 KB
/
quikmultibridge.cpp
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
#include "quikmultibridge.h"
#include <QDebug>
#include <QCoreApplication>
#include <QTimer>
#include <QThread>
#include <thread>
#define JUMP_TABLE_SIZE 100
static std::thread *mainThread = nullptr;
static void stackDump(lua_State *l)
{
int i;
int top = lua_gettop(l);
qDebug() << "-- Stack Dump, Size=" << top << " --";
for(i = 1; i <= top; i++)
{
int t = lua_type(l, i);
switch(t)
{
case LUA_TSTRING:
qDebug() << "String";
break;
case LUA_TBOOLEAN:
qDebug() << "Bool";
break;
case LUA_TNUMBER:
qDebug() << "Number";
break;
default:
qDebug() << QString::fromLocal8Bit(lua_typename(l, t));
break;
}
}
qDebug() << "-----------";
}
lua_State *getRecentStackForThreadId(BridgePlugin *plug, Qt::HANDLE ctid)
{
if(plug)
return plug->getRecentStackForThreadId(ctid);
return nullptr;
}
lua_State *getRecentStack(BridgePlugin *plug, Qt::HANDLE *p_ctid=nullptr)
{
Qt::HANDLE ctid = QThread::currentThreadId();
if(p_ctid)
*p_ctid = ctid;
return getRecentStackForThreadId(plug, ctid);
}
void setRecentStack(BridgePlugin *plug, lua_State *l)
{
if(plug)
{
Qt::HANDLE ctid = QThread::currentThreadId();
plug->setRecentStack(ctid, l);
}
}
struct JumpTableItem
{
BridgePlugin *ownerPlugin;
Qt::HANDLE threadId;
QString fName;
void *customData;
lua_CFunction callback;
QString callerName;
JumpTableItem():
ownerPlugin(nullptr),
threadId(nullptr),
fName(QString()),
customData(nullptr),
callback(nullptr),
callerName(QString())
{}
};
JumpTableItem jumpTable[JUMP_TABLE_SIZE];
int findFreeJumpTableSlot()
{
int i;
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(!jumpTable[i].customData && jumpTable[i].fName.isEmpty())
return i;
}
return -1;
}
int findJumpTableSlotForNamedCallback(BridgePlugin *plug, QString cbName)
{
int i;
//search slot for replacement
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(jumpTable[i].ownerPlugin==plug && !jumpTable[i].customData && jumpTable[i].fName==cbName)
return i;
}
return findFreeJumpTableSlot();
}
int findFreeOrExpiredJumpTableSlot(BridgePlugin *plug, QString caller)
{
//find expired
Qt::HANDLE ctid = QThread::currentThreadId();
int i;
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(jumpTable[i].ownerPlugin==plug && jumpTable[i].customData && jumpTable[i].threadId==ctid && jumpTable[i].callerName==caller)
return i;
}
//else find free
return findFreeJumpTableSlot();
}
int findNamedJumpTableSlot(BridgePlugin *plug, QString cbName)
{
int i;
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(jumpTable[i].ownerPlugin==plug && jumpTable[i].fName==cbName)
return i;
}
return -1;
}
bool registerNamedCallback(BridgePlugin *plug, QString cbName)
{
Qt::HANDLE ctid;
lua_State *recentStack = getRecentStack(plug, &ctid);
//qDebug() << "register named callback:" << cbName;
if(recentStack)
{
int i=findJumpTableSlotForNamedCallback(plug, cbName);
//qDebug() << "jumptable slot found:" << i;
if(i<0)
{
qDebug() << "No more free callback slots. Can't register" << cbName;
return false;
}
jumpTable[i].ownerPlugin = plug;
jumpTable[i].threadId = ctid;
jumpTable[i].fName = cbName;
lua_register(recentStack, cbName.toLocal8Bit().data(), jumpTable[i].callback);
}
return true;
}
int registerFastCallback(BridgePlugin *plug, QString caller, void *data)
{
Qt::HANDLE ctid = QThread::currentThreadId();
int i=findFreeOrExpiredJumpTableSlot(plug, caller);
if(i<0)
{
qDebug() << "No more free callback slots. Can't register fast callback";
return -1;
}
jumpTable[i].ownerPlugin = plug;
jumpTable[i].threadId = ctid;
jumpTable[i].callerName = caller;
jumpTable[i].customData = data;
return i;
}
void unregisterAllNamedCallbacks(BridgePlugin *plug)
{
int i;
lua_State *recentStack = getRecentStack(plug);
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(jumpTable[i].ownerPlugin==plug && !jumpTable[i].fName.isEmpty())
{
lua_pushnil(recentStack);
lua_setglobal(recentStack, jumpTable[i].fName.toLocal8Bit().data());
jumpTable[i].ownerPlugin = nullptr;
jumpTable[i].threadId = nullptr;
jumpTable[i].customData = nullptr;
jumpTable[i].fName = QString();
jumpTable[i].callerName = QString();
}
}
}
void unregisterAllCallbacksForCaller(BridgePlugin *plug, QString caller)
{
int i;
Qt::HANDLE ctid = QThread::currentThreadId();
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(jumpTable[i].ownerPlugin==plug && jumpTable[i].customData && jumpTable[i].threadId==ctid && jumpTable[i].callerName==caller)
{
jumpTable[i].ownerPlugin = nullptr;
jumpTable[i].threadId = nullptr;
jumpTable[i].customData = nullptr;
jumpTable[i].fName = QString();
jumpTable[i].callerName = QString();
}
}
}
void unregisterAllObjectCallbacks(BridgePlugin *plug, int objid)
{
QString prefix = QString("obj%1.").arg(objid);
int i;
Qt::HANDLE ctid = QThread::currentThreadId();
for(i=0; i<JUMP_TABLE_SIZE; i++)
{
if(jumpTable[i].ownerPlugin==plug && jumpTable[i].customData && jumpTable[i].threadId==ctid && jumpTable[i].callerName.startsWith(prefix))
{
jumpTable[i].ownerPlugin = nullptr;
jumpTable[i].threadId = nullptr;
jumpTable[i].customData = nullptr;
jumpTable[i].fName = QString();
jumpTable[i].callerName = QString();
}
}
}
static int extractValueFromLuaStack(lua_State *l, int sid, QVariant &sVal, QVariantList &lVal, QVariantMap &mVal, int *dtype=nullptr)
{
int resType; //0 - simple value, 1 - list, 2 - map
sid = lua_absindex(l, sid);
int t = lua_type(l, sid);
sVal.clear();
lVal.clear();
mVal.clear();
if(dtype)
*dtype = t;
switch(t)
{
case LUA_TBOOLEAN:
{
//qDebug() << "bool";
bool v = (bool)lua_toboolean(l, sid);
resType = 0;
sVal = QVariant(v);
break;
}
case LUA_TSTRING:
{
//qDebug() << "string";
QString v = QString::fromLocal8Bit(lua_tostring(l, sid));
resType = 0;
sVal = QVariant(v);
break;
}
case LUA_TNUMBER:
{
double v = lua_tonumber(l, sid);
resType = 0;
if(v==(int)v)
{
//qDebug() << "int";
sVal = QVariant((int)v);
}
else
{
//qDebug() << "double";
sVal = QVariant(v);
}
break;
}
case LUA_TTABLE:
{
lua_pushnil(l);
int lidx=1;
bool islist=true;
int dtype;
bool hasFunction=false;
while(lua_next(l, sid) != 0)
{
int kt=lua_type(l, -2);
QString k;
int ridx=0;
if(kt == LUA_TSTRING)
{
k = QString::fromLocal8Bit(lua_tostring(l, -2));
islist=false;
}
else
{
ridx = (int)lua_tonumber(l, -2);
k = QString("[%1]").arg(ridx);
if(ridx != lidx)
islist=false;
}
QVariant sv;
QVariantList lv;
QVariantMap mv;
int vtp = extractValueFromLuaStack(l, lua_gettop(l), sv, lv, mv, &dtype);
if(!vtp)
{
lVal.append(sv);
mVal.insert(k, sv);
if(dtype == LUA_TFUNCTION)
hasFunction = true;
}
else
{
if(vtp==1)
{
lVal.insert(lVal.length(), lv);
mVal.insert(k, lv);
}
else
{
lVal.insert(lVal.length(), mv);
mVal.insert(k, mv);
}
}
lidx++;
lua_pop(l, 1);
}
if(islist)
{
//qDebug() << "list";
mVal.clear();
resType = 1;
}
else
{
if(hasFunction)
{
//qDebug() << "object";
lua_pushvalue(l, sid); //копируем таблицу
int objid = luaL_ref(l, LUA_REGISTRYINDEX); //сохраняем в реестр и возвращаем индекс в реестре
lVal.clear();
mVal.clear();
QuikCallableObject qcobj;
qcobj.objid = objid;
sVal = QVariant::fromValue(qcobj);
resType = 0;
}
else
{
//qDebug() << "dict";
lVal.clear();
resType = 2;
}
}
break;
}
case LUA_TNIL:
case LUA_TNONE:
//qDebug() << "none";
resType = 0;
sVal = QVariant();
break;
case LUA_TFUNCTION:
//qDebug() << "function";
resType = 0;
sVal = QVariant();
break;
default:
//qDebug() << "Unknown type:" << QString::fromLocal8Bit(lua_typename(l, t));
resType = 0;
sVal = QVariant();
break;
}
return resType;
}
void invokePlugin(BridgePlugin *plug, QString name, const QVariantList &args, QVariant &vres)
{
if(plug)
plug->callbackRequest(name, args, vres);
}
void fastInvokePlugin(BridgePlugin *plug, BridgeCallableObject cobj, const QVariantList &args, QVariant &vres)
{
if(plug)
plug->fastCallbackRequest(cobj, args, vres);
}
void pushVariantToLuaStack(lua_State *l, QVariant val, QString caller)
{
switch(val.type())
{
case QVariant::Bool:
{
bool v = val.toBool();
lua_pushboolean(l, v);
break;
}
case QVariant::Int:
case QVariant::UInt:
case QVariant::LongLong:
case QVariant::ULongLong:
{
qlonglong v = val.toLongLong();
lua_pushinteger(l, v);
break;
}
case QVariant::String:
{
QString v = val.toString();
lua_pushstring(l, v.toLocal8Bit().data());
break;
}
case QVariant::Double:
{
double v = val.toDouble();
lua_pushnumber(l, v);
break;
}
case QVariant::Map:
{
QVariantMap tbl = val.toMap();
lua_newtable(l);
QMapIterator<QString, QVariant> ti(tbl);
while(ti.hasNext())
{
ti.next();
QString k;
QVariant v;
k=ti.key();
v=ti.value();
lua_pushstring(l, k.toLocal8Bit().data());
pushVariantToLuaStack(l, v, caller);
lua_settable(l, -3);
}
break;
}
case QVariant::List:
{
QVariantList lst = val.toList();
lua_newtable(l);
for(int li=0;li<lst.count();li++)
{
QVariant v = lst.at(li);
lua_pushinteger(l, li+1);
pushVariantToLuaStack(l, v, caller);
lua_settable(l, -3);
}
break;
}
default:
if(val.canConvert<BridgeCallableObject>())
{
if(caller.isEmpty())
qDebug() << "Callable object sent from lua?!";
else
{
BridgeCallableObject fcb = val.value<BridgeCallableObject>();
int cbi=registerFastCallback(fcb.ownerPlugin, caller, fcb.data);
if(cbi<0)
lua_pushnil(l);
else
{
lua_pushcfunction(l, jumpTable[cbi].callback);
}
}
}
else
lua_pushnil(l);
break;
}
}
QVariant popVariantFromLuaStack(lua_State *l)
{
QVariant sv;
QVariantList lv;
QVariantMap mv;
int vtp = extractValueFromLuaStack(l, -1, sv, lv, mv);
lua_pop(l, 1);
if(vtp == 1)
return QVariant(lv);
if(vtp == 2)
return QVariant(mv);
return sv;
}
bool getQuikVariable(BridgePlugin *plug, QString varname, QVariant &res)
{
lua_State *recentStack = getRecentStack(plug);
if(!recentStack)
{
qDebug() << "No stack?!";
return false;
}
lua_getglobal(recentStack, varname.toLocal8Bit().data());
res = popVariantFromLuaStack(recentStack);
return true;
}
bool invokeQuik(BridgePlugin *plug, QString method, const QVariantList &args, QVariantList &res, QString &errMsg)
{
//qDebug() << "invokeQuik:" << method;
lua_State *recentStack = getRecentStack(plug);
int top = lua_gettop(recentStack);
lua_getglobal(recentStack, method.toLocal8Bit().data());
res.clear();
errMsg.clear();
int li;
for(li=0;li<args.count();li++)
{
QVariant v = args.at(li);
pushVariantToLuaStack(recentStack, v, method);
}
//qDebug() << "lua_pcall...";
int pcres=lua_pcall(recentStack, li, LUA_MULTRET, 0);
if(pcres)
{
errMsg = QString::fromLocal8Bit(lua_tostring(recentStack, -1));
//qDebug() << "..." << errMsg;
lua_pop(recentStack, 1);
return false;
}
//qDebug() << "...finished";
while(lua_gettop(recentStack) != top)
{
QVariant resItem = popVariantFromLuaStack(recentStack);
//qDebug() << "return" << resItem.toString();
//мы забираем результаты с конца, поэтому и складывать нужно в обратном порядке
res.prepend(resItem);
}
//qDebug() << "return from invokeQuik";
return true;
}
bool invokeQuikObject(BridgePlugin *plug, int objid, QString method, const QVariantList &args, QVariantList &res, QString &errMsg)
{
QString caller = QString("obj%1.%2").arg(objid).arg(method);
lua_State *recentStack = getRecentStack(plug);
int top = lua_gettop(recentStack);
lua_rawgeti(recentStack, LUA_REGISTRYINDEX, objid);
lua_getfield(recentStack, -1, method.toLocal8Bit().data());
lua_pushvalue(recentStack, -2);
res.clear();
errMsg.clear();
int li;
for(li=0;li<args.count();li++)
{
QVariant v = args.at(li);
pushVariantToLuaStack(recentStack, v, caller);
}
int pcres=lua_pcall(recentStack, li+1, LUA_MULTRET, 0);
if(pcres)
{
errMsg = QString::fromLocal8Bit(lua_tostring(recentStack, -1));
lua_pop(recentStack, 1);
return false;
}
while(lua_gettop(recentStack) != top+1)
{
QVariant resItem = popVariantFromLuaStack(recentStack);
//мы забираем результаты с конца, поэтому и складывать нужно в обратном порядке
res.prepend(resItem);
}
lua_pop(recentStack, 1);
return true;
}
void deleteQuikObject(BridgePlugin *plug, int objid)
{
lua_State *recentStack = getRecentStack(plug);
if(!recentStack)
return;
unregisterAllObjectCallbacks(plug, objid);
luaL_unref(recentStack, LUA_REGISTRYINDEX, objid);
}
static int initBridge(lua_State *l)
{
BridgePlugin *plug = nullptr;
QVariant sv;
QVariantList lv;
QVariantMap mv;
int vtp = extractValueFromLuaStack(l, 1, sv, lv, mv);
if(vtp)
{
qDebug() << "First argument must specify bridge type('Python', 'QtRO', 'QtPlugin','R')";
return 1;
}
QString bridgeType = sv.toString();
if(bridgeType != "Python" &&
bridgeType != "QtRO" &&
bridgeType != "QtPlugin" &&
bridgeType != "R")
{
qDebug() << "Unknown bridge type. Possible values: 'Python', 'QtRO', 'QtPlugin','R'";
return 1;
}
vtp = extractValueFromLuaStack(l, 2, sv, lv, mv);
if(vtp != 2)
{
qDebug() << "Second argument must be bridge configuration table";
return 1;
}
//проверим специальный параметр "eventLoopName" и создадим главный цикл вне
//плагина - это нужно поскольку завершение этого цикла
//сигнализирует о завершении всего плагина и позволяет очистить память аккуратно
//сам же плагин должен зарегистрировать этот колбэк через registerCallback
QString loceln;
if(mv.contains("eventLoopName"))
{
loceln=mv.value("eventLoopName").toString();
}
//здесь нужно создать соответствующий плагин с заданной конфигурацией
if(bridgeType == "Python")
{
qDebug() << "Create PythonBridge...";
plug = new PythonBridge(mv);
}
if(plug)
{
if(!loceln.isEmpty())
plug->setEventLoopName(loceln);
setRecentStack(plug, l);
qDebug() << "Start plugin...";
plug->start();
}
return 1;
}
static struct luaL_Reg ls_lib[] = {
{"initBridge", initBridge},
{nullptr, nullptr}
};
static volatile int appStarted = 0;
static void qmbMain()
{
int argc = 1;
char appname[] = "QuikMultiBridge";
char* argv[] = {appname, NULL};
QCoreApplication app(argc, argv);
qDebug() << "start application...";
appStarted=1;
app.exec();
qDebug() << "Application finished";
}
int luaopen_QuikMultiBridge(lua_State *l)
{
if(!appStarted)
{
mainThread = new std::thread(qmbMain);
while(!appStarted);
}
luaL_newlib(l, ls_lib);
qDebug() << "Register initBridge...";
lua_register(l, "initBridge", initBridge);
qDebug() << "initBridge registered";
return 0;
}
static int universalCallbackHandler(JumpTableItem *jitem, lua_State *l)
{
QVariantList args;
QVariant sv, vres;
QVariantList lv;
QVariantMap mv;
int i;
//qDebug() << "universalCallbackHandler: start";
int top = lua_gettop(l);
for(i = 1; i <= top; i++)
{
int vtp = extractValueFromLuaStack(l, i, sv, lv, mv);
if(!vtp)
{
args.append(sv);
}
else
{
if(vtp==1)
{
args.insert(args.length(), lv);
}
else
{
args.insert(args.length(), mv);
}
}
}
//qDebug() << "universalCallbackHandler: get plugin";
BridgePlugin *plug = jitem->ownerPlugin;
/*
if(plug)
qDebug() << "universalCallbackHandler: plugin found";
else
qDebug() << "universalCallbackHandler: plugin is not found!";
*/
setRecentStack(plug, l);
bool finished = false;
if(jitem->fName.isEmpty())
{
//qDebug() << "universalCallbackHandler: fast callback";
if(jitem->customData)
{
BridgeCallableObject cobj;
cobj.ownerPlugin = plug;
cobj.data = jitem->customData;
fastInvokePlugin(plug, cobj, args, vres);
}
}
else
{
//qDebug() << "universalCallbackHandler: named callback:" << jitem->fName;
if(jitem->fName == plug->getEventLoopName())
finished=true;
invokePlugin(plug, jitem->fName, args, vres);
}
int rescnt = 0;
if(!vres.isNull())
{
//qDebug() << "universalCallbackHandler: results received";
if(vres.type() == QVariant::List)
{
//qDebug() << "universalCallbackHandler: return tuple";
//special case: multiple results
QVariantList lst = vres.toList();
for(int li=0;li<lst.count();li++)
{
QVariant v = lst.at(li);
//qDebug() << "item" << li << QString::fromLocal8Bit(v.typeName());
pushVariantToLuaStack(l, v, QString());
rescnt++;
}
}
else
{
//qDebug() << "universalCallbackHandler: return single value";
pushVariantToLuaStack(l, vres, QString());
rescnt++;
}
}
if(finished)
{
delete plug;
if(!BridgePlugin::getPluginCount())
{
qApp->quit();
//mainThread->join();
}
}
//qDebug() << "rescnt=" << rescnt;
return rescnt;
}
template<int i> int cbHandler(lua_State *l)
{
//qDebug() << "cbHandler" << i;
return universalCallbackHandler(&jumpTable[i], l);
}
template<int i> bool JumpTable_init()
{
jumpTable[i-1].callback = &cbHandler<i-1>;
return JumpTable_init<i-1>();
}
template<> bool JumpTable_init<-1>(){ return true; }
const bool jt_initialized = JumpTable_init<JUMP_TABLE_SIZE>();