-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathugolang.pas
1194 lines (1063 loc) · 30 KB
/
ugolang.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
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//----------------------------------------
//
// Copyright © ying32. All Rights Reserved.
//
// Licensed under Lazarus.modifiedLGPL
//
//----------------------------------------
unit ugolang;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
StrUtils,
Forms,
TypInfo,
LazFileUtils,
IDEExternToolIntf,
LazIDEIntf,
CompOptsIntf,
uSupports,
res2goResources,
uLangBase;
type
{ TGoLang }
TGoLang = class(TLangBase)
private
FUseGoEmbed: Boolean;
function ParamTypeCov(ASrc: string): string;
function IsBaseType(AType: string): Boolean;
function IsInterfaceType(AType: string): Boolean;
procedure CreateImplFile(AFileName: string; AEvents: array of TEventItem; AFormName: string);
procedure CreateNewMain(AStrs: TStrings; AParam: TProjParam);
function GetPrefixPackage: string;
function GetPackageImportPath(const AOutPath: string): string;
procedure AddOrRemoveImports(ALists: TStrings; AAdds, ARemoves: array of string; AUIPackageName: string; AOutPath: string);
procedure ProcessMainFunc(ALists: TStrings; ATitle: string; AUseScaled: Boolean; AForms: array of string);
function GetOS(ATargetOS: string): string;
function GetARCH(ATargetCPU: string): string;
protected
procedure InitTypeLists; override;
procedure InitBaseTypes; override;
function GetResFileExists: Boolean; override;
function GetPackageName: string; override;
public
constructor Create;
function Compile(AParams: TCompileParam): Boolean; override;
procedure ConvertProjectFile(AParam: TProjParam); override;
function ToEventString(AProp: PPropInfo): string; override;
procedure SaveToFile(AFileName: string; ARoot: TComponent; AEvents: array of TEventItem; AMem: TMemoryStream); override;
procedure ConvertResource(const AResFileName, APath: string); override;
property UseGoEmbed: Boolean read FUseGoEmbed write FUseGoEmbed;
end;
var
Golang: TGolang;
implementation
uses
Math;
{ TGoLang }
constructor TGoLang.Create;
begin
inherited Create;
end;
function TGoLang.Compile(AParams: TCompileParam): Boolean;
var
LCmd, LCmd2: string;
LTool: TIDEExternalToolOptions;
LOpts: TLazCompilerOptions;
LARCH, LOS: string;
LTags: string = '';
LIsWindows: Boolean = False;
LLdFlags: string = '';
LBuildMode: string = '';
LPaths, LGoRoot: string;
LIParams: string;
begin
Result := False;
if not Assigned(RunExternalTool) then
Exit;
{$ifdef windows}
LIsWindows := True;
{$endif}
// compiler options
LOpts :=LazarusIDE.ActiveProject.LazCompilerOptions;
LOS := GetOS(LOpts.TargetOS);
LARCH := GetARCH(LOpts.TargetCPU);
// -ldflags
// windowsgui
if LIsWindows and LOpts.Win32GraphicApp then
LLdFlags += ' -H windowsgui';
// no debug info
if not LOpts.GenerateDebugInfo then
LLDFlags += ' -w';
// strip symbols
if LOpts.StripSymbols then
LLDFlags += ' -s';
LLdFlags := LLdFlags.Trim;
if not LLdFlags.IsEmpty then
LLdFlags := ' -ldflags="' + LLdFlags + '"';
// -tags
if AParams.GoTags <> '' then
LTags += AParams.GoTags;
if AParams.GoUseTempdll and (LOS <> 'darwin') and (not LTags.Contains('tempdll')) then
LTags += ' tempdll';
if AParams.GoEnabledFinalizerOn and (not LTags.Contains('finalizerOn')) then
LTags += ' finalizerOn';
LTags := LTags.Trim;
if not LTags.IsEmpty then
LTags := ' -tags="' + LTags + '"';
// -buildmode
if AParams.GoBuildMode <> '' then
LBuildMode := ' -buildmode=' + AParams.GoBuildMode;
// command line
LIParams := '';
if not AParams.GoUseGoEmbed then // 1.16不支持-i参数了
LIParams := '-i';
LCmd := Format('build %s%s%s%s -o "%s"', [LIParams, LBuildMode, LLdFlags, LTags, AParams.Output]);
LCmd2 := 'go ' + LCmd;
Logs('Complie Command: ' + LCmd2);
LTool := TIDEExternalToolOptions.Create;
try
LTool.Title := LCmd2;
LTool.Hint := LCmd2;
// 这里要全路径,不然macOS下执行有问题
LGoRoot := AppendPathDelim(AppendPathDelim(AParams.GoRoot) + 'bin');
if not SysUtils.DirectoryExists(LGoRoot) then
LGoRoot := '';
LTool.Executable := LGoRoot + 'go'{$ifdef windows}+'.exe'{$endif};
LTool.WorkingDirectory := AParams.Input;
LTool.CmdLineParams := LCmd;
//Application.GetEnvironmentList(LTool.EnvironmentOverrides);
if LOS <> '' then
LTool.EnvironmentOverrides.Values['GOOS'] := LOS;
if LARCH <> '' then
LTool.EnvironmentOverrides.Values['GOARCH'] := LARCH;
// cgo
LTool.EnvironmentOverrides.Values['CGO_ENABLED'] := IfThen(AParams.GoEnabledCGO, '1', '0');
// GoRoot
if not AParams.GoRoot.IsEmpty then
begin
LTool.EnvironmentOverrides.Values['GOROOT'] := AParams.GoRoot;
//LPaths := LTool.EnvironmentOverrides.Values['PATH'];
//if not LPaths.EndsWith(';') then
// LPaths := LPaths + ';';
//LTool.EnvironmentOverrides.Values['PATH'] := LPaths + AppendPathDelim(AParams.GoRoot) + 'bin';
end;
LTool.Parsers.Add(SubToolFPC);
LTool.Parsers.Add(SubToolDefault);
{$ifdef windows}
// 非windows下不需要这个操作
LTool.ShowConsole := True;
LTool.HideWindow := True;
{$endif}
LTool.ResolveMacros := True;
Result := RunExternalTool(LTool);
finally
LTool.Free;
end;
end;
procedure TGoLang.ConvertProjectFile(AParam: TProjParam);
function GetForms: TAutoCreateForms;
var
I: Integer;
begin
Result := Self.GetAutoCreateForms;
if not Self.IsMainPackage then
begin
for I := 0 to High(Result) do
Result[I] := Self.PackageName + '.' + Result[I];
end;
end;
const
PkgArr: array[0..0] of string = ('_ "github.com/ying32/govcl/pkgs/winappres"');
var
LMainFile: TStringList;
LSaveFileName: string;
LMainFileExists: boolean;
begin
LMainFile := TStringList.Create;
try
LSaveFileName := AParam.OutPath + 'main.go';
LMainFileExists := FileExists(LSaveFileName);
// 如果不存在 main.go文件,则新建一个
if not LMainFileExists then
CreateNewMain(LMainFile, AParam)
else
begin
// 存在则加载此文件
LMainFile.LoadFromFile(LSaveFileName);
if AParam.UseDefaultWinAppRes then
AddOrRemoveImports(LMainFile, PkgArr, [], Self.PackageName, AParam.OutPath)
else
AddOrRemoveImports(LMainFile, [], PkgArr, Self.PackageName, AParam.OutPath);
ProcessMainFunc(LMainFile, AParam.Title, AParam.UseScaled, GetForms);
end;
LMainFile.SaveToFile(LSaveFileName);
finally
LMainFile.Free;
end;
end;
function TGoLang.ToEventString(AProp: PPropInfo): string;
var
I: Integer;
LFnParam: TFnParam;
LCovName: string;
begin
Result := '';
// 处理参数
I := 0;
for LFnParam in GetParams(AProp) do
begin
//if LFnParam.Name <> '$self' then
if Pos('$', LFnParam.Name) = 0 then
begin
if I > 1 then
Result += ', ';
Result += FirstCaseChar(LFnParam.Name) + ' '; // + ' <' + LFlagsStr + '>' + ParamTypeCov(LParamType);
LCovName := ParamTypeCov(LFnParam.&Type);
if ((pfAddress in LFnParam.Flags) or (pfVar in LFnParam.Flags) or (pfOut in LFnParam.Flags)) and not IsInterfaceType(LCovName) then // 要加 * 号的
Result += '*';
// 数组
if pfArray in LFnParam.Flags then
Result += '[]';
// 包名确认
if pfAddress in LFnParam.Flags then
Result += 'vcl.'; // 包名
if (not IsBaseType(LCovName)) and (not (pfAddress in LFnParam.Flags)) then
Result += 'types.';
Result += LCovName;
end;
Inc(I);
end;
end;
procedure TGoLang.SaveToFile(AFileName: string; ARoot: TComponent;
AEvents: array of TEventItem; AMem: TMemoryStream);
var
LStrStream, LBuffer: TStringStream;
LLines: TStringList;
procedure WLine(s: string = '');
begin
LLines.Add(S);
end;
function GetMaxLength: integer;
var
I: integer;
C: TComponent;
begin
Result := 0;
for I := 0 to ARoot.ComponentCount - 1 do
begin
C := ARoot.Components[I];
Result := Max(Result, Length(C.Name));
end;
end;
function GetIsFrame: boolean;
begin
Result := ARoot is TCustomFrame;
end;
function ConvertClassName(const ASrc: string): string;
begin
Result := ASrc;
if Result = 'TCalendar' then
Result := 'TMonthCalendar';
end;
var
I, LMaxLen: integer;
C: TComponent;
LVarName, LFormName, LTempName: string;
LItem: TEventItem;
LFindEvent: boolean;
LRealEventName: string;
LIsFrame: boolean;
begin
LStrStream := TStringStream.Create('');
LBuffer := TStringStream.Create('');
LLines := TStringList.Create;
try
WLine('// ' + rsAutomaticallyGeneratedByTheRes2goDoNotEdit);
WLine('package ' + PackageName);
WLine;
WLine('import (');
WLine(' "github.com/ying32/govcl/vcl"');
if UseGoEmbed then
WLine(' _ "embed"');
WLine(')');
WLine;
LFormName := ARoot.Name;
LIsFrame := False;
if GetIsFrame then
LIsFrame := True;
WLine(Format('type T%s struct {', [LFormName]));
if LIsFrame then
WLine(' *vcl.TFrame')
else
WLine(' *vcl.TForm');
LMaxLen := GetMaxLength;
for I := 0 to ARoot.ComponentCount - 1 do
begin
C := ARoot.Components[I];
if not IsSupportsComponent(C.ClassName) then
begin
CtlWriteln(mluError, rsComponentIsNotSupported, [LFormName + '.' + C.Name, C.ClassName]);
//Exit;
end;
if C.Name = '' then
Continue;
if CharInSet(C.Name[1], ['a'..'z', '_']) then
begin
CtlWriteln(mluWarning, rsComponentMustBeCapitalizedFirstToBeExported, [LFormName + '.' + C.Name, C.ClassName]);
Continue;
end;
//CtlWriteln('%s: %s', [C^.Name, C^.ClassName]);
// 这里查找下,当前组件有事件,但是这个事件是共享的。
LRealEventName := '';
LFindEvent := False;
for LItem in AEvents do
begin
if LItem.InstanceName = C.Name then
begin
// 当前实际关联的事件不是自己的,比如 Button2Click != Button1Click
if C.Name + LItem.EventTypeName <> LItem.EventName then
begin
LFindEvent := True;
if LRealEventName <> '' then
LRealEventName := LRealEventName + ',';
LRealEventName := LRealEventName + 'On' + LItem.EventName;
end;
end;
end;
// CtlWriteln('LReadEventName: %s', [LReadEventName]);
LTempName := Copy(C.Name + DupeString(#32, LMaxLen), 1, LMaxLen);
if LFindEvent and (LRealEventName <> '') then
WLine(Format(' %s *%s.%s `events:"%s"`',
[LTempName, 'vcl', ConvertClassName(C.ClassName), LRealEventName]))
else
WLine(Format(' %s *%s.%s', [LTempName, 'vcl', ConvertClassName(C.ClassName)]));
end;
WLine;
// 添加一个隐式字段,用于私有,方便写一些结构定自定义的变量什么的
WLine(' //' + PrivateFiledsFlagStr); // 这是一个查找标识
WLine(Format(' ' + PrivateFiledsStr, [LFormName]));
WLine('}');
WLine;
if not LIsFrame then
begin
WLine(Format('var %s *T%s', [LFormName, LFormName]));
WLine;
WLine;
WLine;
end;
WLine;
begin
LVarName := LFormName + 'Bytes';
// 包名不为main时,起始不变为小写。
//if PackageName.Equals('main') or PackageName.IsEmpty then
LVarName[1] := LowerCase(LVarName[1]);
if not LIsFrame then
begin
WLine(Format('// vcl.Application.CreateForm(&%s)', [LFormName]));
WLine;
end;
// 添加一个默认构建的,不使用Application.CreateForm
WLine(Format('func New%s(owner vcl.IComponent) (root *T%s) {',
[LFormName, LFormName]));
if not LIsFrame then
WLine(Format(' vcl.CreateResForm(owner, &root)', []))
else
WLine(Format(' vcl.CreateResFrame(owner, &root)', []));
WLine(' return');
WLine('}');
WLine('');
// 嵌入资源
if UseGoEmbed then
begin
WLine('//go:embed resources/' + ChangeFileExt(ExtractFileName(AFileName), '.gfm'));
WLine(Format('var %s []byte', [LVarName]));
end else
begin
LBuffer.WriteString(Format('var %s = []byte("', [LVarName]));
for I := 0 to AMem.Size - 1 do
begin
LBuffer.WriteString('\x');
LBuffer.WriteString(PByte(PByte(AMem.Memory) + I)^.ToHexString(2));
end;
LBuffer.WriteString('")');
WLine(LBuffer.DataString);
end;
WLine('');
WLine('// ' + rsRegisterFormResources);
if LIsFrame then
WLine(Format('var _ = vcl.RegisterFormResource(T%s{}, &%s)',
[LFormName, LVarName]))
else
WLine(Format('var _ = vcl.RegisterFormResource(%s, &%s)',
[LFormName, LVarName]));
end;
LStrStream.WriteString(LLines.Text);
LStrStream.SaveToFile(AFileName + '.go');
finally
LLines.Free;
LBuffer.Free;
LStrStream.Free;
end;
// 一定创建,因为多加了个
CreateImplFile(AFileName, AEvents, LFormName);
end;
procedure TGoLang.ConvertResource(const AResFileName, APath: string);
const
PlatformStr: array[Boolean] of string = ('pe-i386', 'pe-x86-64');
var
LWindResFileName: string;
function GetCmdLine(AOutFileName: string; AIsAmd64: Boolean): string;
begin
Result := Format('%s -i "%s" -J res -o "%s%s" -F %s', [LWindResFileName, AResFileName, APath, AOutFileName, PlatformStr[AIsAmd64]]);
end;
begin
if not FileExists(AResFileName) then
Exit;
LWindResFileName := WindResFileName;
if FileExists(LWindResFileName) then
LWindResFileName := '"' + LWindResFileName + '"'
else
LWindResFileName := 'windres';
ExecuteCommand([GetCmdLine('defaultRes_windows_386.syso', False), GetCmdLine('defaultRes_windows_amd64.syso', True)], True);
//olRust, olNim:
// if (OutLang = olNim) or ((OutLang = olRust) and (IsGNU)) then
// ExecuteCommand([GetCmdLine('appres_386.o', False), GetCmdLine('appres_amd64.o', True)], True);
end;
procedure TGoLang.CreateImplFile(AFileName: string; AEvents: array of TEventItem; AFormName: string);
var
LMName, LTemp, LCode, LPrivateName, LFlags: string;
LItem: TEventItem;
LStream: TStringStream;
LExists, LB: boolean;
LListStr: TStringList;
I: integer;
begin
AFileName += 'Impl.go';
LStream := TStringStream.Create('');
try
LExists := FileExists(AFileName);
LListStr := TStringList.Create;
try
// 不存在,则添加
if not LExists then
begin
LListStr.Add('');
LListStr.Add('package ' + PackageName);
LListStr.Add('');
if Length(AEvents) > 0 then
begin
LListStr.Add('import (');
LListStr.Add(' "github.com/ying32/govcl/vcl"');
LListStr.Add(')');
end;
end
else
begin
// 反之加载
LStream.LoadFromFile(AFileName);
LTemp := LStream.DataString;
LListStr.Text := LTemp;
// 有事件时检查下有没有添加govcl包
if Length(AEvents) > 0 then
begin
if Pos('import', LTemp) = 0 then
begin
I := 0;
while I < LListStr.Count do
begin
if Trim(LListStr[I]).StartsWith('package') then
begin
Inc(I);
LListStr.Insert(I, ')');
LListStr.Insert(I, ' "github.com/ying32/govcl/vcl"');
LListStr.Insert(I, 'import (');
LListStr.Insert(I, '');
Break;
end;
Inc(I);
end;
end;
end;
end;
// 添加事件
for LItem in AEvents do
begin
LMName := Format('On%s', [LItem.EventName]);
//CtlWriteln('method name: %s', [LMName]);
LCode := Format(#13#10'func (f *T%s) %s(%s) {'#13#10#13#10'}'#13#10,
[AFormName, LMName, LItem.EventParams]);
// 不存在不查找了
if not LExists then
begin
if Pos(LMName, LListStr.Text) = 0 then
LListStr.Add(LCode);
end else
begin
// 没有找到,则添加
if Pos(LMName, LListStr.Text) = 0 then
LListStr.Add(LCode);
end;
end;
// 检查私有变量结构是否存在
LPrivateName := Format(PrivateFiledsStr, [AFormName]);
// 不存在,则添加
if Pos(PrivateFiledsFlagStr, LListStr.Text) = 0 then
begin
I := 0;
while I < LListStr.Count do
begin
// 在首个func前几行插入
LFlags := 'import';
LB := (not LExists) and (Length(AEvents) = 0);
if LB then
LFlags := 'package';
if Trim(LListStr[I]).StartsWith(LFlags) then
begin
if not LB then
begin
repeat
Inc(I);
until Trim(LListStr[I]).StartsWith(')');
end;
Inc(I);
LListStr.Insert(I, '');
LListStr.Insert(I, '}');
LListStr.Insert(I, 'type ' + LPrivateName + ' struct {');
LListStr.Insert(I, '//' + PrivateFiledsFlagStr);
LListStr.Insert(I, '');
Break;
end;
Inc(I);
end;
end
else
begin
// 如果存在,则更新,因为防止把窗口名称改了,这里同步更新
for I := 0 to LListStr.Count - 1 do
begin
// 在首个func前几行插入
if LListStr[I].Contains(PrivateFiledsFlagStr) and LListStr[I].Contains('//') then
begin
LListStr[I + 1] := 'type ' + LPrivateName + ' struct {';
Break;
end;
end;
end;
// 这里是不是还得处理下,将窗口名称做一次替换
//f *TFrmMain
LStream.Clear;
LStream.WriteString(LListStr.Text);
finally
LListStr.Free;
end;
LStream.SaveToFile(AFileName);
finally
LStream.Free;
end;
end;
procedure TGoLang.CreateNewMain(AStrs: TStrings; AParam: TProjParam);
var
LForms: TAutoCreateForms;
LS: string;
begin
with AStrs do
begin
Add('// ' + rsAutomaticallyGeneratedByTheRes2go);
Add('package main'); // main.go文件始终都必须为main
Add('');
Add('import (');
Add(' "github.com/ying32/govcl/vcl"');
// winappres
if AParam.UseDefaultWinAppRes then
Add(' _ "github.com/ying32/govcl/pkgs/winappres"');
// 初始添加一个本地导入包的
// 还要判断当前目标目录在GOPATH中???不然要应用不同的规则
if not IsMainPackage then
Add(' "%s"', [GetPackageImportPath(AParam.OutPath)]);
Add(')');
Add('');
Add('func main() {');
// scaled
if AParam.UseScaled then
Add(' vcl.Application.SetScaled(true)');
// title
if AParam.Title <> '' then
Add(' vcl.Application.SetTitle("%s")', [AParam.Title]);
Add(' vcl.Application.Initialize()');
Add(' vcl.Application.SetMainFormOnTaskBar(true)');
// forms
LForms := Self.GetAutoCreateForms;
for LS in LForms do
begin
Add(' vcl.Application.CreateForm(&%s%s)', [GetPrefixPackage, LS]);
end;
Add(' vcl.Application.Run()');
Add('}');
end;
end;
function TGoLang.GetPrefixPackage: string;
begin
Result := '';
if not IsMainPackage then
Result := PackageName + '.';
end;
function TGoLang.GetPackageImportPath(const AOutPath: string): string;
var
LGoPaths, LPath, LCPath, LCOPath, LRealPath: string;
LPaths: array of string;
LP: Integer;
begin
Result := '';
if IsMainPackage then
Exit;
LGoPaths := GetEnvironmentVariable('GOPATH');
if not LGoPaths.IsEmpty then
begin
LPaths := LGoPaths.Split([';']);
for LPath in LPaths do
begin
LCPath := AppendPathDelim(AppendPathDelim(LPath.Trim) + 'src');
LCOPath := CleanAndExpandDirectory(AOutPath); //AppendPathDelim(AOutPath);
if SameText(LCPath, Copy(LCOPath, 1, Length(LCPath))) then
begin
LRealPath := Copy(LCOPath, Length(LCPath) + 1, Length(LCOPath) - Length(LCPath) - 1);
Exit(LRealPath.Replace('\', '/') + '/' + PackageName);
end;
end;
end;
Result := './' + PackageName;
end;
procedure TGoLang.AddOrRemoveImports(ALists: TStrings; AAdds,
ARemoves: array of string; AUIPackageName: string; AOutPath: string);
const
Keywords: array[0..3] of string = ('var', 'const', 'type', 'func');
type
TImportItem = record
Path: string;
OrigPath: string;
&Single: Boolean;
LineNumber: Integer;
end;
var
I: Integer;
LS: string;
LIsEnd: Boolean;
LImports: array of TImportItem;
LPkgLineNumber: Integer; // package
LInsertStartIndex: Integer;
LIsSingle: Boolean;
procedure UpdateLineNumber(AStart: Integer; AValue: Integer);
var
J: Integer;
begin
for J := AStart to High(LImports) do
LImports[J].LineNumber += AValue;
end;
function GetRealImportPath(const APath: string): string;
var
LP1, LP2: Integer;
begin
LP1 := Pos('"', APath);
if LP1 > 0 then
begin
LP2 := Pos('"', APath, LP1 + 1);
if LP2 > 0 then
Exit(Copy(APath, LP1+1, LP2 - LP1 - 1));
end;
Result := APath;
end;
procedure AddImportItem(APath: string; ASingle: Boolean);
begin
SetLength(LImports, Length(LImports) + 1);
with LImports[High(LImports)] do
begin
OrigPath := APath;
Path := GetRealImportPath(APath);
&Single := ASingle;
LineNumber := I;
end;
end;
function LastItem: TImportItem;
begin
Result := LImports[High(LImports)];
end;
function IndexPkgNameOf(APath: string): Integer;
var
J: Integer;
begin
Result := -1;
for J := 0 to High(LImports) do
if LImports[J].Path = GetRealImportPath(APath) then
Exit(J);
end;
function IndexUIPkgNameOf: Integer;
var
J: Integer;
begin
Result := -1;
for J := 0 to High(LImports) do
if LImports[J].Path.EndsWith('/'+ AUIPackageName) then
Exit(J);
end;
function InKeyWords: Boolean;
var
LKey: string;
begin
Result := False;
for LKey in Keywords do
begin
if LS.StartsWith(LKey) then
Exit(True);
end;
end;
function LineStr: string;
begin
Result := ALists[I].Trim;
end;
procedure CheckComment;
begin
if LS.StartsWith('/*') then
begin
repeat
Inc(I);
LS := LineStr;
until LS.StartsWith('*/') or LS.EndsWith('*/') or (I >= ALists.Count-1);
Inc(I);
LS := LineStr;
end;
end;
begin
I := 0;
while I < ALists.Count do
begin
LS := LineStr;
CheckComment;
if LS.StartsWith('package') then
LPkgLineNumber := I
else
if LS.StartsWith('import') then
begin
if LS.IndexOf('(') >= 6 then
begin
repeat
Inc(I);
LS := LineStr;
CheckComment;
LIsEnd := LS.StartsWith(')');
if (not LIsEnd) and (not LS.IsEmpty) then
AddImportItem(LS, False);
until LIsEnd or (I >= ALists.Count-1);
end else
begin
AddImportItem(Copy(LS, 7, Length(LS)-6).Trim, True);
end;
end;
if InKeyWords then
Break;
Inc(I);
end;
// 添加测试
if (Length(ARemoves) > 0) and (Length(LImports) > 0) then
begin
// 删除
for LS in ARemoves do
begin
I := IndexPkgNameOf(LS);
if I <> -1 then
begin
ALists.Delete(LImports[I].LineNumber);
UpdateLineNumber(I, -1);
end;
end;
end;
if Length(AAdds) > 0 then
begin
if Length(LImports) > 0 then
begin
with LastItem do
begin
LInsertStartIndex := LineNumber;
LIsSingle := &Single;
end;
end else
begin
LInsertStartIndex := LPkgLineNumber + 2;
ALists.Insert(LInsertStartIndex, ')');
ALists.Insert(LInsertStartIndex, 'import (');
LIsSingle := False;
end;
// 添加
for LS in AAdds do
begin
if IndexPkgNameOf(LS) = -1 then
begin
if LIsSingle then
ALists.Insert(LInsertStartIndex + 1, 'import ' + LS)
else
ALists.Insert(LInsertStartIndex + 1, ' ' + LS);
UpdateLineNumber(I, 1);
end;
end;
end;
// 独立检查的
if (AUIPackageName <> '') and (AUIPackageName <> 'main') and (Length(LImports) > 0) then
begin
I := IndexUIPkgNameOf;
if I = -1 then
begin
with LastItem do
begin
LS := '"' + GetPackageImportPath(AOutPath) + '"';
if &Single then
ALists.Insert(LineNumber + 1, 'import ' + LS)
else
ALists.Insert(LineNumber + 1, ' ' + LS);
end;
end;
end;
end;
procedure TGoLang.ProcessMainFunc(ALists: TStrings; ATitle: string;
AUseScaled: Boolean; AForms: array of string);
type
TAppItem = record
Name: string;
UsePkgName: Boolean;
LineNumber: Integer;
end;
var
I, N: Integer;
LS: string;
LUsePkgName: Boolean;
LLineArr: array of string;
LApps: array of TAppItem;
procedure AddItem(AName: string);
begin
SetLength(LApps, Length(LApps) + 1);
with LApps[High(LApps)] do
begin
Name := AName;
LineNumber := I;
end;
end;
procedure UpdateLineNumber(AStart: Integer; AValue: Integer);
var
J: Integer;
begin
for J := AStart to High(LApps) do
LApps[J].LineNumber += AValue;
end;
function LineStr: string;
begin
Result := ALists[I].Trim;
end;
procedure CheckComment;
begin
if LS.StartsWith('/*') then
begin
repeat
Inc(I);
LS := LineStr;
until LS.StartsWith('*/') or LS.EndsWith('*/') or (I >= ALists.Count-1);
Inc(I);
LS := LineStr;
end;
end;
function IndexNameOf(const AName: string): Integer;
var
J: Integer;
begin
Result := -1;
for J := 0 to High(LApps) do
begin
if SameText(LApps[J].Name, AName) then
Exit(J);
end;
end;
function RemoveAllCreateForm: Integer;
var
J: Integer;
begin
Result := -1;
for J := 0 to High(LApps) do
begin
if SameText(LApps[J].Name, 'CreateForm') then
begin
ALists.Delete(LApps[J].LineNumber);
UpdateLineNumber(J, -1);
if Result = -1 then
Result := LApps[J].LineNumber + 1;
end;