-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprogram.cs
More file actions
733 lines (616 loc) · 26.9 KB
/
Copy pathprogram.cs
File metadata and controls
733 lines (616 loc) · 26.9 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
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using System.Text.RegularExpressions;
using NkiTool;
public class Program
{
private const string PluginDllName = "inNKX.wcx64";
public const int PK_PACK_SAVE_PATHS = 2;
public const int PK_SKIP = 0;
public const int PK_EXTRACT = 2;
public const int PK_OM_EXTRACT = 1;
public const int E_SUCCESS = 0;
public const int E_END_ARCHIVE = 10;
// Formats supportés
private static readonly HashSet<string> SupportedArchiveExtensions =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".nkx", ".nkr", ".nicnt", ".nks"
};
// --- STRUCTURES ---
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct tHeaderDataExW_WCXPlugin
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] public string hdArcNameW;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] public string hdFileNameW;
public int hdFlags;
public uint hdPackSize;
public uint hdPackSizeHigh;
public uint hdUnpSize;
public uint hdUnpSizeHigh;
public int hdHostOS;
public int hdFileCRC;
public int hdFileTime;
public int hdUnpVer;
public int hdMethod;
public int hdFileAttr;
public IntPtr hdCmtBuf;
public int hdCmtBufSize;
public int hdCmtSize;
public int hdCmtState;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)] public byte[] hdReserved;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct tOpenArchiveDataW_WCXPlugin
{
public IntPtr ArcName;
public int OpenMode;
public int OpenResult;
public IntPtr CmtBuf;
public int CmtBufSize;
public int CmtSize;
public int CmtState;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct PackDefaultParamStruct
{
public int size;
public uint PluginInterfaceVersionLow;
public uint PluginInterfaceVersionHi;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string DefaultIniName;
}
// --- DELEGATES ---
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public delegate int ProcessDataProcWDelegate(string FileName, int Size);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public delegate int ChangeVolProcWDelegate(string ArcName, int Mode);
private static ProcessDataProcWDelegate _processDataProc = new ProcessDataProcWDelegate(OnProcessData);
private static ChangeVolProcWDelegate _changeVolProc = new ChangeVolProcWDelegate(OnChangeVol);
private static int OnProcessData(string FileName, int Size) { return 1; }
private static int OnChangeVol(string ArcName, int Mode) { return 1; }
// --- IMPORTS ---
[DllImport(PluginDllName, CharSet = CharSet.Ansi)]
private static extern void PackSetDefaultParams(ref PackDefaultParamStruct dps);
[DllImport(PluginDllName, CharSet = CharSet.Unicode)]
private static extern int PackFilesW(string PackedFile, string? SubPath, string SrcPath, IntPtr AddList, int Flags);
[DllImport(PluginDllName, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenArchiveW(ref tOpenArchiveDataW_WCXPlugin OpenArchiveData);
[DllImport(PluginDllName, CharSet = CharSet.Unicode)]
private static extern int ReadHeaderExW(IntPtr hArc, ref tHeaderDataExW_WCXPlugin HeaderData);
[DllImport(PluginDllName, CharSet = CharSet.Unicode)]
private static extern int ProcessFileW(IntPtr hArc, int Operation, string? DestPath, string? DestName);
[DllImport(PluginDllName, CharSet = CharSet.Unicode)]
private static extern void SetProcessDataProcW(IntPtr hArc, ProcessDataProcWDelegate pProcessDataProc);
[DllImport(PluginDllName, CharSet = CharSet.Unicode)]
private static extern void SetChangeVolProcW(IntPtr hArc, ChangeVolProcWDelegate pChangeVolProc);
[DllImport(PluginDllName)]
private static extern int CloseArchive(IntPtr hArc);
private static string NormalizeArchivePath(string path)
{
if (string.IsNullOrWhiteSpace(path))
return string.Empty;
return path.Trim()
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar);
}
[STAThread]
public static int Main(string[] args)
{
int exitCode = 1;
#pragma warning disable CA1416
Thread staThread = new Thread(() =>
{
exitCode = RunTool(args);
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
#pragma warning restore CA1416
return exitCode;
}
private static int RunTool(string[] args)
{
string exeDirectory = AppDomain.CurrentDomain.BaseDirectory;
//Directory.SetCurrentDirectory(exeDirectory);
List<string> argsList = new List<string>(args);
// Extraction du flag -y (pour l'écrasement dans unpack)
bool overwrite = argsList.Remove("-y") || argsList.Remove("-Y");
if (argsList.Count < 1)
{
ShowUsage();
return 1;
}
string operation = argsList[0].ToLowerInvariant();
// Commande update avec option -f
if (operation == "update")
{
string? customXmlPath = null;
int fIndex = argsList.IndexOf("-f");
if (fIndex >= 0)
{
if (fIndex + 1 >= argsList.Count)
{
Console.WriteLine("Error: Missing file path after -f");
return 1;
}
string rawPath = argsList[fIndex + 1].Trim();
if (string.IsNullOrWhiteSpace(rawPath))
{
Console.WriteLine("Error: Empty file path after -f");
return 1;
}
customXmlPath = Path.GetFullPath(rawPath);
}
return UpdateUserDb(customXmlPath);
}
// Commande dump : diagnostic lecture seule d'un fichier NKI
if (operation == "dump")
{
if (argsList.Count < 2)
{
Console.WriteLine("Usage: NkxTool dump <instrument.nki> [--out report.txt]");
return 1;
}
string nkiPath = Path.GetFullPath(argsList[1]);
if (!File.Exists(nkiPath))
{
Console.WriteLine($"Error: The source file '{nkiPath}' does not exist.");
return 1;
}
string? outReport = null;
int outIndex = argsList.IndexOf("--out");
if (outIndex >= 0 && outIndex + 1 < argsList.Count)
{
outReport = Path.GetFullPath(argsList[outIndex + 1]);
}
return NkiDumpCommand.Run(nkiPath, outReport);
}
if (operation == "nki-infoscan")
{
if (argsList.Count < 2)
{
Console.WriteLine("Usage: NkxTool nki-infoscan <instrument.nki> [--length N] [--out report.txt]");
return 1;
}
string nkiPath = Path.GetFullPath(argsList[1]);
if (!File.Exists(nkiPath))
{
Console.WriteLine($"Error: The source file '{nkiPath}' does not exist.");
return 1;
}
int scanLength = 4096;
int lenIndex = argsList.IndexOf("--length");
if (lenIndex >= 0 && lenIndex + 1 < argsList.Count)
{
int.TryParse(argsList[lenIndex + 1], out scanLength);
}
string? outReport = null;
int outIndex = argsList.IndexOf("--out");
if (outIndex >= 0 && outIndex + 1 < argsList.Count)
{
outReport = Path.GetFullPath(argsList[outIndex + 1]);
}
return NkiInfoScan.Run(nkiPath, scanLength, outReport);
}
if (operation == "nki-version")
{
if (argsList.Count < 2)
{
Console.WriteLine("Usage: NkxTool nki-version <instrument.nki> [-v]");
return 1;
}
string nkiPath = Path.GetFullPath(argsList[1]);
if (!File.Exists(nkiPath))
{
Console.Error.WriteLine($"Error: The source file '{nkiPath}' does not exist.");
return 1;
}
bool verbose = argsList.Contains("-v") || argsList.Contains("--verbose");
return NkiVersionCommand.Run(nkiPath, verbose);
}
if (argsList.Count < 2)
{
ShowUsage();
return 1;
}
string path1 = Path.GetFullPath(argsList[1]);
if ((operation == "list" || operation == "unpack") && !File.Exists(path1))
{
Console.WriteLine($"Error: The source file '{path1}' does not exist.");
return 1;
}
try
{
PackDefaultParamStruct dps = new PackDefaultParamStruct();
dps.size = Marshal.SizeOf(typeof(PackDefaultParamStruct));
dps.PluginInterfaceVersionLow = 1;
dps.PluginInterfaceVersionHi = 2;
dps.DefaultIniName = Path.Combine(exeDirectory, "inNKX.ini");
PackSetDefaultParams(ref dps);
}
catch { }
try
{
if (operation == "list")
{
string? outList = argsList.Count >= 3 ? Path.GetFullPath(argsList[2]) : null;
return ListArchive(path1, outList);
}
else if (operation == "unpack" && argsList.Count >= 3)
{
string destinationFolder = Path.GetFullPath(argsList[2]);
HashSet<string>? selectedFiles = null;
if (argsList.Count >= 4 && argsList[3].StartsWith("@"))
{
string listFile = argsList[3].Substring(1);
if (File.Exists(listFile))
{
var lines = File.ReadAllLines(listFile);
selectedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var line in lines)
{
if (!string.IsNullOrWhiteSpace(line))
selectedFiles.Add(line.Trim());
}
}
}
return DecompressArchive(path1, destinationFolder, selectedFiles, overwrite);
}
else if (operation == "pack" && argsList.Count >= 3)
{
string rootPath = argsList.Count >= 4 ? Path.GetFullPath(argsList[3]) : "";
return CompressFolder(argsList[2], path1, rootPath);
}
else
{
Console.WriteLine("Invalid operation or missing arguments.");
ShowUsage();
return 1;
}
}
catch (Exception ex)
{
Console.WriteLine($"Critical Error: {ex.Message}");
return 1;
}
}
private static void ShowUsage()
{
Console.WriteLine("Usage:");
Console.WriteLine(" NkxTool unpack <source_file> <destinationFolder> [@filelist.txt] [-y]");
Console.WriteLine(" NkxTool pack <destination_file> <sourceFolder_OR_@filelist.txt> [rootPath]");
Console.WriteLine(" NkxTool list <source_file> [outputList.txt]");
Console.WriteLine(" NkxTool update [-f <NativeAccess.xml path>]");
Console.WriteLine(" NkxTool dump <fichier.nki> [--out rapport.txt]");
Console.WriteLine(" NkxTool nki-infoscan <instrument.nki> [--length N] [--out report.txt]");
Console.WriteLine(" NkxTool nki-version <instrument.nki> [-v]");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" NkxTool unpack archive.nkx output_folder");
Console.WriteLine(" NkxTool update");
Console.WriteLine(" NkxTool update -f \"C:\\Program Files\\Common Files\\Native Instruments\\Service Center\\NativeAccess.xml\"");
Console.WriteLine(" NkxTool nki-infoscan \"Piano.nki\" --length 4096 --out version_report.txt");
Console.WriteLine(" NkxTool nki-version \"Piano.nki\"");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -y : Overwrite existing files without skipping (unpack only)");
Console.WriteLine(" -f : Specify a custom path to NativeAccess.xml (update only)");
Console.WriteLine(" --length N : Number of bytes to scan from the start of the file (nki-infoscan only, default 4096)");
Console.WriteLine(" --out : Write the report to a file instead of (or in addition to) the console");
Console.WriteLine(" -v : Verbose mode, lists all version candidates found (nki-version only)");
Console.WriteLine();
Console.WriteLine("Supported extensions: .nkx, .nkr, .nicnt, .nks");
}
// --- METHODE UPDATE ---
private static int UpdateUserDb(string? customXmlPath = null)
{
Console.WriteLine("Updating nklibs_info.userdb from NativeAccess.xml...");
string exeDirectory = AppDomain.CurrentDomain.BaseDirectory;
string dbPath = Path.Combine(exeDirectory, "nklibs_info.userdb");
string xmlPath;
if (!string.IsNullOrEmpty(customXmlPath))
{
xmlPath = customXmlPath;
}
else
{
string commonFiles = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);
xmlPath = Path.Combine(commonFiles, "Native Instruments", "Service Center", "NativeAccess.xml");
}
if (!File.Exists(xmlPath))
{
Console.WriteLine($"Error: Could not find '{xmlPath}'");
return 1;
}
StringBuilder sb = new StringBuilder();
int entryCount = 0;
int duplicatedHexCount = 0;
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlNodeList? productNodes = xmlDoc.SelectNodes("//Product");
if (productNodes != null)
{
foreach (XmlNode node in productNodes)
{
string? snpid = node.SelectSingleNode("SNPID")?.InnerText?.Trim();
XmlNode? psNode = node.SelectSingleNode("ProductSpecific");
if (string.IsNullOrEmpty(snpid) || psNode == null) continue;
string? jdx = psNode.SelectSingleNode("JDX")?.InnerText?.Trim();
string? hu = psNode.SelectSingleNode("HU")?.InnerText?.Trim();
string regKey = node.SelectSingleNode("RegKey")?.InnerText?.Trim() ?? "Unknown";
string company = node.SelectSingleNode("Company")?.InnerText?.Trim() ?? "Unknown";
if (string.IsNullOrEmpty(jdx) || string.IsNullOrEmpty(hu)) continue;
void AppendEntry(string id)
{
sb.AppendLine($"[{id}]");
sb.AppendLine($"JDX={jdx}");
sb.AppendLine($"HU={hu}");
sb.AppendLine($"RegKey={regKey}");
sb.AppendLine($"Company={company}");
sb.AppendLine();
entryCount++;
}
// 1. On écrit TOUJOURS la valeur brute originale (ex: "8H3", "224", "S65"...)
AppendEntry(snpid);
// 2. Si le SNPID est purement numérique, on calcule aussi sa forme
// hexadécimale sur 3 caractères (X3) et on l'ajoute si elle diffère
// de l'original -> couvre les deux interprétations possibles côté inNKX.
if (Regex.IsMatch(snpid, @"^\d+$") && int.TryParse(snpid, out int snpidInt))
{
string hexSnpid = snpidInt.ToString("X3");
if (hexSnpid != snpid)
{
AppendEntry(hexSnpid);
duplicatedHexCount++;
}
}
}
}
// Encodage ANSI (Windows-1252), requis par inNKX.wcx64 (plugin Delphi/C ancien).
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding ansiEncoding = Encoding.GetEncoding(1252);
File.WriteAllText(dbPath, sb.ToString(), ansiEncoding);
Console.WriteLine($"Success. Generated file: {dbPath}");
Console.WriteLine($"Total entries written: {entryCount} (including {duplicatedHexCount} decimal/hex duplicates).");
return E_SUCCESS;
}
catch (Exception ex)
{
Console.WriteLine($"Error updating database: {ex.Message}");
return 1;
}
}
private static int ListArchive(string sourceNkxPath, string? outputListPath)
{
// ... (code inchangé)
tOpenArchiveDataW_WCXPlugin openArcData = new tOpenArchiveDataW_WCXPlugin { OpenMode = PK_OM_EXTRACT };
IntPtr pArcName = Marshal.StringToHGlobalUni(sourceNkxPath);
openArcData.ArcName = pArcName;
IntPtr hArc = OpenArchiveW(ref openArcData);
Marshal.FreeHGlobal(pArcName);
if (hArc == IntPtr.Zero) return 1;
try
{
tHeaderDataExW_WCXPlugin headerData = new tHeaderDataExW_WCXPlugin();
List<string> fileList = new List<string>();
while (ReadHeaderExW(hArc, ref headerData) != E_END_ARCHIVE)
{
string relativePath = headerData.hdFileNameW.Replace('/', Path.DirectorySeparatorChar);
if ((headerData.hdFileAttr & 0x10) == 0) // N'ajouter que les fichiers
{
fileList.Add(relativePath);
}
ProcessFileW(hArc, PK_SKIP, null, null);
}
if (!string.IsNullOrEmpty(outputListPath))
{
File.WriteAllLines(outputListPath, fileList, Encoding.UTF8);
Console.WriteLine($"List saved to: {outputListPath} ({fileList.Count} files)");
}
else
{
foreach (string file in fileList)
{
Console.WriteLine(file);
}
}
return E_SUCCESS;
}
finally
{
CloseArchive(hArc);
}
}
private static int CompressFolder(string sourceOrList, string outputNkxFilePath, string rootPath)
{
// ... (code inchangé)
string ext = Path.GetExtension(outputNkxFilePath);
if (string.IsNullOrWhiteSpace(ext))
{
outputNkxFilePath += ".nkx";
}
else if (!SupportedArchiveExtensions.Contains(ext))
{
Console.WriteLine($"Warning: Unsupported output extension '{ext}', defaulting to .nkx");
outputNkxFilePath = Path.ChangeExtension(outputNkxFilePath, ".nkx");
}
Directory.CreateDirectory(Path.GetDirectoryName(outputNkxFilePath) ?? string.Empty);
List<string> filesToPack = new List<string>();
string srcPath = "";
if (sourceOrList.StartsWith("@"))
{
string listFile = sourceOrList.Substring(1);
if (!File.Exists(listFile)) return 1;
srcPath = string.IsNullOrEmpty(rootPath) ? Path.GetDirectoryName(listFile) ?? "" : rootPath;
filesToPack.AddRange(File.ReadAllLines(listFile));
}
else
{
srcPath = Path.GetFullPath(sourceOrList);
foreach (string file in Directory.GetFiles(sourceOrList, "*", SearchOption.AllDirectories))
{
filesToPack.Add(Path.GetRelativePath(sourceOrList, file));
}
}
if (!srcPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
srcPath += Path.DirectorySeparatorChar;
if (filesToPack.Count == 0) return 1;
long maxSize = 2090000000L;
List<List<string>> batches = new List<List<string>>();
List<string> currentBatch = new List<string>();
long currentSize = 0;
foreach (string file in filesToPack)
{
if (string.IsNullOrWhiteSpace(file)) continue;
string fullFilePath = Path.Combine(srcPath, file);
long fileSize = new FileInfo(fullFilePath).Length;
if (currentSize + fileSize > maxSize && currentBatch.Count > 0)
{
batches.Add(currentBatch);
currentBatch = new List<string>();
currentSize = 0;
}
currentBatch.Add(file);
currentSize += fileSize;
}
if (currentBatch.Count > 0) batches.Add(currentBatch);
int overallResult = E_SUCCESS;
for (int i = 0; i < batches.Count; i++)
{
string batchOutputPath = outputNkxFilePath;
if (batches.Count > 1)
{
string dir = Path.GetDirectoryName(outputNkxFilePath) ?? "";
string name = Path.GetFileNameWithoutExtension(outputNkxFilePath);
string batchExt = Path.GetExtension(outputNkxFilePath);
batchOutputPath = Path.Combine(dir, $"{name}_{i:D2}{batchExt}");
}
List<byte> listBytes = new List<byte>();
foreach (string file in batches[i])
{
listBytes.AddRange(Encoding.Unicode.GetBytes(file));
listBytes.Add(0); listBytes.Add(0);
}
listBytes.Add(0); listBytes.Add(0);
byte[] finalBytes = listBytes.ToArray();
IntPtr pAddList = Marshal.AllocHGlobal(finalBytes.Length);
Marshal.Copy(finalBytes, 0, pAddList, finalBytes.Length);
try
{
Console.WriteLine($"Packing batch {i + 1}/{batches.Count} ({batches[i].Count} files) into '{batchOutputPath}'...");
try { SetProcessDataProcW(IntPtr.Zero, _processDataProc); } catch { }
try { SetChangeVolProcW(IntPtr.Zero, _changeVolProc); } catch { }
int result = PackFilesW(batchOutputPath, null, srcPath, pAddList, PK_PACK_SAVE_PATHS);
if (result == E_SUCCESS && File.Exists(batchOutputPath))
{
Console.WriteLine($"Batch {i + 1} success.");
}
else
{
Console.WriteLine($"Batch {i + 1} failed. Code: {result}");
overallResult = result;
}
}
finally
{
Marshal.FreeHGlobal(pAddList);
}
}
return overallResult;
}
private static int DecompressArchive(string sourceNkxPath, string destinationDirPath, HashSet<string>? selectedFiles, bool overwrite)
{
Directory.CreateDirectory(destinationDirPath);
string destPathW = destinationDirPath;
if (!destPathW.EndsWith(Path.DirectorySeparatorChar.ToString()))
destPathW += Path.DirectorySeparatorChar;
tOpenArchiveDataW_WCXPlugin openArcData = new tOpenArchiveDataW_WCXPlugin { OpenMode = PK_OM_EXTRACT };
IntPtr pArcName = Marshal.StringToHGlobalUni(sourceNkxPath);
openArcData.ArcName = pArcName;
IntPtr hArc = OpenArchiveW(ref openArcData);
Marshal.FreeHGlobal(pArcName);
if (hArc == IntPtr.Zero) return 1;
try
{
try { SetProcessDataProcW(hArc, _processDataProc); } catch { }
try { SetChangeVolProcW(hArc, _changeVolProc); } catch { }
tHeaderDataExW_WCXPlugin headerData = new tHeaderDataExW_WCXPlugin();
int extractedCount = 0;
int matchedCount = 0;
int archiveFileCount = 0;
HashSet<string> foundFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (ReadHeaderExW(hArc, ref headerData) != E_END_ARCHIVE)
{
string relativePath = headerData.hdFileNameW.Replace('/', Path.DirectorySeparatorChar);
string fullDestPath = Path.Combine(destinationDirPath, relativePath);
if ((headerData.hdFileAttr & 0x10) != 0)
{
// C'est un dossier, on l'ignore (le plugin avance le curseur)
ProcessFileW(hArc, PK_SKIP, null, null);
continue;
}
archiveFileCount++;
foundFiles.Add(relativePath);
if (selectedFiles != null && !selectedFiles.Contains(relativePath))
{
ProcessFileW(hArc, PK_SKIP, null, null);
continue;
}
matchedCount++;
string fullDestDir = Path.GetDirectoryName(fullDestPath) ?? "";
if (!string.IsNullOrEmpty(fullDestDir))
Directory.CreateDirectory(fullDestDir);
// --- GESTION DE LA COLLISION ---
if (!overwrite && File.Exists(fullDestPath))
{
Console.WriteLine($"Skipping (already exists): {relativePath}");
ProcessFileW(hArc, PK_SKIP, null, null);
continue;
}
Console.WriteLine($"Unpacking: {relativePath}");
int result = ProcessFileW(hArc, PK_EXTRACT, destPathW, relativePath);
if (result == E_SUCCESS)
{
extractedCount++;
}
else
{
Console.WriteLine($"Warning: extraction failed for '{relativePath}' (code {result}).");
}
}
if (selectedFiles == null)
{
Console.WriteLine($"Success. Extracted {extractedCount}/{archiveFileCount} file(s).");
return E_SUCCESS;
}
List<string> missingFiles = new List<string>();
foreach (string selected in selectedFiles)
{
if (!foundFiles.Contains(selected))
missingFiles.Add(selected);
}
Console.WriteLine($"Success. Extracted {extractedCount} selected file(s) out of {matchedCount} matched file(s).");
if (missingFiles.Count > 0)
{
Console.WriteLine($"Warning: {missingFiles.Count} requested file(s) were not found in archive:");
foreach (string missing in missingFiles)
{
Console.WriteLine($" MISSING: {missing}");
}
}
return E_SUCCESS;
}
finally
{
CloseArchive(hArc);
}
}
}