-
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathoptiscaler_update.pas
More file actions
2557 lines (2325 loc) · 89.2 KB
/
Copy pathoptiscaler_update.pas
File metadata and controls
2557 lines (2325 loc) · 89.2 KB
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
unit optiscaler_update;
interface
uses
Classes, SysUtils, Forms, ComCtrls, Buttons, Process,
RegExpr, fpjson, jsonparser, zipper, Dialogs, StdCtrls, Graphics, DateUtils,
constants, notificationunit;
// Function to get the correct OptiScaler installation path (Flatpak-aware)
function GetOptiScalerInstallPath: string;
// Check and automatically install OptiScaler if not present
// Returns True if OptiScaler is installed (or was successfully installed)
function CheckAndInstallOptiScaler(const AFGModPath: string): Boolean;
type
TOptiscalerTab = class
private
FUpdateBtn: TBitBtn;
FCheckupdBtn: TBitBtn;
FProgressBar: TProgressBar;
FStatusLabel: TLabel;
FDeckyLabel: TLabel;
FOptiLabel: TLabel;
FOptiLabel2: TLabel; // Label for OptiScaler update notification
FFakeNvapiLabel: TLabel;
FXessLabel: TLabel;
FFsrLabel: TLabel;
FDeckyLabel2: TLabel; // Label for update notification
FFakeNvapiLabel2: TLabel; // Label for update notification
FNotificationLabel: TLabel; // Label for general notifications
FFsrVersionComboBox: TComboBox; // ComboBox for FSR version selection
FOptVersionComboBox: TComboBox; // ComboBox for OptiScaler channel selection
FOptiPatcherLabel: TLabel; // Label for OptiPatcher version
FDlssLabel: TLabel; // Label for DLSS download date
FFGModPath: string;
FUpdateThread: TThread;
function FetchManifest(ASilent: Boolean; out AStableVer, AStableURL, AEdgeVer, AEdgeURL: string): Boolean;
function GetLatestReleaseTag(ASilent: Boolean = False): string;
function GetOptiScalerStableTag(ASilent: Boolean = False): string;
function GetOptiScalerPreReleaseTag(ASilent: Boolean = False): string;
function DownloadFile(const AURL, ADestFile: string): Boolean;
function ExtractZip(const AZipFile, ADestPath: string): Boolean;
function Extract7z(const A7zFile, ADestPath: string): Boolean;
procedure CopyDirectory(const ASource, ADest: string);
procedure UpdateProgress(AProgress: Integer);
procedure UpdateStatus(const AStatus: string);
function ExtractOptiScalerVersion(const AFileName: string): string;
function FetchFakeNvapiLatest(out ATag, AURL: string): Boolean;
function FetchVarsTxt(out AFsrStable, AFsrEdge, AXessStable, AXessEdge: string): Boolean;
function ReadCachedOptiScalerVersion: string;
procedure CheckForUpdates;
procedure SyncPristineAssetsTo(const ASourceDir, ATargetDir: string);
function GetBGModOriginalPathForChannel(IsStable: Boolean): string;
public
FOptiStableVersion: string;
FOptiStableURL: string;
FOptiEdgeVersion: string;
FOptiEdgeURL: string;
procedure LoadVersionsFromFile;
procedure UpdateButtonClick(Sender: TObject);
procedure InitializeTab;
procedure CheckForUpdatesOnClick;
property FGModPath: string read FFGModPath write FFGModPath;
property UpdateBtn: TBitBtn read FUpdateBtn write FUpdateBtn;
property CheckupdBtn: TBitBtn read FCheckupdBtn write FCheckupdBtn;
property ProgressBar: TProgressBar read FProgressBar write FProgressBar;
property StatusLabel: TLabel read FStatusLabel write FStatusLabel;
property DeckyLabel: TLabel read FDeckyLabel write FDeckyLabel;
property OptiLabel: TLabel read FOptiLabel write FOptiLabel;
property OptiLabel2: TLabel read FOptiLabel2 write FOptiLabel2;
property FakeNvapiLabel: TLabel read FFakeNvapiLabel write FFakeNvapiLabel;
property XessLabel: TLabel read FXessLabel write FXessLabel;
property FsrLabel: TLabel read FFsrLabel write FFsrLabel;
property DeckyLabel2: TLabel read FDeckyLabel2 write FDeckyLabel2;
property FakeNvapiLabel2: TLabel read FFakeNvapiLabel2 write FFakeNvapiLabel2;
property NotificationLabel: TLabel read FNotificationLabel write FNotificationLabel;
property FsrVersionComboBox: TComboBox read FFsrVersionComboBox write FFsrVersionComboBox;
property OptVersionComboBox: TComboBox read FOptVersionComboBox write FOptVersionComboBox;
property OptiPatcherLabel: TLabel read FOptiPatcherLabel write FOptiPatcherLabel;
property DlssLabel: TLabel read FDlssLabel write FDlssLabel;
end;
implementation
uses
FileUtil, LazFileUtils, BaseUnix, bgmod_resources, systemdetector, overlayunit, overlay_config, apputils, IniFiles;
type
TOptiUpdateThread = class(TThread)
private
FOptiTab: TOptiscalerTab;
FIsStableChannel: Boolean;
FLatestOptiTag: string;
FLatestDeckyVersion: string;
FCheckDecky: Boolean;
FSpawnedFGModPath: string;
procedure SyncUpdateUI;
protected
procedure Execute; override;
public
constructor Create(AOptiTab: TOptiscalerTab; AIsStable: Boolean; ACheckDecky: Boolean);
end;
{ TOptiUpdateThread }
constructor TOptiUpdateThread.Create(AOptiTab: TOptiscalerTab; AIsStable: Boolean; ACheckDecky: Boolean);
begin
inherited Create(True);
FOptiTab := AOptiTab;
FIsStableChannel := AIsStable;
FCheckDecky := ACheckDecky;
FLatestOptiTag := '';
FLatestDeckyVersion := '';
// Snapshot the path the thread was spawned against so SyncUpdateUI can
// discard stale results when the active game (and thus FGModPath) has
// changed between spawn and UI sync.
FSpawnedFGModPath := AOptiTab.FFGModPath;
FreeOnTerminate := True;
end;
procedure TOptiUpdateThread.Execute;
begin
WriteLn('[DEBUG] TOptiUpdateThread.Execute: Thread started');
// Fetch OptiScaler version
if FIsStableChannel then
begin
WriteLn('[DEBUG] TOptiUpdateThread.Execute: Checking Stable channel...');
FLatestOptiTag := FOptiTab.GetOptiScalerStableTag(True);
end
else
begin
WriteLn('[DEBUG] TOptiUpdateThread.Execute: Checking Bleeding-Edge channel...');
FLatestOptiTag := FOptiTab.GetOptiScalerPreReleaseTag(True);
end;
// Fetch Decky version if requested
if FCheckDecky then
begin
WriteLn('[DEBUG] TOptiUpdateThread.Execute: Checking Decky version...');
FLatestDeckyVersion := FOptiTab.GetLatestReleaseTag(True);
end;
WriteLn('[DEBUG] TOptiUpdateThread.Execute: Thread work completed. OptiTag = ', FLatestOptiTag, ', DeckyTag = ', FLatestDeckyVersion);
if not Terminated then
begin
WriteLn('[DEBUG] TOptiUpdateThread.Execute: Synchronizing UI...');
Synchronize(@SyncUpdateUI);
end;
end;
procedure TOptiUpdateThread.SyncUpdateUI;
var
HasUpdates: Boolean;
CurrentVersion: string;
NormLatest, NormCurrent: string;
CurrentIsEdge, IsCrossChannel: Boolean;
begin
if Terminated then Exit;
// Skip if channel changed since thread was spawned
if Assigned(FOptiTab.FOptVersionComboBox) then
begin
if (FIsStableChannel and (FOptiTab.FOptVersionComboBox.ItemIndex <> 0))
or (not FIsStableChannel and (FOptiTab.FOptVersionComboBox.ItemIndex <> 1)) then
begin
WriteLn('[DEBUG] SyncUpdateUI: Channel changed since spawn, discarding results (spawned=', FIsStableChannel, ' current=', FOptiTab.FOptVersionComboBox.ItemIndex, ')');
FOptiTab.FUpdateThread := nil;
Exit;
end;
end;
// Skip if the active game (FGModPath) changed since thread was spawned:
// otherwise we would compare remote tags against the wrong game's vars.
if FSpawnedFGModPath <> FOptiTab.FFGModPath then
begin
WriteLn('[DEBUG] SyncUpdateUI: FGModPath changed since spawn (spawned=', FSpawnedFGModPath, ' current=', FOptiTab.FFGModPath, '), discarding results');
FOptiTab.FUpdateThread := nil;
Exit;
end;
HasUpdates := False;
// 1. Process OptiScaler Updates
if Assigned(FOptiTab.FOptiLabel2) then
begin
if Assigned(FOptiTab.FOptiLabel) then
CurrentVersion := FOptiTab.FOptiLabel.Caption
else
CurrentVersion := '';
if (FLatestOptiTag <> '') and (CurrentVersion <> '') then
begin
NormLatest := StringReplace(FLatestOptiTag, '-', '.', [rfReplaceAll]);
NormCurrent := StringReplace(CurrentVersion, '-', '.', [rfReplaceAll]);
if (Length(NormLatest) > 5) and (Copy(NormLatest, 1, 5) = 'edge.') then
NormLatest := Copy(NormLatest, 6, MaxInt);
if (Length(NormCurrent) > 5) and (Copy(NormCurrent, 1, 5) = 'edge.') then
NormCurrent := Copy(NormCurrent, 6, MaxInt);
CurrentIsEdge := (Length(CurrentVersion) > 5) and (Copy(CurrentVersion, 1, 5) = 'edge-');
if FIsStableChannel then
IsCrossChannel := CurrentIsEdge
else
IsCrossChannel := not CurrentIsEdge;
WriteLn('[DEBUG] SyncUpdateUI: FIsStableChannel=', FIsStableChannel, ' CurrentVersion="', CurrentVersion,
'" CurrentIsEdge=', CurrentIsEdge, ' IsCrossChannel=', IsCrossChannel,
' NormLatest=', NormLatest, ' NormCurrent=', NormCurrent);
if IsCrossChannel or (CompareVersions(NormLatest, NormCurrent) > 0) then
begin
FOptiTab.FOptiLabel2.Caption := 'Update Available ' + FLatestOptiTag;
FOptiTab.FOptiLabel2.Font.Color := clLime;
FOptiTab.FOptiLabel2.Visible := True;
HasUpdates := True;
WriteLn('[DEBUG] TOptiUpdateThread.SyncUpdateUI: OptiScaler update available: ', FLatestOptiTag);
end
else
begin
FOptiTab.FOptiLabel2.Visible := False;
WriteLn('[DEBUG] TOptiUpdateThread.SyncUpdateUI: OptiScaler is up to date (remote=', NormLatest, ' installed=', NormCurrent, ')');
end;
end
else
FOptiTab.FOptiLabel2.Visible := False;
end;
// 2. Process Decky Updates
if FCheckDecky and (FLatestDeckyVersion <> '') then
begin
if Assigned(FOptiTab.FDeckyLabel) and (FOptiTab.FDeckyLabel.Caption <> '') and (FOptiTab.FDeckyLabel.Caption <> '—') then
begin
if (FLatestDeckyVersion <> FOptiTab.FDeckyLabel.Caption) then
begin
if Assigned(FOptiTab.FDeckyLabel2) then
begin
FOptiTab.FDeckyLabel2.Caption := ' Update available ' + '(' + FLatestDeckyVersion + ')';
FOptiTab.FDeckyLabel2.Visible := True;
FOptiTab.FDeckyLabel2.Font.Color := clLime;
HasUpdates := True;
WriteLn('[DEBUG] TOptiUpdateThread.SyncUpdateUI: Decky update available: ', FLatestDeckyVersion);
end;
end
else
begin
if Assigned(FOptiTab.FDeckyLabel2) then
FOptiTab.FDeckyLabel2.Visible := False;
WriteLn('[DEBUG] TOptiUpdateThread.SyncUpdateUI: Decky is up to date');
end;
end;
end
else
begin
if Assigned(FOptiTab.FDeckyLabel2) then
FOptiTab.FDeckyLabel2.Visible := False;
end;
// 3. Update update button & check button visibility
if HasUpdates then
begin
if Assigned(FOptiTab.FCheckupdBtn) then
FOptiTab.FCheckupdBtn.Visible := False;
if Assigned(FOptiTab.FUpdateBtn) then
begin
FOptiTab.FUpdateBtn.Caption := 'Update';
FOptiTab.FUpdateBtn.Visible := True;
end;
end
else
begin
if Assigned(FOptiTab.FCheckupdBtn) then
begin
FOptiTab.FCheckupdBtn.Visible := True;
FOptiTab.FCheckupdBtn.Enabled := True;
end;
if Assigned(FOptiTab.FUpdateBtn) then
FOptiTab.FUpdateBtn.Visible := False;
end;
// 4. Clean up thread pointer
FOptiTab.FUpdateThread := nil;
// 5. Refresh UI layout helpers in overlayunit
if Assigned(goverlayform) then
begin
goverlayform.RefreshHomeOptiStatus;
goverlayform.RefreshOsStatusDots;
end;
WriteLn('[DEBUG] TOptiUpdateThread.SyncUpdateUI: UI synchronization finished');
end;
// Function to get the correct OptiScaler installation path with XDG compliance
// Returns: ~/.local/share/goverlay/bgmod (Sandboxed in Flatpak)
function GetOptiScalerInstallPath: string;
begin
// Use the central function from bgmod_resources to ensure consistency
Result := GetBGModPath;
end;
{ TOptiscalerTab }
procedure TOptiscalerTab.UpdateProgress(AProgress: Integer);
begin
if Assigned(FProgressBar) then
begin
FProgressBar.Position := AProgress;
Application.ProcessMessages;
end;
// Show percentage on button (but don't change if resetting to 0)
if Assigned(FUpdateBtn) and (AProgress > 0) then
begin
FUpdateBtn.Caption := IntToStr(AProgress) + '%';
Application.ProcessMessages;
end;
end;
procedure TOptiscalerTab.UpdateStatus(const AStatus: string);
begin
if Assigned(FStatusLabel) then
begin
FStatusLabel.Caption := AStatus;
Application.ProcessMessages;
end;
end;
function TOptiscalerTab.ExtractOptiScalerVersion(const AFileName: string): string;
var
BaseName: string;
RegEx: TRegExpr;
begin
Result := '';
WriteLn('[DEBUG] ExtractOptiScalerVersion: Input filename = ', AFileName);
// Get filename without path and extension
BaseName := ChangeFileExt(ExtractFileName(AFileName), '');
WriteLn('[DEBUG] ExtractOptiScalerVersion: Base name (no ext) = ', BaseName);
// Use regex to extract version pattern (numbers separated by dots)
// Pattern: OptiScaler_X.X.X or similar
RegEx := TRegExpr.Create;
try
// Match pattern like: 0.7.9 or 1.2.3.4
RegEx.Expression := '(\d+\.\d+\.\d+(?:\.\d+)?)';
WriteLn('[DEBUG] ExtractOptiScalerVersion: Attempting regex match with pattern: ', RegEx.Expression);
if RegEx.Exec(BaseName) then
begin
WriteLn('[DEBUG] ExtractOptiScalerVersion: Regex matched, MatchCount = ', RegEx.SubExprMatchCount);
if RegEx.SubExprMatchCount >= 1 then
begin
Result := RegEx.Match[1];
WriteLn('[DEBUG] ExtractOptiScalerVersion: Extracted version = "', Result, '"');
end
else
WriteLn('[ERROR] ExtractOptiScalerVersion: Match found but SubExprMatchCount < 1');
end
else
WriteLn('[WARN] ExtractOptiScalerVersion: No regex match found in basename');
finally
RegEx.Free;
end;
end;
function TOptiscalerTab.GetLatestReleaseTag(ASilent: Boolean = False): string;
var
Process: TProcess;
OutputList: TStringList;
Response: string;
JSONData: TJSONData;
JSONObject: TJSONObject;
begin
Result := '';
Process := TProcess.Create(nil);
OutputList := TStringList.Create;
try
try
WriteLn('[DEBUG] GetLatestReleaseTag: Fetching from ', URL_DECKY_FRAMEGEN_API);
// Use curl to get GitHub API
Process.Executable := 'curl';
Process.Parameters.Add('-s'); // Silent mode
Process.Parameters.Add('-L'); // Follow redirects
Process.Parameters.Add('-H');
Process.Parameters.Add('Accept: application/vnd.github.v3+json');
Process.Parameters.Add('-H');
Process.Parameters.Add('User-Agent: Mozilla/5.0');
Process.Parameters.Add(URL_DECKY_FRAMEGEN_API);
Process.Options := [poWaitOnExit, poUsePipes];
Process.Execute;
// Read response
OutputList.LoadFromStream(Process.Output);
Response := OutputList.Text;
WriteLn('[DEBUG] GetLatestReleaseTag: Curl exit status: ', Process.ExitStatus);
WriteLn('[DEBUG] GetLatestReleaseTag: Response length: ', Length(Response), ' bytes');
if (Process.ExitStatus = 0) and (Response <> '') then
begin
WriteLn('[DEBUG] GetLatestReleaseTag: Parsing JSON response...');
// Validate response is JSON before parsing (to handle GitHub API errors/rate limiting)
if (Length(Response) > 0) and ((Response[1] = '{') or (Response[1] = '[')) then
begin
JSONData := GetJSON(Response);
try
if Assigned(JSONData) and (JSONData is TJSONObject) then
begin
WriteLn('[DEBUG] GetLatestReleaseTag: Valid JSON object received');
JSONObject := TJSONObject(JSONData);
Result := JSONObject.Get('tag_name', '');
WriteLn('[DEBUG] GetLatestReleaseTag: tag_name = "', Result, '"');
end
else
WriteLn('[ERROR] GetLatestReleaseTag: JSON data is not a valid object');
finally
JSONData.Free;
end;
end
else
begin
WriteLn('[ERROR] GetLatestReleaseTag: API returned non-JSON response (possibly rate limited or error)');
WriteLn('[ERROR] GetLatestReleaseTag: Response preview: ', Copy(Response, 1, 200));
end;
end
else
begin
WriteLn('[ERROR] GetLatestReleaseTag: Failed to get response (exit: ', Process.ExitStatus, ', response empty: ', Response = '', ')');
if Response <> '' then
WriteLn('[ERROR] GetLatestReleaseTag: Response content: ', Copy(Response, 1, 200));
end;
except
on E: Exception do
begin
WriteLn('[ERROR] GetLatestReleaseTag: Exception - ', E.ClassName, ': ', E.Message);
if not ASilent then
ShowMessage('Error getting latest release: ' + E.Message + sLineBreak +
'Check your internet connection and if curl is installed.');
end;
end;
finally
OutputList.Free;
Process.Free;
end;
end;
function TOptiscalerTab.FetchManifest(ASilent: Boolean; out AStableVer, AStableURL, AEdgeVer, AEdgeURL: string): Boolean;
var
Process: TProcess;
OutputList: TStringList;
Response: string;
JSONData: TJSONData;
JSONObject, StableObj, EdgeObj: TJSONObject;
begin
Result := False;
AStableVer := '';
AStableURL := '';
AEdgeVer := '';
AEdgeURL := '';
Process := TProcess.Create(nil);
OutputList := TStringList.Create;
try
try
WriteLn('[DEBUG] FetchManifest: Fetching from ', URL_OPTISCALER_MANIFEST);
Process.Executable := 'curl';
Process.Parameters.Add('-s');
Process.Parameters.Add('-L');
Process.Parameters.Add(URL_OPTISCALER_MANIFEST);
Process.Options := [poWaitOnExit, poUsePipes];
Process.Execute;
OutputList.LoadFromStream(Process.Output);
Response := OutputList.Text;
if (Process.ExitStatus = 0) and (Response <> '') then
begin
if (Length(Response) > 0) and (Response[1] = '{') then
begin
JSONData := GetJSON(Response);
try
if Assigned(JSONData) and (JSONData is TJSONObject) then
begin
JSONObject := TJSONObject(JSONData);
StableObj := TJSONObject(JSONObject.Find('stable'));
if Assigned(StableObj) then
begin
AStableVer := StableObj.Get('version', '');
AStableURL := StableObj.Get('url', '');
end;
EdgeObj := TJSONObject(JSONObject.Find('edge'));
if Assigned(EdgeObj) then
begin
AEdgeVer := EdgeObj.Get('version', '');
AEdgeURL := EdgeObj.Get('url', '');
end;
Result := (AStableVer <> '') and (AEdgeVer <> '');
end;
finally
JSONData.Free;
end;
end;
end;
except
on E: Exception do
begin
WriteLn('[ERROR] FetchManifest: Exception - ', E.ClassName, ': ', E.Message);
if not ASilent then
ShowMessage('Error getting OptiScaler manifest: ' + E.Message);
end;
end;
finally
OutputList.Free;
Process.Free;
end;
end;
function TOptiscalerTab.GetOptiScalerStableTag(ASilent: Boolean = False): string;
var
StableVer, StableURL, EdgeVer, EdgeURL: string;
begin
Result := '';
if FetchManifest(ASilent, StableVer, StableURL, EdgeVer, EdgeURL) then
begin
FOptiStableVersion := StableVer;
FOptiStableURL := StableURL;
FOptiEdgeVersion := EdgeVer;
FOptiEdgeURL := EdgeURL;
Result := StableVer;
end;
end;
function TOptiscalerTab.GetOptiScalerPreReleaseTag(ASilent: Boolean = False): string;
var
StableVer, StableURL, EdgeVer, EdgeURL: string;
begin
Result := '';
if FetchManifest(ASilent, StableVer, StableURL, EdgeVer, EdgeURL) then
begin
FOptiStableVersion := StableVer;
FOptiStableURL := StableURL;
FOptiEdgeVersion := EdgeVer;
FOptiEdgeURL := EdgeURL;
Result := EdgeVer;
end;
end;
function TOptiscalerTab.DownloadFile(const AURL, ADestFile: string): Boolean;
var
Process: TProcess;
OutputList: TStringList;
begin
Result := False;
Process := TProcess.Create(nil);
OutputList := TStringList.Create;
try
try
WriteLn('[DEBUG] DownloadFile: Starting download');
WriteLn('[DEBUG] DownloadFile: URL = ', AURL);
WriteLn('[DEBUG] DownloadFile: Destination = ', ADestFile);
UpdateStatus('Downloading file...');
// Use curl to download file with progress
Process.Executable := 'curl';
Process.Parameters.Add('-L'); // Follow redirects
Process.Parameters.Add('-#'); // Show progress bar
Process.Parameters.Add('-o');
Process.Parameters.Add(ADestFile);
Process.Parameters.Add('-A'); // User agent
Process.Parameters.Add('Goverlay/1.6 (Linux; Flatpak-compatible)');
Process.Parameters.Add(AURL);
// Don't use poWaitOnExit - we'll wait manually while processing UI events
Process.Options := [poUsePipes];
WriteLn('[DEBUG] DownloadFile: Executing curl...');
Process.Execute;
// Wait for download to complete while keeping UI responsive
while Process.Running do
begin
Application.ProcessMessages; // Keep UI responsive
Sleep(100); // Small delay to avoid excessive CPU usage
end;
WriteLn('[DEBUG] DownloadFile: Curl finished with exit status: ', Process.ExitStatus);
// Read any output (curl progress goes to stderr)
if Process.Stderr.NumBytesAvailable > 0 then
OutputList.LoadFromStream(Process.Stderr);
// Check if download succeeded
if (Process.ExitStatus = 0) and FileExists(ADestFile) then
begin
WriteLn('[DEBUG] DownloadFile: Download successful, file exists at: ', ADestFile);
Result := True;
UpdateProgress(50); // Mark download complete at 50%
end
else
begin
if Process.ExitStatus <> 0 then
begin
WriteLn('[ERROR] DownloadFile: Curl failed with exit code: ', Process.ExitStatus);
ShowMessage('Error downloading file: curl exited with code ' + IntToStr(Process.ExitStatus) + sLineBreak +
'URL: ' + AURL + sLineBreak +
'Check your internet connection and if curl is installed.');
end
else if not FileExists(ADestFile) then
begin
WriteLn('[ERROR] DownloadFile: File does not exist after download: ', ADestFile);
ShowMessage('Error: Downloaded file does not exist.' + sLineBreak +
'URL: ' + AURL);
end;
end;
except
on E: Exception do
begin
WriteLn('[ERROR] DownloadFile: Exception - ', E.ClassName, ': ', E.Message);
ShowMessage('Error downloading file: ' + E.Message + sLineBreak +
'URL: ' + AURL + sLineBreak +
'Check your internet connection and if curl is installed.');
end;
end;
finally
OutputList.Free;
Process.Free;
end;
end;
function TOptiscalerTab.ExtractZip(const AZipFile, ADestPath: string): Boolean;
var
UnZipper: TUnZipper;
begin
Result := False;
UnZipper := TUnZipper.Create;
try
try
UnZipper.FileName := AZipFile;
UnZipper.OutputPath := ADestPath;
UnZipper.Examine;
UnZipper.UnZipAllFiles;
Result := True;
except
on E: Exception do
ShowMessage('Error extracting ZIP: ' + E.Message);
end;
finally
UnZipper.Free;
end;
end;
function TOptiscalerTab.Extract7z(const A7zFile, ADestPath: string): Boolean;
var
Process: TProcess;
OutputLines: TStringList;
StdoutOutput, StderrOutput: string;
FileInfo: TSearchRec;
FullCommand: string;
begin
Result := False;
Process := TProcess.Create(nil);
OutputLines := TStringList.Create;
try
try
WriteLn('[DEBUG] Extract7z: Starting 7z extraction');
WriteLn('[DEBUG] Extract7z: Source file = ', A7zFile);
WriteLn('[DEBUG] Extract7z: Destination path = ', ADestPath);
WriteLn('[DEBUG] Extract7z: File exists = ', FileExists(A7zFile));
// Check file size if exists
if FileExists(A7zFile) then
begin
if FindFirst(A7zFile, faAnyFile, FileInfo) = 0 then
begin
WriteLn('[DEBUG] Extract7z: File size = ', FileInfo.Size, ' bytes');
FindClose(FileInfo);
end;
end
else
begin
WriteLn('[ERROR] Extract7z: Source file does not exist!');
ShowMessage('Error: 7z file not found at: ' + A7zFile);
Exit;
end;
WriteLn('[DEBUG] Extract7z: Destination directory exists = ', DirectoryExists(ADestPath));
Process.Executable := FindDefaultExecutablePath('7z');
Process.Parameters.Add('x');
Process.Parameters.Add('-y'); // Yes to all questions
Process.Parameters.Add('-o' + ADestPath);
// Exclude bgmod / fgmod files if they already exist (to preserve user's configuration)
if FileExists(IncludeTrailingPathDelimiter(ADestPath) + 'bgmod') then
begin
Process.Parameters.Add('-xr!bgmod');
WriteLn('[DEBUG] Extract7z: Excluding bgmod from extraction (file already exists)');
end;
if FileExists(IncludeTrailingPathDelimiter(ADestPath) + 'bgmod.conf') then
begin
Process.Parameters.Add('-xr!bgmod.conf');
WriteLn('[DEBUG] Extract7z: Excluding bgmod.conf from extraction (file already exists)');
end;
if FileExists(IncludeTrailingPathDelimiter(ADestPath) + 'fgmod') then
begin
Process.Parameters.Add('-xr!fgmod');
WriteLn('[DEBUG] Extract7z: Excluding fgmod from extraction (file already exists)');
end;
if FileExists(IncludeTrailingPathDelimiter(ADestPath) + 'fgmod.sh') then
begin
Process.Parameters.Add('-xr!fgmod.sh');
WriteLn('[DEBUG] Extract7z: Excluding fgmod.sh from extraction (file already exists)');
end;
Process.Parameters.Add(A7zFile);
Process.Options := [poWaitOnExit, poUsePipes];
// Build full command string for debugging
FullCommand := '7z x -y -o' + ADestPath + ' ' + A7zFile;
WriteLn('[DEBUG] Extract7z: Full command = ', FullCommand);
WriteLn('[DEBUG] Extract7z: Executing...');
Process.Execute;
WriteLn('[DEBUG] Extract7z: Process completed');
WriteLn('[DEBUG] Extract7z: Exit status = ', Process.ExitStatus);
// Capture stdout output
if Process.Output.NumBytesAvailable > 0 then
begin
OutputLines.LoadFromStream(Process.Output);
StdoutOutput := OutputLines.Text;
WriteLn('[DEBUG] Extract7z: stdout output:');
WriteLn(StdoutOutput);
end
else
WriteLn('[DEBUG] Extract7z: No stdout output');
// Capture stderr output
if Process.Stderr.NumBytesAvailable > 0 then
begin
OutputLines.Clear;
OutputLines.LoadFromStream(Process.Stderr);
StderrOutput := OutputLines.Text;
WriteLn('[ERROR] Extract7z: stderr output:');
WriteLn(StderrOutput);
end
else
WriteLn('[DEBUG] Extract7z: No stderr output');
Result := Process.ExitStatus = 0;
if not Result then
begin
WriteLn('[ERROR] Extract7z: Extraction failed with exit code ', Process.ExitStatus);
WriteLn('[ERROR] Extract7z: 7z exit code 2 typically means: fatal error, file not found, or invalid archive');
ShowMessage('Error extracting 7z file. Exit code: ' + IntToStr(Process.ExitStatus) +
sLineBreak + sLineBreak +
'Check terminal output for details.' + sLineBreak +
'File: ' + A7zFile);
end
else
WriteLn('[DEBUG] Extract7z: Extraction completed successfully');
except
on E: Exception do
begin
WriteLn('[ERROR] Extract7z: Exception - ', E.ClassName, ': ', E.Message);
ShowMessage('Error executing 7z: ' + E.Message);
end;
end;
finally
OutputLines.Free;
Process.Free;
end;
end;
procedure TOptiscalerTab.CopyDirectory(const ASource, ADest: string);
var
SearchRec: TSearchRec;
SourcePath, DestPath: string;
SourceFile, DestFile: string;
begin
if not DirectoryExists(ADest) then
ForceDirectories(ADest);
SourcePath := IncludeTrailingPathDelimiter(ASource);
DestPath := IncludeTrailingPathDelimiter(ADest);
if FindFirst(SourcePath + '*', faAnyFile, SearchRec) = 0 then
begin
try
repeat
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
if (SearchRec.Attr and faDirectory) = faDirectory then
begin
// Recursive directory copy
CopyDirectory(SourcePath + SearchRec.Name, DestPath + SearchRec.Name);
end
else
begin
// File copy with permission preservation for .sh files
SourceFile := SourcePath + SearchRec.Name;
DestFile := DestPath + SearchRec.Name;
// Copy file
if not CopyFile(SourceFile, DestFile) then
ShowMessage('Error copying file: ' + SearchRec.Name);
// If it's a .sh file, make it executable
if LowerCase(ExtractFileExt(SearchRec.Name)) = '.sh' then
begin
fpChmod(DestFile, &755); // rwxr-xr-x
end;
end;
end;
until FindNext(SearchRec) <> 0;
finally
FindClose(SearchRec);
end;
end;
end;
function TOptiscalerTab.FetchFakeNvapiLatest(out ATag, AURL: string): Boolean;
var
Process: TProcess;
OutputList: TStringList;
Response: string;
JSONData: TJSONData;
JSONObject, AssetObj: TJSONObject;
AssetsArray: TJSONArray;
i: Integer;
begin
Result := False;
ATag := '';
AURL := '';
Process := TProcess.Create(nil);
OutputList := TStringList.Create;
try
try
WriteLn('[DEBUG] FetchFakeNvapiLatest: Fetching from ', URL_FAKENVAPI_API);
Process.Executable := 'curl';
Process.Parameters.Add('-s');
Process.Parameters.Add('-L');
Process.Parameters.Add('-A');
Process.Parameters.Add('Goverlay/1.6 (Linux; Flatpak-compatible)');
Process.Parameters.Add(URL_FAKENVAPI_API);
Process.Options := [poWaitOnExit, poUsePipes];
Process.Execute;
OutputList.LoadFromStream(Process.Output);
Response := OutputList.Text;
if (Process.ExitStatus = 0) and (Response <> '') then
begin
if (Length(Response) > 0) and (Response[1] = '{') then
begin
JSONData := GetJSON(Response);
try
if Assigned(JSONData) and (JSONData is TJSONObject) then
begin
JSONObject := TJSONObject(JSONData);
ATag := JSONObject.Get('tag_name', '');
AssetsArray := TJSONArray(JSONObject.Find('assets'));
if Assigned(AssetsArray) then
begin
for i := 0 to AssetsArray.Count - 1 do
begin
AssetObj := TJSONObject(AssetsArray.Items[i]);
if Assigned(AssetObj) and SameText(ExtractFileExt(AssetObj.Get('name', '')), '.7z') then
begin
AURL := AssetObj.Get('browser_download_url', '');
Break;
end;
end;
end;
Result := (ATag <> '') and (AURL <> '');
end;
finally
JSONData.Free;
end;
end;
end;
except
on E: Exception do
WriteLn('[ERROR] FetchFakeNvapiLatest: Exception - ', E.ClassName, ': ', E.Message);
end;
finally
OutputList.Free;
Process.Free;
end;
end;
function TOptiscalerTab.FetchVarsTxt(out AFsrStable, AFsrEdge, AXessStable, AXessEdge: string): Boolean;
var
Process: TProcess;
OutputList: TStringList;
i: Integer;
Line: string;
SepPos: Integer;
Key, Value: string;
begin
Result := False;
AFsrStable := '';
AFsrEdge := '';
AXessStable := '';
AXessEdge := '';
Process := TProcess.Create(nil);
OutputList := TStringList.Create;
try
try
Process.Executable := 'curl';
Process.Parameters.Add('-s');
Process.Parameters.Add('-L');
Process.Parameters.Add('-A');
Process.Parameters.Add('Goverlay/1.6 (Linux; Flatpak-compatible)');
Process.Parameters.Add('https://raw.githubusercontent.com/benjamimgois/OptiScaler-builds/nightly-action/vars.txt');
Process.Options := [poWaitOnExit, poUsePipes];
Process.Execute;
OutputList.LoadFromStream(Process.Output);
if Process.ExitStatus = 0 then
begin
for i := 0 to OutputList.Count - 1 do
begin
Line := Trim(OutputList[i]);
SepPos := Pos('=', Line);
if SepPos > 0 then
begin
Key := Trim(Copy(Line, 1, SepPos - 1));
Value := Trim(Copy(Line, SepPos + 1, Length(Line)));
if SameText(Key, 'fsrstable') then
AFsrStable := Value
else if SameText(Key, 'fsredge') then
AFsrEdge := Value
else if SameText(Key, 'xessstable') then
AXessStable := Value
else if SameText(Key, 'xessedge') then
AXessEdge := Value;
end;
end;
Result := True;
end;
except
on E: Exception do
WriteLn('[ERROR] FetchVarsTxt: Exception - ', E.ClassName, ': ', E.Message);
end;
finally
OutputList.Free;
Process.Free;
end;
end;
function TOptiscalerTab.ReadCachedOptiScalerVersion: string;
var
VarsFilePath: string;
VarsFile: TextFile;
Line, Key, Value: string;
SepPos: Integer;
IsStable: Boolean;
begin
Result := '';
IsStable := True;
if Assigned(FOptVersionComboBox) and (FOptVersionComboBox.ItemIndex = 1) then
IsStable := False;
VarsFilePath := IncludeTrailingPathDelimiter(GetBGModOriginalPathForChannel(IsStable)) + 'goverlay.vars';
if not FileExists(VarsFilePath) then Exit;
try
AssignFile(VarsFile, VarsFilePath);
Reset(VarsFile);
try
while not Eof(VarsFile) do
begin
ReadLn(VarsFile, Line);
if (Length(Line) > 0) and (Line[1] = '#') then Continue;
SepPos := Pos('=', Line);
if SepPos > 0 then
begin
Key := Copy(Line, 1, SepPos - 1);
Value := Copy(Line, SepPos + 1, Length(Line));
if SameText(Key, 'OptiScalerVersion') then
begin
Result := Trim(Value);
Exit;
end;
end;
end;
finally
CloseFile(VarsFile);
end;
except
on E: Exception do
WriteLn('[WARN] ReadCachedOptiScalerVersion: ', E.Message);
end;