-
Notifications
You must be signed in to change notification settings - Fork 0
/
jcr6.cs
1619 lines (1396 loc) · 55.7 KB
/
jcr6.cs
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
// Lic:
// jcr6.cs
// (c) 2018, 2019, 2020, 2021, 2023, 2024 JCR6 for C#.
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL was not
// distributed with this file, You can obtain one at
// http://mozilla.org/MPL/2.0/.
// Version: 24.02.24
// EndLic
#undef jcr6debugchat
using TrickyUnits;
using System.Collections.Generic;
using System;
using System.IO;
using System.Text;
// required TrickyUnits:
// = mkl.cs
// = qstream.cs
namespace UseJCR6 {
// Basically you should not meddle with this class unless you know what you are doing.
// The two abstract methods speak for itself. Compress is to make compression possible and Expand for Expansion or Decompression.
// The 'realsize' parameter has only been added as in my experience in earlier getups, so algorithms can require to know this prior to decompression.
public abstract class TJCRBASECOMPDRIVER {
public abstract byte[] Compress(byte[] inputbuffer);
public abstract byte[] Expand(byte[] inputbuffer, int realsize);
}
public abstract class TJCRBASEDRIVER {
public string name = "???";
public abstract bool Recognize(string file);
public abstract TJCRDIR Dir(string file);
}
internal class TJCRCStore : TJCRBASECOMPDRIVER {
public override byte[] Compress(byte[] inputbuffer) { return inputbuffer; }
public override byte[] Expand(byte[] inputbuffer, int realsize) { return inputbuffer; }
}
public class JCR6Exception : Exception {
public readonly string mainfile;
public readonly string entry;
public void ThrowMe() { throw this; }
public override string ToString() => $"JCR6 Error: {Message}";
public JCR6Exception(string Message, string main = "", string entry = "", bool throwit = false) : base($"JCR6 Error: {Message}") {
this.mainfile = main;
this.entry = entry;
if (throwit) throw this;
}
}
class TJCR6DRIVER : TJCRBASEDRIVER {
public TJCR6DRIVER() { name = "JCR6"; }
readonly string checkheader = "JCR6" + ((char)26);
public override bool Recognize(string file) {
bool ret = false;
if (!File.Exists(file)) {
JCR6.dCHAT(file + " not found!");
return false;
}
var bt = QuickStream.ReadFile(file);
ret = bt.Size > 10; // I don't believe a JCR6 file can even get close to that!
ret = ret && bt.ReadString(checkheader.Length) == checkheader;
bt.Close();
//Console.WriteLine(ret);
return ret;
}
public override TJCRDIR Dir(string file) {
var ret = new TJCRDIR();
bool isJ = false;
if (!File.Exists(file)) {
Console.WriteLine(file + " not found!");
return null;
}
var bt = QuickStream.ReadFile(file);
isJ = bt.Size > 10; // I don't believe a JCR6 file can even get close to that!
isJ = isJ && bt.ReadString(checkheader.Length) == checkheader;
if (!isJ) { JCR6.JERROR = file + " is not a JCR6 file!"; bt.Close(); return null; } // This error should NEVER be possible, unless you are using JCR6 NOT the way it was intended to be used.
ret.FAToffset = bt.ReadInt();
if (ret.FAToffset <= 0) {
JCR6.JERROR = "Invalid FAT offset. Maybe you are trying to read a JCR6 file that has never been properly finalized";
bt.Close();
return null;
}
byte TTag = 0;
string Tag = "";
do {
TTag = bt.ReadByte();
if (TTag != 255) { Tag = bt.ReadString(); }
switch (TTag) {
case 1:
ret.CFGstr[Tag] = bt.ReadString();
break;
case 2:
ret.CFGbool[Tag] = bt.ReadByte() == 1;
break;
case 3:
ret.CFGint[Tag] = bt.ReadInt();
break;
case 255:
break;
default:
JCR6.JERROR = $"Invalid config tag ({TTag}) {file}";
bt.Close();
return null;
}
} while (TTag != 255);
if (ret.CFGbool.ContainsKey("_CaseSensitive") && ret.CFGbool["_CaseSensitive"]) {
JCR6.JERROR = "Case Sensitive dir support was already deprecated and removed from JCR6 before it went to the Go language. It's only obvious that support for this was never implemented in C# in the first place.";
bt.Close();
return null;
}
bt.Position = ret.FAToffset;
bool theend = false;
ret.FATsize = bt.ReadInt();
ret.FATcsize = bt.ReadInt();
ret.FATstorage = bt.ReadString();
// ret.Entries = map[string]TJCR6Entry{ } // Was needed in Go, but not in C#, as unlike Go, C# DOES support field assign+define
var fatcbytes = bt.ReadBytes(ret.FATcsize);
bt.Close();
//Console.WriteLine(ret);
if (!JCR6.CompDrivers.ContainsKey(ret.FATstorage)) {
JCR6.JERROR = "The File Table of file '" + file + "' was packed with the '" + ret.FATstorage + "' algorithm, but unfortunately I don't have drivers loaded for that one.";
return null;
}
var fatbytes = JCR6.CompDrivers[ret.FATstorage].Expand(fatcbytes, ret.FATsize);
bt = QuickStream.StreamFromBytes(fatbytes, QuickStream.LittleEndian); // Little Endian is the default, but I need to make sure as JCR6 REQUIRES Little Endian for its directory structures.
if (fatbytes[fatbytes.Length - 1] != 0xff) {
System.Diagnostics.Debug.WriteLine("WARNING! This JCR resource is probably written with the Python Prototype of JCR6 and lacks a proper ending byte.... I'll fix that");
var fixfat = new byte[fatbytes.Length + 1];
fixfat[fixfat.Length - 1] = 255;
for (int i = 0; i < fatbytes.Length; i++) fixfat[i] = fatbytes[i];
fatbytes = fixfat;
}
while ((!bt.EOF) && (!theend)) {
var mtag = bt.ReadByte();
var ppp = bt.Position;
switch (mtag) {
case 0xff:
theend = true;
break;
case 0x01:
var tag = bt.ReadString().ToUpper(); //strings.ToUpper(qff.ReadString(btf));
//Console.WriteLine($"Read tag: '{tag}'");
switch (tag) {
case "BLOCK": {
var ID = bt.ReadInt();
var nb = new TJCRBlock(ID, ret, file);
var ftag = bt.ReadByte();
ret.Blocks[$"{ID}:{file}"] = nb;
//Console.WriteLine($"Block ftag{ftag}");
while (ftag != 255) {
//chats("FILE TAG %d", ftag)
switch (ftag) {
case 1:
var k = bt.ReadString();
var v = bt.ReadString();
nb.datastring[k] = v;
break;
case 2:
var kb = bt.ReadString();
var vb = bt.ReadBoolean();
nb.databool[kb] = vb;
break;
case 3:
var ki = bt.ReadString();
var vi = bt.ReadInt();
nb.dataint[ki] = vi;
break;
case 255:
break;
default:
// p,_:= btf.Seek(0, 1)
JCR6.JERROR = $"Illegal tag in BLOCK({ID}) part: {ftag} on fatpos {bt.Position}";
bt.Close();
return null;
}
ftag = bt.ReadByte();
}
}
break;
case "FILE": {
var nb = new TJCREntry {
MainFile = file
};
/* Not needed in C#
* nb.Datastring = map[string]string{}
* nb.Dataint = map[string]int{}
* nb.Databool = map[string]bool{}
*/
var ftag = bt.ReadByte();
while (ftag != 255) {
//chats("FILE TAG %d", ftag)
switch (ftag) {
case 1:
var k = bt.ReadString();
var v = bt.ReadString();
nb.datastring[k] = v;
break;
case 2:
var kb = bt.ReadString();
var vb = bt.ReadBoolean();
nb.databool[kb] = vb;
break;
case 3:
var ki = bt.ReadString();
var vi = bt.ReadInt();
nb.dataint[ki] = vi;
break;
case 255:
break;
default:
// p,_:= btf.Seek(0, 1)
JCR6.JERROR = $"Illegal tag in FILE part {ftag} on fatpos {bt.Position}";
bt.Close();
return null;
}
ftag = bt.ReadByte();
}
var centry = nb.Entry.ToUpper();
ret.Entries[centry] = nb;
}
break;
case "COMMENT":
var commentname = bt.ReadString();
ret.Comments[commentname] = bt.ReadString();
break;
case "IMPORT":
case "REQUIRE":
//if impdebug {
// fmt.Printf("%s request from %s\n", tag, file)
// }
// Now we're playing with power. Tha ability of
// JCR6 to automatically patch other files into
// one resource
var deptag = bt.ReadByte();
string depk;
string depv;
var depm = new Dictionary<string, string>();
while (deptag != 255) {
depk = bt.ReadString();
depv = bt.ReadString();
depm[depk] = depv;
deptag = bt.ReadByte();
}
var depfile = depm["File"];
//depsig := depm["Signature"]
var deppatha = depm.ContainsKey("AllowPath") && depm["AllowPath"] == "TRUE";
var depcall = "";
// var depgetpaths[2][] string
List<string>[] depgetpaths = new List<string>[2];
depgetpaths[0] = new List<string>();
depgetpaths[1] = new List<string>();
var owndir = Path.GetDirectoryName(file);
int deppath = 0;
/*if impdebug{
fmt.Printf("= Wanted file: %s\n",depfile)
fmt.Printf("= Allow Path: %d\n",deppatha)
fmt.Printf("= ValConv: %d\n",deppath)
fmt.Printf("= Prio entnum %d\n",len(ret.Entries))
}*/
if (deppatha) {
deppath = 1;
}
if (owndir != "") { owndir += "/"; }
depgetpaths[0].Add(owndir);
depgetpaths[1].Add(owndir);
// TODO: JCR6: depgetpaths[1] = append(depgetpaths[1], dirry.Dirry("$AppData$/JCR6/Dependencies/") )
if (qstr.Left(depfile, 1) != "/" && qstr.Left(depfile, 2) != ":") {
foreach (string depdir in depgetpaths[deppath]) //for _,depdir:=range depgetpaths[deppath]
{
if ((depcall == "") && File.Exists(depdir + depfile)) {
depcall = depdir + depfile;
} /*else if (depcall=="" && impdebug ){
if !qff.Exists(depdir+depfile) {
fmt.Printf("It seems %s doesn't exist!!\n",depdir+depfile)
}*/
}
} else {
if (File.Exists(depfile)) {
depcall = depfile;
}
}
if (depcall != "") {
ret.PatchFile(depcall);
if (JCR6.JERROR != "" && tag == "REQUIRE") {//((!ret.PatchFile(depcall)) && tag=="REQUIRE"){
JCR6.JERROR = "Required JCR6 addon file (" + depcall + ") could not imported! Importer reported: " + JCR6.JERROR; //,fil,"N/A","JCR 6 Driver: Dir()")
bt.Close();
return null;
} else if (tag == "REQUIRE" && (!File.Exists(depcall))) {
JCR6.JERROR = "Required JCR6 addon file (" + depcall + ") could not be found!"; //,fil,"N/A","JCR 6 Driver: Dir()")
bt.Close();
return null;
}
} /*else if impdebug {
fmt.Printf("Importing %s failed!", depfile);
fmt.Printf("Request: %s", tag);
}*/
break;
}
break;
default:
JCR6.JERROR = $"Unknown main tag {mtag}, at file table position '{file}'::{bt.Position}/{bt.Size}";
JCR6.Fail($"Unknown main tag {mtag}, at file table position '{file}'::{bt.Position}/{bt.Size}", file);
bt.Close();
return null;
}
}
bt.Close();
return ret; // Actual reader comes later.
}
}
/// <summary>
/// This class is used to store all information about an entry living inside a JCR6 file.
/// </summary>
public class TJCREntry {
private string _mainfile;
/// <summary>
/// Will contain the filename of the resource file this entry lives in (this is most of all important for multi-file resources).
/// </summary>
public string MainFile {
get => _mainfile;
set { _mainfile = value.Replace("\\", "/"); }
}
/// <summary>
/// Contains string data about the entry. The nice part is that you can add fields to it to your liking if you want, but please keep in mind that all fields prefixed with two underscores are considered to be part of JCR6 itself and should not be used if you don't want conflicts with future versions.
/// </summary>
public Dictionary<string, string> datastring = new Dictionary<string, string>();
/// <summary>
/// Contains integer data about the entry. The nice part is that you can add fields to it to your liking if you want, but please keep in mind that all fields prefixed with two underscores are considered to be part of JCR6 itself and should not be used if you don't want conflicts with future versions.
/// </summary>
public Dictionary<string, int> dataint = new Dictionary<string, int>();
/// <summary>
/// Contains boolean data about the entry. The nice part is that you can add fields to it to your liking if you want, but please keep in mind that all fields prefixed with two underscores are considered to be part of JCR6 itself and should not be used if you don't want conflicts with future versions.
/// </summary>
public Dictionary<string, bool> databool = new Dictionary<string, bool>();
/// <summary>
/// Contains the true name of the entry. Also with its regular upper and lower case settings.
/// </summary>
public string Entry {
get { while (datastring["__Entry"] != "" && datastring["__Entry"][0] == '/') datastring["__Entry"] = datastring["__Entry"].Substring(1); return datastring["__Entry"]; }
set { value = value.Trim(); datastring["__Entry"] = value; while (datastring["__Entry"] != "" && datastring["__Entry"][0] == '/') datastring["__Entry"] = datastring["__Entry"].Substring(1); }
}
/// <summary>
/// Gets or sets the size of an entry (setting should only be done by JCR6 write classes itself) without compression.
/// </summary>
public int Size {
get {
return dataint["__Size"];
}
set {
dataint["__Size"] = value;
}
}
/// <summary>
/// Gets or sets the compressed size of an entry (setting should only be done by JCR6 write classes itself)
/// </summary>
public int CompressedSize {
get { return dataint["__CSize"]; }
set { dataint["__CSize"] = value; }
}
/// <summary>
/// Contains a string presentation of the ratio in %.
/// Please note, JCR6 doesn't tell you how much smaller it is, but how to how much % the file has been reduced.
/// </summary>
public string Ratio {
get {
if (Size <= 0) return "N/A";
return $"{Math.Floor((double)(((double)CompressedSize / Size) * (double)100))}%";
}
}
/// <summary>
/// Gets or sets the offset of an entry inside its mainfile. (setting should only be done by JCR6 write classes itself)
/// </summary>
public int Offset {
get { return dataint["__Offset"]; }
set { dataint["__Offset"] = value; }
}
/// <summary>
/// Which compression algorithm has been used to compress this entry?
/// </summary>
public string Storage {
get {
if (!datastring.ContainsKey("__Storage")) {
return "???ERROR???";
}
return datastring["__Storage"];
}
set { datastring["__Storage"] = value; }
}
/// <summary>
/// Gets or sets the author of this entry. This can be handy when you make use of 3rd party assets in your projects.
/// </summary>
public string Author {
get {
if (!datastring.ContainsKey("__Author")) return "";
return datastring["__Author"];
}
set { datastring["__Author"] = value; }
}
/// <summary>
/// Contains the number of the block if it is part of a block. If not part of a block it contains 0.
/// </summary>
public uint Block {
get {
if (!dataint.ContainsKey("__Block")) return 0;
return (uint)dataint["__Block"];
}
set {
dataint["__Block"] = (int)value;
}
}
/// <summary>
/// Gets or sets the notes of an entry. I myself often use these to include copyright and license notices.
/// </summary>
public string Notes {
get {
if (!datastring.ContainsKey("__Notes")) return "";
return datastring["__Notes"];
}
set { datastring["__Notes"] = value; }
}
}
public class TJCRBlock {
public readonly int ID;
public readonly TJCRDIR Parent;
public readonly string MainFile;
public readonly Dictionary<string, string> datastring = new Dictionary<string, string>();
public readonly Dictionary<string, bool> databool = new Dictionary<string, bool>();
public readonly Dictionary<string, int> dataint = new Dictionary<string, int>();
public int Size => dataint["__Size"];
public int CompressedSize => dataint["__CSize"];
public string Storage => datastring["__Storage"];
public int Offset => dataint["__Offset"];
public int Ratio => (int)Math.Floor(((double)CompressedSize / Size) * 100);
internal TJCRBlock(int _ID,TJCRDIR _Parent,string _MainFile) { ID = _ID;Parent = _Parent; MainFile = _MainFile; }
}
/// <summary>
/// This class is used to store all information of the directory inside the JCR6 resource.
/// It also contains many handy methods to help you work with JCR6 resources.
/// Although strictly speaking writing is possible, it's best to consider everything within this class as "read-only".
/// </summary>
public class TJCRDIR {
public int FAToffset;
public int FATsize;
public int FATcsize;
public string FATstorage;
public Dictionary<string, string> CFGstr = new Dictionary<string, string>();
public Dictionary<string, bool> CFGbool = new Dictionary<string, bool>();
public Dictionary<string, int> CFGint = new Dictionary<string, int>();
public SortedDictionary<string, TJCREntry> Entries = new SortedDictionary<string, TJCREntry>();
public SortedDictionary<string, string> Comments = new SortedDictionary<string, string>();
public SortedDictionary<string, TJCRBlock> Blocks = new SortedDictionary<string, TJCRBlock>();
public TJCRBlock LastBlock { get; private set; } = null;
private byte[] LastBlockBuff = null;
/// <summary>
/// Count the entries.
/// </summary>
/// <value>the number of entries inside this JCR6 resource.</value>
public int CountEntries {
get {
var ret = 0;
foreach (string str in Entries.Keys) ret++;
return ret;
}
}
public string[] Aliases(TJCREntry E) {
var ret = new List<string>();
foreach (TJCREntry cE in Entries.Values) {
if (cE != E && $"{cE.MainFile}:{cE.Offset}" == $"{E.MainFile}:{E.Offset}") ret.Add(cE.Entry);
}
ret.Sort();
return ret.ToArray();
}
public string[] Aliases(string ent) {
if (!Exists(ent)) {
JCR6.JERROR = $"Can't get aliases from non-existant entry: {ent}";
return null;
}
return Aliases(Entries[ent.ToUpper().Replace("\\", "//")]);
}
/// <summary>
/// Checks if an entry exists
/// </summary>
/// <remarks>Please remember that JCR6 is case INSENSITIVE!!!</remarks>
/// <returns>True if the entry does exist and false otherwise</returns>
/// <param name="entry">Entry.</param>
public bool Exists(string entry) => Entries.ContainsKey(entry.ToUpper().Replace("\\", "/"));
/// <summary>
/// Checks the resource for a directory! (NOTE! There is not real directory support in JCR6, it just checks if any file has the specified path name (file itself not counted)
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public bool DirExists(string d) {
d = d.ToUpper();
foreach (string k in Entries.Keys)
if (qstr.ExtractDir(k) == d) return true;
return false;
}
public string[] DirList {
get {
try {
var l = new List<string>();
foreach (string EN in Entries.Keys) {
var d = qstr.ExtractDir(EN);
if (!l.Contains(d)) l.Add(d);
while (d.IndexOf('/') >= 0) {
d = qstr.ExtractDir(d);
if (!l.Contains(d)) l.Add(d);
}
}
return l.ToArray();
} catch (Exception e) {
//Confirm.Annoy($"{e}", ".NET Error on operation!", System.Windows.Forms.MessageBoxIcon.Error);
JCR6.JERROR = e.Message;
return new string[0];
}
}
}
/// <summary>
/// Patches a file into a JCR6 resource, if JCR6 can recognise it as a resource.
/// </summary>
/// <param name="file">File.</param>
public void PatchFile(string file) {
JCR6.dCHAT($"Patching: {file}");
var p = JCR6.Dir(file);
if (p == null) {
JCR6.JERROR = ("PATCH ERROR:" + JCR6.JERROR);
return;
}
Patch(p);
}
/// <summary>
/// Patches another resource into this resource.
/// </summary>
/// <param name="pdata">Pdata.</param>
public void Patch(TJCRDIR pdata) {
foreach (string k in pdata.CFGstr.Keys) { this.CFGstr[k] = pdata.CFGstr[k]; }
foreach (string k in pdata.CFGint.Keys) { this.CFGint[k] = pdata.CFGint[k]; }
foreach (string k in pdata.CFGbool.Keys) { this.CFGbool[k] = pdata.CFGbool[k]; }
foreach (string k in pdata.Entries.Keys) { this.Entries[k] = pdata.Entries[k]; }
foreach (string k in pdata.Comments.Keys) { this.Comments[k] = pdata.Comments[k]; }
foreach (string k in pdata.Blocks.Keys) { this.Blocks[k] = pdata.Blocks[k]; }
}
/// <summary>This overload is dangerous. Only use it when you know what you are doing.</summary>
public void Patch(TJCRDIR pdata,string AsDir) {
AsDir = AsDir.ToUpper();
foreach (string k in pdata.CFGstr.Keys) { this.CFGstr[k] = pdata.CFGstr[k]; }
foreach (string k in pdata.CFGint.Keys) { this.CFGint[k] = pdata.CFGint[k]; }
foreach (string k in pdata.CFGbool.Keys) { this.CFGbool[k] = pdata.CFGbool[k]; }
foreach (string k in pdata.Entries.Keys) { this.Entries[$"{AsDir}/{k}"] = pdata.Entries[k]; pdata.Entries[k].Entry = $"{AsDir}/{k}"; }
foreach (string k in pdata.Comments.Keys) { this.Comments[k] = pdata.Comments[k]; }
foreach (string k in pdata.Blocks.Keys) { this.Blocks[k] = pdata.Blocks[k]; }
}
/// <summary>
/// Reads the content of a JCR6 resource entry.
/// </summary>
/// <returns>The contents of the entry in a byte array</returns>
/// <param name="entry">The entry name (case insensitive)</param>
public byte[] JCR_B(string entry) {
JCR6.ErrorReset();
var ce = entry.ToUpper().Replace(@"\", "/");
if (!Entries.ContainsKey(ce)) { JCR6.JERROR = "Resource does not appear to contain an entry called: " + entry; return null; }
var e = Entries[ce];
byte[] cbuf;
byte[] ubuf;
var bt = QuickStream.ReadFile(e.MainFile);
if (e.Block == 0) {
bt.Position = e.Offset;
cbuf = bt.ReadBytes(e.CompressedSize);
bt.Close();
if (!JCR6.CompDrivers.ContainsKey(e.Storage)) { JCR6.JERROR = "Entry \"" + entry + "\" has been packed with the unsupported \"" + e.Storage + "\" algorithm"; return null; }
ubuf = JCR6.CompDrivers[e.Storage].Expand(cbuf, e.Size);
return ubuf;
}
if (LastBlock==null || LastBlock.ID!=e.Block || LastBlock.MainFile != e.MainFile) {
var Tag = $"{e.Block}:{e.MainFile}";
if (!Blocks.ContainsKey(Tag)) { JCR6.Fail($"{e.MainFile} contains no block with numnber {e.Block}", e.MainFile, entry); return null; }
LastBlock = Blocks[Tag];
bt.Position = LastBlock.Offset;
cbuf = bt.ReadBytes(LastBlock.CompressedSize);
ubuf = JCR6.CompDrivers[e.Storage].Expand(cbuf, e.Size);
LastBlockBuff = ubuf;
}
ubuf = new byte[e.Size];
for (int p = 0; p < e.Size; ++p) ubuf[p] = LastBlockBuff[p + e.Offset];
return ubuf;
}
public void FlushBlock() {
LastBlock = null;
LastBlockBuff = null;
}
/// <summary>
/// Loads a stringmap (or Dictionary<string,string>) from a JCR file,in simple form (I rarely used this, but hey,it's there :P )
/// </summary>
/// <returns>The string map.</returns>
/// <param name="filename">Name of the entry in this JCR6 resource.</param>
public Dictionary<string, string> LoadStringMapSimple(string filename) {
var bt = ReadFile(filename, QuickStream.LittleEndian);
bt.Position = 0;
var ret = new Dictionary<string, string>();
//Console.WriteLine($"LSM START! {bt.Position}/{bt.Size}");
while (!bt.EOF) {
//Console.WriteLine($"LSM: {bt.Position}/{bt.Size}");
var lkey = bt.ReadInt(); //Console.WriteLine(lkey);
var key = bt.ReadString(lkey); //Console.WriteLine(key);
var lvalue = bt.ReadInt(); //Console.WriteLine(lvalue);
var value = bt.ReadString(lvalue); //Console.WriteLine(value);
//Console.WriteLine($"LSM: {key} = {value}.");
ret[key] = value;
}
//Console.WriteLine("Loaded LSM");
bt.Close();
return ret;
}
/// <summary>
/// Loads the stringmap. In most of my works this variant has been used.
/// </summary>
/// <returns>The string map.</returns>
/// <param name="entry">Entry in JCR6 resource.</param>
public Dictionary<string, string> LoadStringMap(string entry) {
var bt = ReadFile(entry, QuickStream.LittleEndian);
if (bt == null) return null;
var ret = new Dictionary<string, string>();
string k;
string v;
while (true) {
var tag = bt.ReadByte();
switch (tag) {
case 1:
k = bt.ReadString();
v = bt.ReadString();
ret[k] = v;
break;
case 255:
bt.Close();
return ret;
default:
bt.Close();
JCR6.JERROR = $"Invalid tag in stringmap {tag}";
return null;
}
}
}
public SortedDictionary<string, string> LoadStringMapSorted(string entry) {
var bt = ReadFile(entry, QuickStream.LittleEndian);
if (bt == null) return null;
var ret = new SortedDictionary<string, string>();
string k;
string v;
while (true) {
var tag = bt.ReadByte();
switch (tag) {
case 1:
k = bt.ReadString();
v = bt.ReadString();
ret[k] = v;
break;
case 255:
bt.Close();
return ret;
default:
bt.Close();
JCR6.JERROR = $"Invalid tag in stringmap {tag}";
return null;
}
}
}
/// <summary>
/// Reads the content of a JCR6 resource entry.
/// </summary>
/// <returns>The contents of the entry as a string</returns>
/// <param name="entry">The entry name (case insensitive)</param>
public string LoadString(string entry) {
var buf = JCR_B(entry);
if (buf == null) return "";
return System.Text.Encoding.Default.GetString(buf);
}
/// <summary>
/// Opens an entry inside a JCR6 file as a standard default memory stream for the regular C# routines to read.
/// </summary>
/// <returns>The memory stream.</returns>
/// <param name="entry">The entry name (case insensitive)</param>
public MemoryStream AsMemoryStream(string entry) {
var buf = JCR_B(entry);
if (buf == null) return null;
return new MemoryStream(buf);
}
/// <summary>
/// Opens the file as a QuickStream. See the qstream.cs class file for more information about that.
/// </summary>
/// <returns>The QuickStream</returns>
/// <param name="entry">>The entry name (case insensitive)</param>
/// <param name="endian">QuickStream.LittleEndian or QuickStream.BigEndian for automatic endian conversion, if set to 0 it will just read endians by the way the CPU does it.</param>
public QuickStream ReadFile(string entry, byte endian = QuickStream.LittleEndian) {
var buf = JCR_B(entry);
if (buf == null) return null;
return QuickStream.StreamFromBytes(buf, endian);
}
/// <summary>
/// Reads the content of a JCR6 resource entry
/// </summary>
/// <returns>All lines of the JCR6 entry (assuming it's a text file). A (limited) support is there for recognition of DOS-text files (as used by Windows) and Unix text files (as used by Mac and Linux).</returns>
/// <param name="entry">The entry name (case insensitive)</param>
public string[] ReadLines(string entry, bool unixonly = false) {
var s = LoadString(entry);
string[] eol = new string[3]; eol[0] = "\r\n"; eol[1] = "\n\r"; eol[2] = "\n";
if (unixonly) return s.Split('\n');
foreach (string eoln in eol) {
if (s.Contains(eoln)) {
var sp = new System.Text.RegularExpressions.Regex(eoln);
return sp.Split(s);
}
}
return new[] { s }; // if all one line, just dump it as one line!
}
}
#region Creation
class TJCRCreateStream {
QuickStream stream;
readonly string storage;
readonly string author;
readonly string notes;
readonly string entry;
private MemoryStream memstream;
// block only
public uint block { get; private set; } = 0;
//readonly uint blockoffset = 0;
readonly QuickStream blockstream;
readonly TJCRCreate parent;
public bool closed { get; private set; } = false;
//public byte[] buffer;
public TJCRCreateStream(TJCRCreate theparent, string theentry, string thestorage, string theauthor = "", string thenotes = "", byte Endian = QuickStream.LittleEndian) {
/*
if (theparent.Entries.ContainsKey(theentry.ToUpper())) {
System.Diagnostics.Debug.WriteLine($"DUPE ENTRY {theentry}! Making new!");
int i = -1;
do i++; while (theparent.Entries.ContainsKey($"Dupe{i}.{theentry.ToUpper()}")); theentry = $"Dupe{i}.{theentry.ToUpper()}";
}
*/
entry = theentry;
storage = thestorage;
author = theauthor;
notes = thenotes;
memstream = new MemoryStream();
stream = new QuickStream(memstream, Endian);
parent = theparent;
parent.OpenEntries[this] = theentry;
}
public TJCRCreateStream(TJCRCreate theparent, uint theblock, QuickStream thestream, string theentry, string theauthor = "", string thenotes = "", byte Endian = QuickStream.LittleEndian) {
entry = theentry;
//storage = thestorage;
author = theauthor;
notes = thenotes;
memstream = null;
memstream = new MemoryStream();
stream = new QuickStream(memstream, Endian);
blockstream = thestream;
parent = theparent;
parent.OpenEntries[this] = theentry;
block = theblock;
//startoffset = (uint)thestream.Size;
}
public MemoryStream GetStream => memstream;
public void WriteByte(byte b) => stream.WriteByte(b);
public void WriteInt(int i) => stream.WriteInt(i);
public void WriteString(string s, bool raw = false) => stream.WriteString(s, raw);
public void WriteLong(long i) => stream.WriteLong(i);
public void WriteBytes(byte[] b, bool ce = false) => stream.WriteBytes(b, ce);
public string BufAsString{
get {
var p = stream.Position;
var b = stream.ReadBytes((int)stream.Size);
var r = JCR6.BufAsString(b);
stream.Position = p;
return r;
}
}
~TJCRCreateStream() {
JCR6.dCHAT($"Flusing TJCRCreateStream: {entry}/{storage}");
if (!closed) {
Console.Beep();
Console.WriteLine($"WARNING! Unclosed TJCRCreatestream ({entry}) is being flushed");
Close();
}
}
public void Close() {
if (closed) return;
TJCREntry NEntry = null;
if (block == 0) {
var rawbuff = memstream.ToArray();
var hash = "Unhashed"; if (TJCRCreate.MaxHashSize == 0 || TJCRCreate.MaxHashSize > rawbuff.Length) hash = qstr.md5(System.Text.Encoding.Default.GetString(rawbuff));
var cmpbuff = JCR6.CompDrivers[storage].Compress(rawbuff);
var astorage = storage;
if (cmpbuff == null) {
JCR6.Fail("Compression buffer failed to be created!", "?", entry);
if (stream != null) stream.Close();
parent.OpenEntries.Remove(this);
return;
}
if (parent == null) {
JCR6.Fail("Parent of JCR creation stream happen to be 'null'.", "null", entry);
}
if (parent.mystream == null) {
JCR6.Fail("JCR creation impossible with non-existent stream", parent.ToString(), entry);
return;
}
if (2000000000 - cmpbuff.Length < parent.mystream.Size) {
JCR6.Fail($"Adding {entry} to this JCR file will exceed the limit!", parent.ToString(), entry);
if (stream != null) stream.Close();
parent.OpenEntries.Remove(this);
return;
}
// TODO: "BRUTE" support entry closure
if (storage != "Store" && rawbuff.Length <= cmpbuff.Length) { cmpbuff = rawbuff; astorage = "Store"; }
NEntry = new TJCREntry {
Entry = entry,
Size = rawbuff.Length,
CompressedSize = cmpbuff.Length,
Offset = (int)parent.mystream.Position,
Author = author,
Notes = notes,
Storage = astorage
};
NEntry.datastring["__MD5HASH"] = hash;
parent.mystream.WriteBytes(cmpbuff);
if (stream != null) stream.Close();
} else {
var rawbuff = memstream.ToArray();
var hash = "Unhashed"; if (TJCRCreate.MaxHashSize == 0 || TJCRCreate.MaxHashSize > rawbuff.Length) hash = qstr.md5(System.Text.Encoding.Default.GetString(rawbuff));
NEntry = new TJCREntry {
Entry = entry,
Size = rawbuff.Length,
CompressedSize = 0,
Offset = (int)blockstream.Position,
Author = author,
Notes = notes,
Storage = parent.Blocks[block].Storage
};
NEntry.dataint["__Block"] = (int)block;
NEntry.datastring["__MD5HASH"] = hash;
blockstream.WriteBytes(rawbuff);
}
parent.LastAddedEntry = NEntry;
NEntry.datastring["__JCR6FOR"] = "C#";
parent.Entries[NEntry.Entry.ToUpper()] = NEntry;
parent.OpenEntries.Remove(this);
closed = true;
memstream = null;
stream = null;
}
}
class TJCRCreateBlock {
readonly public Dictionary<string, string> datastring = new Dictionary<string, string>();
readonly public Dictionary<string, int> dataint = new Dictionary<string, int>();
readonly public Dictionary<string, bool> databool = new Dictionary<string, bool>();
readonly public uint ID = 0;
readonly TJCRCreate parent = null;
private MemoryStream memstream;
QuickStream stream;
private bool closed = false;
public string Storage => datastring["__Storage"];
public int Size => dataint["__Size"];
public int CompressedSize => dataint["__CSize"];
public int Ratio => (int)Math.Floor(((double)CompressedSize / Size) * 100);
public TJCRCreateBlock(TJCRCreate _parent,string aStorage="Store") {
JCR6.ErrorReset();
parent = _parent;
do { } while (parent.Blocks.ContainsKey(++ID));
if (!JCR6.CompDrivers.ContainsKey(aStorage)) { JCR6.Fail($"Unknown compression method: {aStorage}", parent.MainFile, $"Block: {ID}"); aStorage = "Store"; }
datastring["__JCR6FOR"] = "C#";
parent.Blocks[ID]=this;
parent.OpenBlocks[this] = ID;
memstream = new MemoryStream();
stream = new QuickStream(memstream);
datastring["__Storage"] = aStorage;
}
public void Close() {
if (closed) return;
var rawbuff = memstream.ToArray();
var hash = "Unhashed"; if (TJCRCreate.MaxHashSize == 0 || TJCRCreate.MaxHashSize > rawbuff.Length) hash = qstr.md5(System.Text.Encoding.Default.GetString(rawbuff));
var cmpbuff = JCR6.CompDrivers[Storage].Compress(rawbuff);
var astorage = Storage;
if (cmpbuff == null) {