forked from Alexey-T/CudaText
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proc_py.pas
667 lines (593 loc) · 16.2 KB
/
proc_py.pas
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
(*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (c) Alexey Torgashin
*)
unit proc_py;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes,
PythonEngine,
proc_globdata,
proc_appvariant;
type
{ TAppPython }
TAppPython = class
private
const NamePrefix = 'xx'; //the same as in py/cudatext_reset_plugins.py
private
FInited: boolean;
FEngine: TPythonEngine;
FRunning: boolean;
FLastCommandModule: string;
FLastCommandMethod: string;
FLastCommandParam: string;
EventTime: QWord;
EventTimes: TStringList;
LoadedLocals: TStringList;
LoadedModules: TStringList;
ModuleMain: PPyObject;
ModuleCud: PPyObject;
GlobalsMain: PPyObject;
GlobalsCud: PPyObject;
procedure TimeTrackBegin(var tick: QWord);
procedure TimeTrackEnd(const AModule: string; var tick: QWord);
procedure InitModuleMain;
procedure InitModuleCud;
procedure ImportCommand(const AObjectName, AModule: string);
function ImportModuleCached(const AModule: string): PPyObject;
function IsLoadedLocal(const S: string): boolean;
function MethodEvalEx(const AObject, AMethod: string; const AParams: array of PPyObject): TAppPyEventResult;
function MethodEvalObjects(const AObject, AFunc: string; const AParams: array of PPyObject): PPyObject;
public
constructor Create;
destructor Destroy; override;
procedure Initialize;
property Inited: boolean read FInited;
property Engine: TPythonEngine read FEngine;
property IsRunning: boolean read FRunning;
property LastCommandModule: string read FLastCommandModule;
property LastCommandMethod: string read FLastCommandMethod;
property LastCommandParam: string read FLastCommandParam;
function Eval(const Command: string; UseFileMode: boolean=false): PPyObject;
procedure Exec(const Command: string);
function RunCommand(const AModule, AMethod: string;
const AParams: TAppVariantArray): boolean;
function RunEvent(const AModule, ACmd: string; AEd: TObject;
const AParams: TAppVariantArray; ALazy: boolean): TAppPyEventResult;
function RunModuleFunction(const AModule, AFunc: string;
const AParams: array of PPyObject;
const AParamNames: array of string): PPyObject;
function RunModuleFunction(const AModule, AFunc: string;
const AParams: array of PPyObject): PPyObject;
function ValueFromString(const S: string): PPyObject;
function ValueToString(Obj: PPyObject; QuoteStrings: boolean): string;
procedure SetPath(const Dirs: array of string; DoAdd: boolean);
procedure ClearCache;
procedure DisableTiming;
function GetTimingReport: string;
end;
var
AppPython: TAppPython;
implementation
{ TAppPython }
constructor TAppPython.Create;
begin
inherited Create;
LoadedLocals:= TStringList.Create;
LoadedModules:= TStringList.Create;
EventTimes:= TStringList.Create;
end;
destructor TAppPython.Destroy;
begin
if Assigned(EventTimes) then
FreeAndNil(EventTimes);
FreeAndNil(LoadedModules);
FreeAndNil(LoadedLocals);
inherited Destroy;
end;
procedure TAppPython.Initialize;
begin
FInited:= PythonOK;
if FInited then
FEngine:= GetPythonEngine;
end;
function TAppPython.IsLoadedLocal(const S: string): boolean; inline;
begin
Result:= LoadedLocals.IndexOf(S)>=0;
end;
procedure TAppPython.DisableTiming;
begin
FreeAndNil(EventTimes);
end;
function TAppPython.GetTimingReport: string;
var
i: integer;
tick: PtrInt;
begin
Result:= IntToStr(EventTime div 10 * 10)+'ms (';
for i:= 0 to EventTimes.Count-1 do
begin
tick:= PtrInt(EventTimes.Objects[i]);
if i>0 then
Result+= ', ';
Result+=
Copy(EventTimes[i], 6, MaxInt)+' '+
IntToStr(tick)+'ms';
end;
Result+= ')';
end;
procedure TAppPython.InitModuleMain;
begin
with FEngine do
if ModuleMain=nil then
begin
ModuleMain:= PyImport_AddModule('__main__'); //same as PythonEngine.GetMainModule
if ModuleMain=nil then
raise EPythonError.Create('Python: cannot init __main__');
if GlobalsMain=nil then
GlobalsMain:= PyModule_GetDict(ModuleMain);
end;
end;
procedure TAppPython.InitModuleCud;
begin
with FEngine do
if ModuleCud=nil then
begin
ModuleCud:= PyImport_ImportModule('cudatext');
if ModuleCud=nil then
raise EPythonError.Create('Python: cannot import "cudatext"');
if GlobalsCud=nil then
GlobalsCud:= PyModule_GetDict(ModuleCud);
end;
end;
function TAppPython.Eval(const Command: string; UseFileMode: boolean=false): PPyObject;
var
Mode: integer;
begin
Result:= nil;
if not FInited then exit;
InitModuleMain;
if UseFileMode then
Mode:= file_input
else
Mode:= eval_input;
with FEngine do
begin
Traceback.Clear;
CheckError(False);
try
//PythonEngine used PChar(CleanString(Command)) - is it needed?
Result := PyRun_String(PChar(Command), Mode, GlobalsMain, GlobalsMain); //seems no need separate Locals
if Result = nil then
CheckError(False);
except
if PyErr_Occurred <> nil then
CheckError(False)
else
raise;
end;
end;
end;
procedure TAppPython.Exec(const Command: string);
begin
if not FInited then exit;
with FEngine do
Py_XDECREF(Eval(Command, true));
//UseFileMode=True to allow running several statements with ";"
end;
function TAppPython.MethodEvalObjects(const AObject, AFunc: string;
const AParams: array of PPyObject): PPyObject;
var
CurrObject, Func, Params: PPyObject;
i: integer;
begin
Result:=nil;
with FEngine do
begin
CurrObject:=PyDict_GetItemString(GlobalsMain,PChar(AObject));
if Assigned(CurrObject) then
begin
Func:=PyObject_GetAttrString(CurrObject,PChar(AFunc));
if Assigned(Func) then
try
//additional "self" is not needed
Params:=PyTuple_New(Length(AParams));
if Assigned(Params) then
try
for i:=0 to Length(AParams)-1 do
if PyTuple_SetItem(Params,i,AParams[i])<>0 then
RaiseError;
try
Result:=PyObject_Call(Func,Params,nil);
if Result = nil then
CheckError(False);
except
if PyErr_Occurred <> nil then
CheckError(False)
else
raise;
end;
finally
Py_DECREF(Params);
end;
finally
Py_DECREF(Func);
end;
end;
end;
end;
function TAppPython.MethodEvalEx(const AObject, AMethod: string;
const AParams: array of PPyObject): TAppPyEventResult;
var
Obj: PPyObject;
begin
Result.Val:= evrOther;
Result.Str:= '';
with FEngine do
begin
Obj:= MethodEvalObjects(AObject, AMethod, AParams);
if Assigned(Obj) then
try
if Pointer(Obj)=Pointer(Py_True) then
Result.Val:= evrTrue
else
if Pointer(Obj)=Pointer(Py_False) then
Result.Val:= evrFalse
else
if Obj^.ob_type=PyUnicode_Type then
begin
Result.Val:= evrString;
Result.Str:= PyUnicode_AsWideString(Obj);
end;
finally
Py_XDECREF(Obj);
end;
end;
end;
procedure TAppPython.ImportCommand(const AObjectName, AModule: string);
var
ObjModule, ObjDict, ObjClass, ObjObject: PPyObject;
begin
with FEngine do
begin
ObjModule:= ImportModuleCached(AModule);
if Assigned(ObjModule) then
begin
ObjDict:= PyModule_GetDict(ObjModule);
if Assigned(ObjDict) then
begin
ObjClass:= PyDict_GetItemString(ObjDict, 'Command');
if Assigned(ObjClass) then
try
ObjObject:= PyObject_CallObject(ObjClass, nil);
if Assigned(ObjObject) then
PyDict_SetItemString(GlobalsMain, PChar(AObjectName), ObjObject);
finally
Py_DECREF(ObjClass);
end;
end;
end;
end;
//old slow code:
//Exec(Format('import %s;%s=%s.Command()', [AModule, AObjectName, AModule]));
end;
function TAppPython.RunCommand(const AModule, AMethod: string; const AParams: TAppVariantArray): boolean;
var
ObjName: string;
ParamObjs: array of PPyObject;
Obj: PPyObject;
tick: QWord;
i: integer;
begin
if not FInited then exit(false);
InitModuleMain;
FRunning:= true;
TimeTrackBegin(tick);
FLastCommandModule:= AModule;
FLastCommandMethod:= AMethod;
FLastCommandParam:= '';
if Length(AParams)>0 then
if AParams[0].Typ=avrStr then
FLastCommandParam:= AParams[0].Str;
ObjName:= NamePrefix+AModule;
if not IsLoadedLocal(ObjName) then
begin
try
ImportCommand(ObjName, AModule);
LoadedLocals.Add(ObjName);
except
end;
end;
try
SetLength(ParamObjs, Length(AParams));
for i:= 0 to Length(AParams)-1 do
ParamObjs[i]:= AppVariantToPyObject(AParams[i]);
//Obj:= MethodEval(ObjName, AMethod, AppVariantArrayToString(AParams));
Obj:= MethodEvalObjects(ObjName, AMethod, ParamObjs);
if Assigned(Obj) then
with FEngine do
begin
//only check for False
Result:= Pointer(Obj)<>Pointer(Py_False);
Py_XDECREF(Obj);
end;
finally
TimeTrackEnd(AModule, tick);
FRunning:= false;
end;
end;
procedure TAppPython.TimeTrackBegin(var tick: QWord);
begin
if Assigned(EventTimes) then
tick:= GetTickCount64;
end;
procedure TAppPython.TimeTrackEnd(const AModule: string; var tick: QWord);
var
i: integer;
begin
if Assigned(EventTimes) then
begin
tick:= GetTickCount64-tick;
if tick>0 then
begin
Inc(EventTime, tick);
i:= EventTimes.IndexOf(AModule);
if i>=0 then
EventTimes.Objects[i]:= TObject(PtrInt(EventTimes.Objects[i])+PtrInt(tick))
else
EventTimes.AddObject(AModule, TObject(PtrInt(tick)));
end;
end;
end;
function TAppPython.RunEvent(const AModule, ACmd: string; AEd: TObject;
const AParams: TAppVariantArray; ALazy: boolean): TAppPyEventResult;
var
ParamsObj: array of PPyObject;
//
procedure InitParamsObj;
var
ObjEditor, ObjEditorArgs: PPyObject;
i: integer;
begin
SetLength(ParamsObj, Length(AParams)+1);
//first param must be None or Editor(AEd_handle)
with FEngine do
if AEd=nil then
ParamsObj[0]:= ReturnNone
else
begin
InitModuleCud;
ObjEditor:= PyDict_GetItemString(GlobalsCud, 'Editor');
if ObjEditor=nil then
raise EPythonError.Create('Python: cannot find cudatext.Editor');
ObjEditorArgs:= PyTuple_New(1);
try
PyTuple_SetItem(ObjEditorArgs, 0, PyLong_FromLongLong(PtrInt(AEd)));
ParamsObj[0]:= PyObject_CallObject(ObjEditor, ObjEditorArgs);
finally
Py_XDECREF(ObjEditorArgs);
end;
end;
for i:= 0 to Length(AParams)-1 do
ParamsObj[i+1]:= AppVariantToPyObject(AParams[i]);
end;
//
var
ObjName: string;
tick: QWord;
i: integer;
begin
Result.Val:= evrOther;
Result.Str:= '';
if not FInited then exit;
InitModuleMain;
FRunning:= true;
TimeTrackBegin(tick);
ObjName:= NamePrefix+AModule;
if not ALazy then
begin
if not IsLoadedLocal(ObjName) then
begin
try
ImportCommand(ObjName, AModule);
LoadedLocals.Add(ObjName);
except
end;
end;
InitParamsObj;
Result:= MethodEvalEx(ObjName, ACmd, ParamsObj);
end
else
//lazy event: run only of ObjName already created
if IsLoadedLocal(ObjName) then
begin
InitParamsObj;
Result:= MethodEvalEx(ObjName, ACmd, ParamsObj);
end;
FRunning:= false;
TimeTrackEnd(AModule, tick);
end;
function TAppPython.ImportModuleCached(const AModule: string): PPyObject;
var
N: integer;
begin
N:= LoadedModules.IndexOf(AModule);
if N>=0 then
Result:= PPyObject(LoadedModules.Objects[N])
else
begin
if UiOps.PyInitLog then
MsgLogConsole('Init: '+AModule);
Result:= FEngine.PyImport_ImportModule(PChar(AModule));
LoadedModules.AddObject(AModule, TObject(Result))
end;
end;
function TAppPython.RunModuleFunction(const AModule,AFunc:string;
const AParams:array of PPyObject;
const AParamNames:array of string):PPyObject;
var
Module,ModuleDic,Func,Params,ParamsDic:PPyObject;
i,UnnamedCount:integer;
begin
Result:=nil;
if not FInited then exit;
with FEngine do
begin
Module:=ImportModuleCached(AModule);
if Assigned(Module) then
try
ModuleDic:=PyModule_GetDict(Module);
if Assigned(ModuleDic) then
begin
Func:=PyDict_GetItemString(ModuleDic,PChar(AFunc));
if Assigned(Func) then
begin
UnnamedCount:=Length(AParams)-Length(AParamNames);
Params:=PyTuple_New(UnnamedCount);
if Assigned(Params) then
try
ParamsDic:=PyDict_New();
if Assigned(ParamsDic) then
try
for i:=0 to UnnamedCount-1 do
if PyTuple_SetItem(Params,i,AParams[i])<>0 then
RaiseError;
for i:=0 to Length(AParamNames)-1 do
if PyDict_SetItemString(ParamsDic,PChar(AParamNames[i]),AParams[UnnamedCount+i])<>0 then
RaiseError;
Result:=PyObject_Call(Func,Params,ParamsDic);
finally
Py_DECREF(ParamsDic);
end;
finally
Py_DECREF(Params);
end;
end;
end;
finally
end;
end;
end;
function TAppPython.RunModuleFunction(const AModule, AFunc: string;
const AParams: array of PPyObject): PPyObject;
var
Module,ModuleDic,Func,Params:PPyObject;
i:integer;
begin
Result:=nil;
if not FInited then exit;
with FEngine do
begin
Module:=ImportModuleCached(AModule);
if Assigned(Module) then
try
ModuleDic:=PyModule_GetDict(Module);
if Assigned(ModuleDic) then
begin
Func:=PyDict_GetItemString(ModuleDic,PChar(AFunc));
if Assigned(Func) then
begin
Params:=PyTuple_New(Length(AParams));
if Assigned(Params) then
try
for i:=0 to Length(AParams)-1 do
if PyTuple_SetItem(Params,i,AParams[i])<>0 then
RaiseError;
Result:=PyObject_Call(Func,Params,nil);
finally
Py_DECREF(Params);
end;
end;
end;
finally
end;
end;
end;
function TAppPython.ValueFromString(const S: string): PPyObject;
var
Num: Int64;
begin
if not FInited then exit(nil);
with FEngine do
begin
if S='' then
Result:= ReturnNone
else
if (S[1]='"') or (S[1]='''') then
Result:= PyString_FromString(PChar( Copy(S, 2, Length(S)-2) ))
else
if S='False' then
Result:= PyBool_FromLong(0)
else
if S='True' then
Result:= PyBool_FromLong(1)
else
if TryStrToInt64(S, Num) then
Result:= PyLong_FromLongLong(Num)
else
Result:= ReturnNone;
end;
end;
function TAppPython.ValueToString(Obj: PPyObject; QuoteStrings: boolean): string;
// the same as TPythonEngine.PyObjectAsString but also quotes str values
var
s: PPyObject;
w: UnicodeString;
begin
Result:= '';
if not FInited then exit;
if Obj=nil then exit;
with FEngine do
begin
if PyUnicode_Check(Obj) then
begin
w:= PyUnicode_AsWideString(Obj);
if QuoteStrings then
w:= '"'+w+'"';
Result:= w;
Exit;
end;
s:= PyObject_Str(Obj);
if Assigned(s) and PyString_Check(s) then
Result:= PyString_AsDelphiString(s);
Py_XDECREF(s);
end;
end;
procedure TAppPython.ClearCache;
var
i: integer;
Obj: PPyObject;
begin
if not FInited then exit;
LoadedLocals.Clear;
with FEngine do
for i:= 0 to LoadedModules.Count-1 do
begin
Obj:= PPyObject(LoadedModules.Objects[i]);
Py_XDECREF(Obj);
end;
LoadedModules.Clear;
end;
procedure TAppPython.SetPath(const Dirs: array of string; DoAdd: boolean);
var
Str, Sign: string;
i: Integer;
begin
Str:= '';
for i:= 0 to Length(Dirs)-1 do
Str:= Str + 'r"' + Dirs[i] + '",';
if DoAdd then
Sign:= '+='
else
Sign:= '=';
Str:= Format('sys.path %s [%s]', [Sign, Str]);
Exec(Str+';print("Python %d.%d"%sys.version_info[:2])');
end;
initialization
AppPython:= TAppPython.Create;
finalization
FreeAndNil(AppPython);
end.