-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJamBatch.pas
More file actions
1320 lines (1201 loc) · 39.7 KB
/
JamBatch.pas
File metadata and controls
1320 lines (1201 loc) · 39.7 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 JamBatch;
interface
uses
System.IOUtils, Winapi.Windows, Winapi.Messages, System.SysUtils,
System.Generics.Collections,
System.Classes, Vcl.Dialogs, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.NumberBox, Vcl.Samples.Spin,
System.Threading, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ToolWin,
jamGeneral, jamPaletteDetector, jamSW, jamHW, System.types, strutils,
Vcl.Menus, generalhelpers, System.Win.Registry, Winapi.ShellAPI;
type
TTextureSimpOptions = (quad, seed, mean, neighbour);
// Batch-run lifecycle state for each item. Drives the row colour
// and status text in the ListView.
TJamBatchStatus = (bsIdle, bsPending, bsProcessing, bsDone, bsFailed);
TJamOptions = record
Simplify: TTextureSimpOptions;
Blur: integer;
simplifyThresh: integer;
doPals: boolean;
doSimplePal: boolean;
doSoftenMatte: boolean;
end;
TJamBatchItem = class
filepath: string;
filename: string;
outputpath: string;
inputType: TJamType;
outputType: TJamType;
TextureOptions: TJamOptions;
status: TJamBatchStatus;
constructor Create(const aFile: string);
end;
type
TJamBatchForm = class(TForm)
panel: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
LabelOutputFormat: TLabel;
lblProgress: TLabel;
cbSimplify: TComboBox;
cbOutputFormat: TComboBox;
chkSimpPalette: TCheckBox;
chkDoMatte: TCheckBox;
chkDoPalette: TCheckBox;
chkScanAllFolders: TCheckBox;
seBlur: TNumberBox;
seThreshold: TNumberBox;
strJamFile: TEdit;
edtOutputPath: TEdit;
edtFilename: TEdit;
GroupBox1: TGroupBox;
GroupBoxTools: TGroupBox;
btnBrowseOutput: TButton;
btnRun: TButton;
btnCancel: TButton;
btnAddFile: TButton;
btnDel: TButton;
btnScanFolder: TButton;
btnConvertTrack: TButton;
lvBatch: TListView;
Panel1: TPanel;
Panel2: TPanel;
StatusBarPanel: TPanel;
Splitter1: TSplitter;
pbBatch: TProgressBar;
jamBatchPopup: TPopupMenu;
AddFiles01: TMenuItem;
AddScanFolder1: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
DeleteItems1: TMenuItem;
mnuOpenFolder: TMenuItem;
mnuRetryFailed: TMenuItem;
openTrack: TOpenDialog;
procedure btnAddFileClick(Sender: TObject);
procedure btnScanFolderClick(Sender: TObject);
procedure btnDelClick(Sender: TObject);
procedure btnRunClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure lvBatchSelectItem(Sender: TObject; Item: TListItem;
Selected: boolean);
procedure cbSimplifyChange(Sender: TObject);
procedure cbOutputFormatChange(Sender: TObject);
procedure seThresholdChange(Sender: TObject);
procedure seBlurChange(Sender: TObject);
procedure edtOutputPathChange(Sender: TObject);
procedure chkSimpPaletteClick(Sender: TObject);
procedure chkDoMatteClick(Sender: TObject);
procedure chkDoPaletteClick(Sender: TObject);
function GetJamType(jamType: TJamType): string;
function GetSimplifyOptions(opts: TTextureSimpOptions): string;
procedure lvBatchKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lvBatchDblClick(Sender: TObject);
procedure jamBatchPopupPopup(Sender: TObject);
procedure lvBatchClick(Sender: TObject);
procedure btnBrowseOutputClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtFilenameChange(Sender: TObject);
procedure DeleteItems1Click(Sender: TObject);
procedure btnConvertTrackClick(Sender: TObject);
procedure mnuOpenFolderClick(Sender: TObject);
procedure mnuRetryFailedClick(Sender: TObject);
procedure lvBatchCustomDrawItem(Sender: TCustomListView; Item: TListItem;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure lvBatchCustomDrawSubItem(Sender: TCustomListView;
Item: TListItem; SubItem: Integer; State: TCustomDrawState;
var DefaultDraw: Boolean);
private
// O(1) duplicate detection — paired with BatchList. Normalised lower-case
// filepath → item. Kept in sync in AddBatchItem / btnDelClick / OnClear.
FPathIndex: TDictionary<string, TJamBatchItem>;
// Batch progress counters (UI-thread only)
FBatchTotal: integer;
FBatchDone: integer;
FBatchFailed: integer;
// Set by btnCancelClick (UI thread); read by the TTask worker loop
// between items. Plain Boolean reads/writes are atomic on x86/x64
// so no interlock is needed for this one-shot signalling use — the
// worst case is a one-iteration delay before the worker notices.
FCancelRequested: Boolean;
FBatchRunning: Boolean;
FLastRunSummary: string;
procedure RefreshListView;
procedure ConvertJam;
procedure ConvertSingleItem(Item: TJamBatchItem; DoPalette: Boolean);
procedure UpdateListViewItem(li: TListItem);
procedure UpdateItemRow(Item: TJamBatchItem);
procedure RefreshSelectedItems;
procedure PopulateDetails(const Items: TArray<TJamBatchItem>);
procedure ApplyDetailsToItems(const Items: TArray<TJamBatchItem>);
procedure OnItemProcessed(Item: TJamBatchItem);
function GetSelectedBatchItems: TArray<TJamBatchItem>;
function ItemExists(const APath: string): Boolean;
function AddBatchItem(const FilePath: string): TJamBatchItem;
function DefaultOutputType(InputType: TJamType): TJamType;
function DefaultOutputPath(const SourcePath: string;
OutputType: TJamType): string;
function NormalisePath(const APath: string): string;
procedure EnsurePathIndex;
procedure SetItemStatus(Item: TJamBatchItem; NewStatus: TJamBatchStatus);
procedure UpdateBatchProgress;
function StatusText(S: TJamBatchStatus): string;
procedure ClearCompletedItems;
procedure UpdateUIState;
// Queue-from-worker helpers. Pass Item + NewStatus as parameters so
// each call's values are captured per-invocation — the closure would
// otherwise alias the loop variable in the caller and misreport.
procedure QueueStatusChange(Item: TJamBatchItem;
NewStatus: TJamBatchStatus);
procedure QueueItemComplete(Item: TJamBatchItem; Success: Boolean);
// Remember last folder per dialog type (add-files, scan-folder, output)
// in the existing HKCU\Software\JKVFX\JamEditor key. Values are written
// immediately when the user picks a folder, so they persist even if the
// app is killed.
function LoadBatchFolder(const ValueName: string): string;
procedure SaveBatchFolder(const ValueName, Folder: string);
function OutputTypeFromComboIndex(Idx: Integer): TJamType;
function ComboIndexForOutputType(JT: TJamType): Integer;
procedure OpenFolderForItem(Item: TJamBatchItem);
function AnyFailed: Boolean;
function StatusColor(S: TJamBatchStatus): TColor;
public
destructor Destroy; override;
end;
var
JamBatchForm: TJamBatchForm;
BatchList: TObjectList<TJamBatchItem>;
procedure InitBatchList;
procedure FreeBatchList;
implementation
uses
mainform; // only for LoadJam on double-click — kept in implementation
// uses to avoid a circular unit reference
{$R *.dfm}
constructor TJamBatchItem.Create(const aFile: string);
begin
inherited Create;
filepath := aFile;
outputpath := ChangeFileExt(aFile, ''); // or wherever you like
inputType := jamGP3SW;
outputType := jamGP3HW;
with TextureOptions do
begin
Simplify := neighbour;
Blur := intBlurThreshold;
simplifyThresh := intSimplifyThreshold;
doSimplePal := False;
doSoftenMatte := False;
end;
status := bsIdle;
end;
procedure InitBatchList;
begin
BatchList := TObjectList<TJamBatchItem>.Create(True);
end;
procedure FreeBatchList;
begin
BatchList.Free;
end;
destructor TJamBatchForm.Destroy;
begin
FreeAndNil(FPathIndex);
inherited;
end;
function TJamBatchForm.NormalisePath(const APath: string): string;
begin
Result := ExpandFileName(APath).ToLower;
end;
procedure TJamBatchForm.EnsurePathIndex;
var
itm: TJamBatchItem;
begin
if FPathIndex <> nil then Exit;
FPathIndex := TDictionary<string, TJamBatchItem>.Create;
// Populate from any items already in BatchList (defensive)
for itm in BatchList do
FPathIndex.AddOrSetValue(NormalisePath(itm.filepath), itm);
end;
function TJamBatchForm.ItemExists(const APath: string): Boolean;
begin
EnsurePathIndex;
Result := FPathIndex.ContainsKey(NormalisePath(APath));
end;
function TJamBatchForm.DefaultOutputType(InputType: TJamType): TJamType;
begin
// "Convert to the opposite" default: SW → HW, HW → SW, GP2 → GP3SW
case InputType of
jamGP3SW: Result := jamGP3HW;
jamGP3HW: Result := jamGP3SW;
jamGP2: Result := jamGP3SW;
else
Result := InputType;
end;
end;
function TJamBatchForm.DefaultOutputPath(const SourcePath: string;
OutputType: TJamType): string;
var
dir: string;
begin
dir := ExtractFilePath(SourcePath);
// GP3 SW and HW share the same pair of Gp3Jams / Gp3JamsH folders;
// flip between them so output lands in the "other" folder by default.
if OutputType in [jamGP3SW, jamGP3HW] then
Result := ToggleGP3JamsFolder(dir)
else
Result := dir;
end;
function TJamBatchForm.AddBatchItem(const FilePath: string): TJamBatchItem;
begin
EnsurePathIndex;
if FPathIndex.ContainsKey(NormalisePath(FilePath)) then
Exit(nil);
Result := TJamBatchItem.Create(FilePath);
Result.inputType := TJamPaletteDetector.Instance.Detect(FilePath, True);
Result.outputType := DefaultOutputType(Result.inputType);
Result.filename := ExtractFileName(FilePath);
Result.outputpath := DefaultOutputPath(FilePath, Result.outputType);
BatchList.Add(Result);
FPathIndex.Add(NormalisePath(FilePath), Result);
end;
procedure TJamBatchForm.jamBatchPopupPopup(Sender: TObject);
begin
DeleteItems1.Enabled := lvBatch.SelCount > 0;
mnuOpenFolder.Enabled := lvBatch.SelCount > 0;
mnuRetryFailed.Enabled := AnyFailed and not FBatchRunning;
end;
function TJamBatchForm.GetSelectedBatchItems: TArray<TJamBatchItem>;
var
i: integer;
tmp: TList<TJamBatchItem>;
begin
tmp := TList<TJamBatchItem>.Create;
try
for i := 0 to lvBatch.Items.Count - 1 do
if lvBatch.Items[i].Selected then
tmp.Add(TJamBatchItem(lvBatch.Items[i].Data));
Result := tmp.ToArray;
finally
tmp.Free;
end;
end;
procedure TJamBatchForm.btnAddFileClick(Sender: TObject);
var
dlg: TOpenDialog;
fn: string;
begin
dlg := TOpenDialog.Create(nil);
try
dlg.Filter := 'JAM files|*.jam;*.jip';
dlg.Options := dlg.Options + [ofAllowMultiSelect];
dlg.InitialDir := LoadBatchFolder('BatchAddFilesPath');
if dlg.Execute then
begin
ClearCompletedItems;
for fn in dlg.Files do
AddBatchItem(fn);
if dlg.Files.Count > 0 then
SaveBatchFolder('BatchAddFilesPath', ExtractFilePath(dlg.Files[0]));
end;
RefreshListView;
finally
dlg.Free;
end;
end;
procedure TJamBatchForm.btnBrowseOutputClick(Sender: TObject);
var
dlg: TFileOpenDialog;
begin
dlg := TFileOpenDialog.Create(nil);
try
dlg.Options := dlg.Options + [fdoPickFolders, fdoPathMustExist];
dlg.Title := 'Select output folder';
dlg.DefaultFolder := LoadBatchFolder('BatchOutputPath');
if dlg.Execute then
begin
edtOutputPath.Text := dlg.filename;
edtOutputPath.SetFocus;
ApplyDetailsToItems(GetSelectedBatchItems);
SaveBatchFolder('BatchOutputPath', dlg.filename);
end;
finally
dlg.Free;
end;
end;
procedure TJamBatchForm.btnDelClick(Sender: TObject);
var
i: integer;
idxs: TList<integer>;
itm: TJamBatchItem;
begin
if lvBatch.SelCount = 0 then Exit;
if MessageDlg('Remove the selected item(s)?', mtConfirmation, [mbYes, mbNo],
0) <> mrYes then
Exit;
EnsurePathIndex;
idxs := TList<integer>.Create;
try
for i := 0 to lvBatch.Items.Count - 1 do
if lvBatch.Items[i].Selected then
idxs.Add(i);
idxs.Sort;
// remove highest to lowest so preceding indexes stay valid
for i := idxs.Count - 1 downto 0 do
begin
itm := BatchList[idxs[i]];
FPathIndex.Remove(NormalisePath(itm.filepath));
BatchList.Delete(idxs[i]); // TObjectList owns → frees item
end;
RefreshListView;
finally
idxs.Free;
end;
end;
function TJamBatchForm.LoadBatchFolder(const ValueName: string): string;
var
Reg: TRegistry;
begin
Result := '';
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKeyReadOnly(baseKeyPath) then
try
if Reg.ValueExists(ValueName) then
Result := Reg.ReadString(ValueName);
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
// Guard against stale paths pointing at folders that no longer exist.
if (Result <> '') and not DirectoryExists(Result) then
Result := '';
end;
procedure TJamBatchForm.SaveBatchFolder(const ValueName, Folder: string);
var
Reg: TRegistry;
begin
if Folder = '' then Exit;
Reg := TRegistry.Create(KEY_WRITE);
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(baseKeyPath, True) then
try
Reg.WriteString(ValueName, Folder);
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
procedure SetChildrenEnabled(Parent: TWinControl; Enabled: Boolean);
// VCL's Enabled-cascade works for input routing but doesn't force a visual
// repaint through nested TPanels — their children can end up looking active
// even when the outer GroupBox is disabled. Walk the tree and set Enabled
// directly on every leaf TControl so each repaints in its disabled style.
var
i: integer;
child: TControl;
begin
for i := 0 to Parent.ControlCount - 1 do
begin
child := Parent.Controls[i];
child.Enabled := Enabled;
if child is TWinControl then
SetChildrenEnabled(TWinControl(child), Enabled);
end;
end;
procedure TJamBatchForm.UpdateUIState;
// Centralises enable/disable rules so selection / list / status changes all
// route through one place. Called by: selection, add, delete, clear,
// radio-click, and SetItemStatus (so Run disables when all items finish).
var
selCount, readyCount, swSelCount: integer;
i: integer;
itm: TJamBatchItem;
allSelectedAreSW: Boolean;
begin
selCount := 0;
swSelCount := 0;
readyCount := 0;
for i := 0 to BatchList.Count - 1 do
begin
itm := BatchList[i];
// "Ready to convert" = anything that hasn't already succeeded. We keep
// bsFailed items eligible so the user can retry after fixing the cause.
if itm.status <> bsDone then
Inc(readyCount);
end;
// Selection-driven counts (walk the ListView, not BatchList — order may
// differ after sort).
for i := 0 to lvBatch.Items.Count - 1 do
if lvBatch.Items[i].Selected and (lvBatch.Items[i].Data <> nil) then
begin
Inc(selCount);
itm := TJamBatchItem(lvBatch.Items[i].Data);
if itm.outputType in [jamGP2, jamGP3SW] then
Inc(swSelCount);
end;
allSelectedAreSW := (selCount > 0) and (swSelCount = selCount);
// During a batch run we lock down edits entirely — the user can only
// watch progress or hit Cancel.
btnDel.Enabled := (selCount > 0) and not FBatchRunning;
DeleteItems1.Enabled := (selCount > 0) and not FBatchRunning;
btnAddFile.Enabled := not FBatchRunning;
btnScanFolder.Enabled := not FBatchRunning;
btnConvertTrack.Enabled := not FBatchRunning;
edtOutputPath.Enabled := (selCount > 0) and not FBatchRunning;
btnBrowseOutput.Enabled := (selCount > 0) and not FBatchRunning;
edtFilename.Enabled := (selCount = 1) and not FBatchRunning;
// Input JAM field is read-only but grey it out when selection is
// non-singular so it doesn't look like an editable field with no value.
strJamFile.Enabled := selCount = 1;
cbOutputFormat.Enabled := (selCount > 0) and not FBatchRunning;
// Palette controls only meaningful when converting to a software JAM.
// Cascade Enabled through the nested panel so every child greys out
// visually, not just logically.
GroupBox1.Enabled := allSelectedAreSW and not FBatchRunning;
SetChildrenEnabled(GroupBox1, allSelectedAreSW and not FBatchRunning);
btnRun.Enabled := (readyCount > 0) and not FBatchRunning;
end;
procedure TJamBatchForm.ClearCompletedItems;
var
i: integer;
itm: TJamBatchItem;
removed: Boolean;
begin
// Remove any items that finished successfully on the previous run so the
// list doesn't accumulate stale results. Failed items are preserved so the
// user can see what went wrong and retry.
if BatchList.Count = 0 then Exit;
EnsurePathIndex;
removed := False;
for i := BatchList.Count - 1 downto 0 do
begin
itm := BatchList[i];
if itm.status = bsDone then
begin
FPathIndex.Remove(NormalisePath(itm.filepath));
BatchList.Delete(i); // TObjectList owns → frees item
removed := True;
end;
end;
if removed then
begin
FBatchTotal := 0;
FBatchDone := 0;
FLastRunSummary := ''; // New run starts fresh — clear any prior summary
UpdateBatchProgress;
RefreshListView;
end;
end;
procedure TJamBatchForm.btnScanFolderClick(Sender: TObject);
var
dlg: TFileOpenDialog;
Dir: string;
Files: TArray<string>;
f: string;
opt: TSearchOption;
begin
dlg := TFileOpenDialog.Create(nil);
try
dlg.Options := dlg.Options + [fdoPickFolders, fdoPathMustExist];
dlg.Title := 'Select folder to scan for JAMs';
dlg.DefaultFolder := LoadBatchFolder('BatchScanFolderPath');
if not dlg.Execute then Exit;
Dir := dlg.filename;
SaveBatchFolder('BatchScanFolderPath', Dir);
if chkScanAllFolders.Checked then
opt := TSearchOption.soAllDirectories
else
opt := TSearchOption.soTopDirectoryOnly;
Files := TDirectory.GetFiles(Dir, '*.jam', opt);
ClearCompletedItems;
for f in Files do
AddBatchItem(f);
RefreshListView;
finally
dlg.Free;
end;
end;
procedure TJamBatchForm.btnConvertTrackClick(Sender: TObject);
begin
end;
procedure TJamBatchForm.cbSimplifyChange(Sender: TObject);
begin
ApplyDetailsToItems(GetSelectedBatchItems);
end;
procedure TJamBatchForm.chkDoMatteClick(Sender: TObject);
begin
ApplyDetailsToItems(GetSelectedBatchItems);
end;
procedure TJamBatchForm.chkDoPaletteClick(Sender: TObject);
begin
ApplyDetailsToItems(GetSelectedBatchItems);
end;
procedure TJamBatchForm.chkSimpPaletteClick(Sender: TObject);
begin
ApplyDetailsToItems(GetSelectedBatchItems);
end;
procedure TJamBatchForm.edtOutputPathChange(Sender: TObject);
begin
ApplyDetailsToItems(GetSelectedBatchItems);
end;
procedure TJamBatchForm.lvBatchClick(Sender: TObject);
begin
UpdateUIState;
end;
procedure TJamBatchForm.FormShow(Sender: TObject);
begin
UpdateUIState;
end;
procedure TJamBatchForm.lvBatchKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// Ctrl+A → select all
if (Key = Ord('A')) and (Shift = [ssCtrl]) then
begin
lvBatch.Items.BeginUpdate;
try
for var i := 0 to lvBatch.Items.Count - 1 do
lvBatch.Items[i].Selected := True;
finally
lvBatch.Items.EndUpdate;
end;
Key := 0; // swallow
end
// Delete → confirm & remove
else if (Key = VK_DELETE) and (lvBatch.SelCount > 0) then
begin
btnDelClick(Sender);
Key := 0;
end;
end;
procedure TJamBatchForm.lvBatchSelectItem(Sender: TObject; Item: TListItem;
Selected: boolean);
var
sel: TList<TJamBatchItem>;
i: integer;
begin
sel := TList<TJamBatchItem>.Create;
try
for i := 0 to lvBatch.Items.Count - 1 do
if lvBatch.Items[i].Selected then
sel.Add(TJamBatchItem(lvBatch.Items[i].Data));
PopulateDetails(sel.ToArray);
finally
sel.Free;
end;
UpdateUIState;
end;
procedure TJamBatchForm.ConvertSingleItem(Item: TJamBatchItem;
DoPalette: Boolean);
// Handles one input/output type pair with the correct load/convert/save
// pattern. Always frees its bitmap objects, even on exception.
// Item.outputpath is the directory; Item.filename is the file name —
// SaveToFile needs the full path, so we combine them here.
var
JamFile, OldJamFile: TJamFile;
HWJamFile: THWJamFile;
outFile: string;
procedure ZeroPalettesIfRequested;
var
x: Integer;
begin
if not DoPalette then Exit;
for x := 0 to JamFile.FEntries.Count - 1 do
JamFile.ZeroPalette(x);
end;
begin
// Ensure the destination directory exists
checkPath(Item.outputpath);
// Build the full output file path
outFile := TPath.Combine(Item.outputpath, Item.filename);
// HW → SW/GP2: load HW, convert, save SW
if Item.inputType = jamGP3HW then
begin
if not (Item.outputType in [jamGP3SW, jamGP2]) then Exit;
JamFile := TJamFile.Create;
HWJamFile := THWJamFile.Create;
try
HWJamFile.LoadFromFile(Item.filepath);
JamFile.ConvertHWJam(HWJamFile, Item.outputType = jamGP2);
JamFile.SaveToFile(outFile, False);
finally
JamFile.Free;
HWJamFile.Free;
end;
Exit;
end;
// GP2 / GP3SW source — two sub-paths: → SW (with palette option) or → HW
if Item.inputType in [jamGP2, jamGP3SW] then
begin
if Item.outputType = jamGP3HW then
begin
HWJamFile := THWJamFile.Create;
try
HWJamFile.ConvertGpxJam(Item.filepath);
HWJamFile.SaveToFile(outFile);
finally
HWJamFile.Free;
end;
Exit;
end;
if Item.outputType in [jamGP2, jamGP3SW] then
begin
JamFile := TJamFile.Create;
OldJamFile := TJamFile.Create;
try
OldJamFile.LoadFromFile(Item.filepath, False);
JamFile.ConvertGpxJam(OldJamFile, Item.outputType = jamGP2);
ZeroPalettesIfRequested;
JamFile.SaveToFile(outFile, False);
finally
JamFile.Free;
OldJamFile.Free;
end;
end;
end;
end;
procedure TJamBatchForm.QueueStatusChange(Item: TJamBatchItem;
NewStatus: TJamBatchStatus);
begin
TThread.Queue(nil,
procedure
begin
SetItemStatus(Item, NewStatus);
end);
end;
procedure TJamBatchForm.QueueItemComplete(Item: TJamBatchItem; Success: Boolean);
begin
TThread.Queue(nil,
procedure
begin
if Success then
SetItemStatus(Item, bsDone)
else
begin
SetItemStatus(Item, bsFailed);
Inc(FBatchFailed);
end;
Inc(FBatchDone);
UpdateBatchProgress;
end);
end;
procedure TJamBatchForm.ConvertJam;
// See the big comment inside the TTask.Run block for the threading
// rationale.
var
pendingList: TList<TJamBatchItem>;
items: TArray<TJamBatchItem>;
doPalette: Boolean;
it: TJamBatchItem;
begin
if BatchList.Count = 0 then Exit;
// Build the ready-to-convert subset. Items that already succeeded stay
// bsDone; failed items get another shot.
pendingList := TList<TJamBatchItem>.Create;
try
for it in BatchList do
if it.status <> bsDone then
pendingList.Add(it);
items := pendingList.ToArray;
finally
pendingList.Free;
end;
if Length(items) = 0 then Exit;
doPalette := chkDoPalette.Checked;
for it in items do
it.status := bsPending;
FBatchTotal := Length(items);
FBatchDone := 0;
FBatchFailed := 0;
FCancelRequested := False;
FBatchRunning := True;
FLastRunSummary := '';
UpdateBatchProgress;
RefreshListView;
btnCancel.Enabled := True;
btnRun.Enabled := False;
// Run the conversion loop on a single worker thread via TTask.Run.
//
// Why not TParallel.For / multiple workers: the conversion code still
// touches shared globals (gpxPal, intPaletteID, boolRcrJam, the palette
// detector singleton). One worker at a time keeps those globals from
// being contested. True parallelism is a separate, larger refactor.
//
// Why run on a worker at all, if the conversion is still serial: keeping
// the long-running loop off the UI thread lets the VCL paint/click
// pipeline run uninterrupted — the list repaints smoothly, Cancel clicks
// are instant, and we don't have to sprinkle ProcessMessages through the
// loop (which was noticeably slower).
//
// GDI safety: THWJamFile.DrawSingleTexture no longer uses BitBlt — it
// copies pixels with ScanLine+Move, so worker-thread use is safe.
//
// User must not touch the main editor window while a batch is running,
// because the globals above are shared process-wide. UpdateUIState
// locks down the batch dialog itself during a run, but can't disable
// the main form — keep that in mind if the user reports weird palette
// glitches during a batch.
TTask.Run(
procedure
var
i: integer;
current: TJamBatchItem;
ok: Boolean;
begin
try
for i := 0 to High(items) do
begin
if FCancelRequested then
begin
// Roll any still-queued items back to Idle on the UI thread so
// they don't sit forever showing "Pending".
TThread.Queue(nil,
procedure
var
k: integer;
begin
for k := i to High(items) do
if items[k].status = bsPending then
SetItemStatus(items[k], bsIdle);
end);
Break;
end;
current := items[i];
QueueStatusChange(current, bsProcessing);
ok := False;
try
ConvertSingleItem(current, doPalette);
ok := True;
except
on E: Exception do
OutputDebugString(PChar(Format(
'Batch: conversion failed for %s: %s',
[current.filepath, E.Message])));
end;
QueueItemComplete(current, ok);
end;
finally
// Finalise on the UI thread — touch VCL state from here only.
TThread.Queue(nil,
procedure
var
succeeded: integer;
begin
FBatchRunning := False;
btnCancel.Enabled := False;
succeeded := FBatchDone - FBatchFailed;
if FCancelRequested then
FLastRunSummary := Format('Cancelled: %d / %d done',
[FBatchDone, FBatchTotal])
else if FBatchFailed > 0 then
FLastRunSummary := Format('Finished: %d ok, %d failed',
[succeeded, FBatchFailed])
else
FLastRunSummary := Format('Finished: %d / %d ok',
[succeeded, FBatchTotal]);
pbBatch.Visible := False;
lblProgress.Visible := True;
lblProgress.Caption := FLastRunSummary;
UpdateUIState;
end);
end;
end);
end;
procedure TJamBatchForm.DeleteItems1Click(Sender: TObject);
begin
btnDelClick(Sender);
end;
procedure TJamBatchForm.edtFilenameChange(Sender: TObject);
begin
if lvBatch.SelCount > 1 then
Exit;
ApplyDetailsToItems(GetSelectedBatchItems);
end;
procedure TJamBatchForm.btnRunClick(Sender: TObject);
begin
ConvertJam;
end;
procedure TJamBatchForm.btnCancelClick(Sender: TObject);
begin
// Signal the worker loop to stop between items. Current item finishes.
FCancelRequested := True;
btnCancel.Enabled := False;
lblProgress.Caption := lblProgress.Caption + ' — cancelling...';
end;
procedure TJamBatchForm.OpenFolderForItem(Item: TJamBatchItem);
var
folder: string;
begin
if Item = nil then Exit;
folder := ExtractFilePath(Item.filepath);
if (folder = '') or not DirectoryExists(folder) then Exit;
ShellExecute(Handle, 'open', PChar(folder), nil, nil, SW_SHOWNORMAL);
end;
procedure TJamBatchForm.mnuOpenFolderClick(Sender: TObject);
var
sel: TArray<TJamBatchItem>;
begin
sel := GetSelectedBatchItems;
if Length(sel) = 0 then Exit;
// For multi-select, just open the first distinct folder. Users rarely
// want many Explorer windows to fire at once.
OpenFolderForItem(sel[0]);
end;
procedure TJamBatchForm.mnuRetryFailedClick(Sender: TObject);
// Flip every bsFailed item back to bsIdle so the next Run Batch picks
// them up. ConvertJam already ignores bsDone items so this is all we need.
var
itm: TJamBatchItem;
any: Boolean;
begin
any := False;
for itm in BatchList do
if itm.status = bsFailed then
begin
itm.status := bsIdle;
any := True;
end;
if any then
begin
RefreshListView;
lvBatch.Invalidate;
end;
end;
function TJamBatchForm.AnyFailed: Boolean;
var
itm: TJamBatchItem;
begin
for itm in BatchList do
if itm.status = bsFailed then Exit(True);
Result := False;
end;
procedure TJamBatchForm.lvBatchDblClick(Sender: TObject);
// Double-click loads the clicked JAM into the main editor window so the
// user can inspect/edit it before (or instead of) converting. The main
// form's LoadJam handles both HW and SW formats internally.
var
sel: TArray<TJamBatchItem>;
path: string;
begin
sel := GetSelectedBatchItems;
if Length(sel) = 0 then Exit;
path := sel[0].filepath;
if not FileExists(path) then Exit;
FormMain.LoadJam(path);
// Bring the main window forward so the user sees the loaded JAM. The
// batch dialog stays open behind it — user can keep scrolling.
FormMain.BringToFront;
end;
procedure TJamBatchForm.cbOutputFormatChange(Sender: TObject);
begin
ApplyDetailsToItems(GetSelectedBatchItems);
UpdateUIState;
end;
function TJamBatchForm.OutputTypeFromComboIndex(Idx: Integer): TJamType;
begin
case Idx of
0: Result := jamGP2;
1: Result := jamGP3SW;
2: Result := jamGP3HW;
else
Result := jamGP3SW;
end;