-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
4222 lines (3791 loc) · 185 KB
/
Copy pathProgram.cs
File metadata and controls
4222 lines (3791 loc) · 185 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
// Program.cs
// ZX Spectrum Static Recompiler / Lifter to .NET Assembly
// One file. .NET Framework 2.0..4.8. No third-party libraries.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Xml.Serialization;
using System.Globalization;
namespace ZX2ILRecomp
{
static class Program
{
static Options _options;
static StateManager _state;
static TrayManager _tray;
[STAThread]
static int Main(string[] args)
{
Options opts = Options.Parse(args);
if (opts.ShowHelp)
{
HelpPrinter.Print();
return 0;
}
_options = opts;
SetupLogging(opts);
foreach (string u in opts.UnknownArgs)
Log.Warn("Unknown argument: " + u);
AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
{
Log.Error("Unhandled exception: " + e.ExceptionObject);
if (_state != null) _state.Save();
};
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
{
Log.Warn("Ctrl+C/Ctrl+Break received. Saving state...");
if (_state != null) _state.Save();
e.Cancel = false;
};
Status.Changed += delegate(string s)
{
if (_tray != null) _tray.SetStatus(s);
};
Log.Info("ZX Spectrum Static Recompiler started.");
Log.Info("Output directory: " + opts.OutputPath);
_state = new StateManager(opts);
_state.Load();
_state.StartTimer();
if (!opts.NoTray && Environment.UserInteractive)
{
_tray = new TrayManager();
_tray.Start();
}
int exitCode = 0;
try
{
if (string.IsNullOrEmpty(opts.InputPath))
{
if (CanInteractive())
{
if (!Interactive(opts))
return 0;
}
else
{
HelpPrinter.Print();
return 1;
}
}
Pipeline pipeline = new Pipeline(opts, _state);
exitCode = pipeline.Run();
}
catch (Exception ex)
{
Log.Error("Fatal error: " + ex.Message);
Log.Debug(ex.ToString());
exitCode = 1;
}
finally
{
if (_state != null)
{
_state.StopTimer();
_state.Save();
}
if (_tray != null)
{
if (opts.WaitAfter)
{
Log.Info("Done. Application remains in tray. Exit via tray menu.");
_tray.WaitForExit();
}
else
{
_tray.Shutdown();
}
}
else if (opts.WaitAfter)
{
Console.WriteLine("Press any key to exit...");
try { Console.ReadKey(true); }
catch { }
}
}
return exitCode;
}
static bool CanInteractive()
{
return Environment.UserInteractive && !Console.IsInputRedirected && !Console.IsOutputRedirected;
}
static bool Interactive(Options opts)
{
string[] items = new string[5];
items[0] = "Specify ROM/snapshot or folder path (current: <none>)";
items[1] = "Recursive folder processing: off";
items[2] = "Model: Auto-detect";
items[3] = "Start recompilation";
items[4] = "Exit";
while (true)
{
int sel = ConsoleUI.Select("ZX Spectrum Static Recompiler -- TUI", items);
if (sel < 0)
{
HelpPrinter.Print();
return false;
}
if (sel == 0)
{
string p = ConsoleUI.AskPath();
if (!string.IsNullOrEmpty(p))
{
opts.InputPath = p;
items[0] = "Specify path (current: " + p + ")";
}
}
else if (sel == 1)
{
opts.Recursive = !opts.Recursive;
items[1] = "Recursive folder processing: " + (opts.Recursive ? "on" : "off");
}
else if (sel == 2)
{
if (opts.Model == 0) opts.Model = 48;
else if (opts.Model == 48) opts.Model = 128;
else opts.Model = 0;
items[2] = "Model: " + (opts.Model == 0 ? "Auto-detect" : opts.Model.ToString());
}
else if (sel == 3)
{
if (!string.IsNullOrEmpty(opts.InputPath))
return true;
Log.Warn("Please specify a ROM/snapshot or folder path first.");
}
else if (sel == 4)
{
return false;
}
}
}
static void SetupLogging(Options opts)
{
try { Console.OutputEncoding = Encoding.UTF8; }
catch { }
string logFile = null;
try
{
string logDir = Path.Combine(Environment.CurrentDirectory, "logs");
Directory.CreateDirectory(logDir);
string ts = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
logFile = Path.Combine(logDir, "ZxLifter_" + ts + ".log");
}
catch
{
logFile = null;
}
Trace.Listeners.Clear();
Trace.Listeners.Add(new ColorConsoleFileTraceListener(logFile));
Trace.AutoFlush = true;
if (logFile == null)
Log.Warn("Failed to create log file. Logging to console only.");
else
Log.Info("Log file: " + logFile);
}
}
public static class Log
{
public static void Info(string message) { Trace.WriteLine(message, "INFO"); }
public static void Step(string message) { Trace.WriteLine(message, "STEP"); }
public static void Ok(string message) { Trace.WriteLine(message, "OK"); }
public static void Warn(string message) { Trace.WriteLine(message, "WARN"); }
public static void Error(string message) { Trace.WriteLine(message, "ERROR"); }
public static void Debug(string message) { Trace.WriteLine(message, "DEBUG"); }
}
public static class Status
{
public static event Action<string> Changed;
public static void Set(string status)
{
try { Console.Title = "ZX Lifter - " + status; }
catch { }
Action<string> h = Changed;
if (h != null) h(status);
}
}
public class ColorConsoleFileTraceListener : TraceListener
{
StreamWriter _writer;
object _lock = new object();
public ColorConsoleFileTraceListener(string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
try
{
_writer = new StreamWriter(fileName, true, Encoding.UTF8);
_writer.AutoFlush = true;
}
catch
{
_writer = null;
}
}
}
public override void Write(string message)
{
WriteRaw(message, false, "INFO");
}
public override void WriteLine(string message)
{
WriteRaw(message, true, "INFO");
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
WriteFormatted(message, source, eventType);
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
string msg;
if (format == null) msg = string.Empty;
else if (args == null || args.Length == 0) msg = format;
else msg = string.Format(format, args);
WriteFormatted(msg, source, eventType);
}
public override void Fail(string message)
{
WriteFormatted(message, "ERROR", TraceEventType.Error);
}
public override void Fail(string message, string detailMessage)
{
WriteFormatted(message + " " + detailMessage, "ERROR", TraceEventType.Error);
}
void WriteFormatted(string message, string category, TraceEventType type)
{
string cat = string.IsNullOrEmpty(category) ? type.ToString() : category;
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
string full = "[" + time + "] [" + cat + "] " + (message ?? string.Empty);
lock (_lock)
{
WriteConsole(full, cat, true);
if (_writer != null)
{
try { _writer.WriteLine(full); }
catch { }
}
}
}
void WriteRaw(string message, bool line, string category)
{
lock (_lock)
{
WriteConsole(message ?? string.Empty, category, line);
if (_writer != null)
{
try
{
if (line) _writer.WriteLine(message);
else _writer.Write(message);
}
catch { }
}
}
}
void WriteConsole(string text, string category, bool line)
{
ConsoleColor old = ConsoleColor.Gray;
bool restore = false;
try
{
old = Console.ForegroundColor;
Console.ForegroundColor = GetColor(category);
restore = true;
}
catch { }
try
{
if (line) Console.WriteLine(text);
else Console.Write(text);
}
finally
{
if (restore)
{
try { Console.ForegroundColor = old; }
catch { }
}
}
}
ConsoleColor GetColor(string category)
{
if (string.IsNullOrEmpty(category)) return ConsoleColor.Gray;
switch (category.ToUpperInvariant())
{
case "ERROR": return ConsoleColor.Red;
case "WARN": return ConsoleColor.Yellow;
case "OK": return ConsoleColor.Green;
case "STEP": return ConsoleColor.Cyan;
case "DEBUG": return ConsoleColor.DarkGray;
case "PROGRESS": return ConsoleColor.Magenta;
default: return ConsoleColor.Gray;
}
}
public override void Close()
{
lock (_lock)
{
if (_writer != null)
{
try { _writer.Close(); }
catch { }
_writer = null;
}
}
base.Close();
}
protected override void Dispose(bool disposing)
{
if (disposing) Close();
base.Dispose(disposing);
}
}
public class Options
{
public string InputPath;
public string OutputPath;
public bool Recursive;
public bool NoTray;
public bool WaitAfter;
public bool Fresh;
public bool NoCompile;
public bool SaveSource = true;
public int CheckpointMinutes = 10;
public int Model = 0;
public bool ShowHelp;
public List<string> UnknownArgs = new List<string>();
public static Options Parse(string[] args)
{
Options o = new Options();
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (Name(a, "--help", "-h", "/?"))
{
o.ShowHelp = true;
}
else if (Name(a, "-r", "--recursive"))
{
o.Recursive = true;
}
else if (Name(a, "--no-tray"))
{
o.NoTray = true;
}
else if (Name(a, "--wait"))
{
o.WaitAfter = true;
}
else if (Name(a, "--fresh"))
{
o.Fresh = true;
}
else if (Name(a, "--no-compile"))
{
o.NoCompile = true;
}
else if (Name(a, "--no-source"))
{
o.SaveSource = false;
}
else if (Name(a, "--keep-source"))
{
o.SaveSource = true;
}
else if (Name(a, "-i", "--input"))
{
if (i + 1 < args.Length) o.InputPath = args[++i];
}
else if (Name(a, "-o", "--output"))
{
if (i + 1 < args.Length) o.OutputPath = args[++i];
}
else if (Name(a, "--checkpoint"))
{
if (i + 1 < args.Length)
{
int m;
if (int.TryParse(args[++i], out m)) o.CheckpointMinutes = m;
}
}
else if (Name(a, "--model"))
{
if (i + 1 < args.Length)
{
int m;
if (int.TryParse(args[++i], out m)) o.Model = m;
}
}
else if (StartsWith(a, "--input="))
{
o.InputPath = a.Substring("--input=".Length);
}
else if (StartsWith(a, "--output="))
{
o.OutputPath = a.Substring("--output=".Length);
}
else if (StartsWith(a, "--checkpoint="))
{
int m;
if (int.TryParse(a.Substring("--checkpoint=".Length), out m)) o.CheckpointMinutes = m;
}
else if (StartsWith(a, "--model="))
{
int m;
if (int.TryParse(a.Substring("--model=".Length), out m)) o.Model = m;
}
else if (!a.StartsWith("-") && string.IsNullOrEmpty(o.InputPath))
{
o.InputPath = a;
}
else
{
o.UnknownArgs.Add(a);
}
}
if (string.IsNullOrEmpty(o.OutputPath))
o.OutputPath = "zx_lifted_output";
try { o.OutputPath = Path.GetFullPath(o.OutputPath); }
catch { o.OutputPath = Path.Combine(Environment.CurrentDirectory, "zx_lifted_output"); }
try
{
if (!string.IsNullOrEmpty(o.InputPath))
o.InputPath = Path.GetFullPath(o.InputPath);
}
catch { }
return o;
}
static bool Name(string a, params string[] names)
{
foreach (string n in names)
{
if (string.Equals(a, n, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
static bool StartsWith(string a, string prefix)
{
return a.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
}
public static class HelpPrinter
{
public static void Print()
{
Console.WriteLine();
Console.WriteLine("ZX Spectrum Static Recompiler / Lifter to .NET Assembly");
Console.WriteLine("=======================================================");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine(" ZX2ILRecomp.exe --input <game.z80|game.sna|game.tap|folder> --output <dir> [options]");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -i, --input <path> Input .z80/.sna/.tap/.szx file or folder.");
Console.WriteLine(" -o, --output <dir> Output directory. Default: zx_lifted_output");
Console.WriteLine(" -r, --recursive Recursive folder processing.");
Console.WriteLine(" --no-tray Do not create tray icon.");
Console.WriteLine(" --wait Stay in tray/wait after completion.");
Console.WriteLine(" --fresh Ignore saved state (start from scratch).");
Console.WriteLine(" --no-compile Only generate C#, skip EXE compilation.");
Console.WriteLine(" --no-source Do not save intermediate C# (not recommended).");
Console.WriteLine(" --keep-source Save intermediate C# (default).");
Console.WriteLine(" --checkpoint <min> Auto-save interval in minutes. Default: 10.");
Console.WriteLine(" --model <48|128> Force ZX Spectrum model. Default: auto.");
Console.WriteLine(" -h, --help This help.");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" ZX2ILRecomp.exe game.z80");
Console.WriteLine(" ZX2ILRecomp.exe --input C:\\zx_roms --output C:\\lifted -r --wait");
Console.WriteLine(" ZX2ILRecomp.exe --input C:\\zx_roms -r --no-compile --checkpoint 5 --model 128");
Console.WriteLine();
Console.WriteLine("Pipeline:");
Console.WriteLine(" 1. Parse snapshot: .z80/.sna/.tap/.szx, registers, RAM banks.");
Console.WriteLine(" 2. Disassemble Z80, build control-flow graph.");
Console.WriteLine(" 3. Lift instructions to C# code + dynamic dispatch table.");
Console.WriteLine(" 4. Generate Memory Bus, ULA, Beeper, AY, Keyboard, WinForms window.");
Console.WriteLine(" 5. Compile generated C# into Game.exe via CSharpCodeProvider.");
Console.WriteLine();
}
}
public static class ConsoleUI
{
public static bool CanUse()
{
return Environment.UserInteractive && !Console.IsOutputRedirected && !Console.IsInputRedirected;
}
public static int Select(string title, string[] options)
{
if (!CanUse() || options == null || options.Length == 0)
return -1;
int index = 0;
while (true)
{
try
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(title);
Console.WriteLine("Use arrows and Enter. Esc to exit.");
Console.ResetColor();
Console.WriteLine();
for (int i = 0; i < options.Length; i++)
{
if (i == index)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("> " + options[i]);
Console.ResetColor();
}
else
{
Console.WriteLine(" " + options[i]);
}
}
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.UpArrow)
{
index--;
if (index < 0) index = options.Length - 1;
}
else if (key.Key == ConsoleKey.DownArrow)
{
index++;
if (index >= options.Length) index = 0;
}
else if (key.Key == ConsoleKey.Enter)
{
return index;
}
else if (key.Key == ConsoleKey.Escape)
{
return -1;
}
}
catch
{
return -1;
}
}
}
public static string AskPath()
{
Console.Write("Enter path: ");
string s = Console.ReadLine();
return s == null ? string.Empty : s.Trim();
}
public static void Progress(string label, int current, int total)
{
if (!CanUse() || total <= 0) return;
lock (typeof(ConsoleUI))
{
try
{
if (current > total) current = total;
int width = 30;
int filled = (int)((long)current * width / total);
if (filled < 0) filled = 0;
if (filled > width) filled = width;
string bar = new string('#', filled) + new string('-', width - filled);
int percent = (int)((long)current * 100 / total);
string text = string.Format(
"\r[{0}] {1,3}% {2}/{3} {4} ",
bar,
percent,
current,
total,
Truncate(label, 24));
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write(text);
Console.ResetColor();
}
catch { }
}
}
public static void ProgressDone()
{
if (!CanUse()) return;
try { Console.WriteLine(); }
catch { }
}
static string Truncate(string s, int max)
{
if (string.IsNullOrEmpty(s)) return string.Empty;
if (max <= 0) return string.Empty;
if (s.Length <= max) return s;
return s.Substring(0, max);
}
}
public class TrayManager
{
TrayAppContext _context;
Thread _thread;
ManualResetEvent _exited = new ManualResetEvent(false);
ManualResetEvent _ready = new ManualResetEvent(false);
public void Start()
{
try
{
_thread = new Thread(new ThreadStart(Run));
_thread.IsBackground = true;
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
_ready.WaitOne(2000, false);
}
catch (Exception ex)
{
Log.Warn("Failed to start tray: " + ex.Message);
}
}
void Run()
{
try
{
_context = new TrayAppContext(this);
_ready.Set();
Application.Run(_context);
}
catch (Exception ex)
{
Log.Warn("Tray error: " + ex.Message);
}
finally
{
_exited.Set();
_ready.Set();
}
}
public void SetStatus(string text)
{
TrayAppContext ctx = _context;
if (ctx != null) ctx.SetStatus(text);
}
public void Shutdown()
{
TrayAppContext ctx = _context;
if (ctx != null) ctx.RequestExit();
_exited.WaitOne(2000, false);
}
public void WaitForExit()
{
_exited.WaitOne();
}
}
public class TrayAppContext : ApplicationContext
{
NotifyIcon _notify;
Form _invoker;
TrayManager _manager;
public TrayAppContext(TrayManager manager)
{
_manager = manager;
_invoker = new Form();
_invoker.ShowInTaskbar = false;
_invoker.FormBorderStyle = FormBorderStyle.FixedToolWindow;
_invoker.StartPosition = FormStartPosition.Manual;
_invoker.Size = new Size(1, 1);
_invoker.Opacity = 0;
_invoker.Text = "ZX Lifter Invoker";
_invoker.Show();
_invoker.Hide();
MainForm = _invoker;
_notify = new NotifyIcon();
_notify.Icon = SystemIcons.Application;
_notify.Text = "ZX Lifter";
ContextMenuStrip menu = new ContextMenuStrip();
menu.Items.Add("Show status", null, delegate(object sender, EventArgs e)
{
Log.Info("Tray status: " + _notify.Text);
});
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add("Exit", null, delegate(object sender, EventArgs e)
{
RequestExit();
});
_notify.ContextMenuStrip = menu;
_notify.DoubleClick += delegate(object sender, EventArgs e)
{
Log.Info("ZX Lifter in tray. Use context menu.");
};
_notify.Visible = true;
}
public void SetStatus(string text)
{
if (_notify == null) return;
try { _notify.Text = Truncate(text, 63); }
catch { }
}
public void RequestExit()
{
if (_invoker != null && _invoker.IsHandleCreated)
_invoker.BeginInvoke(new MethodInvoker(ExitThread));
else
ExitThread();
}
string Truncate(string s, int max)
{
if (string.IsNullOrEmpty(s)) return "ZX Lifter";
if (s.Length <= max) return s;
return s.Substring(0, max);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_notify != null)
{
try
{
_notify.Visible = false;
_notify.Dispose();
}
catch { }
_notify = null;
}
}
base.Dispose(disposing);
}
}
[XmlRoot("Zx2IlState")]
public class AppState
{
public int Version = 1;
public DateTime Updated = DateTime.Now;
public string LastFile = string.Empty;
public List<string> ProcessedFiles = new List<string>();
}
public class StateManager
{
Options _opts;
AppState _state = new AppState();
string _path;
object _lock = new object();
System.Threading.Timer _timer;
public StateManager(Options opts)
{
_opts = opts;
_path = Path.Combine(opts.OutputPath, ".zx2il.state.xml");
}
public void Load()
{
try
{
if (_opts.Fresh)
{
if (File.Exists(_path))
{
File.Delete(_path);
Log.Info("State reset (--fresh).");
}
_state = new AppState();
return;
}
if (!File.Exists(_path))
{
_state = new AppState();
return;
}
XmlSerializer ser = new XmlSerializer(typeof(AppState));
FileStream fs = new FileStream(_path, FileMode.Open, FileAccess.Read);
try
{
_state = (AppState)ser.Deserialize(fs);
}
finally
{
fs.Close();
}
if (_state == null) _state = new AppState();
if (_state.ProcessedFiles == null) _state.ProcessedFiles = new List<string>();
Log.Info("State loaded. Already processed files: " + _state.ProcessedFiles.Count);
}
catch (Exception ex)
{
Log.Warn("Failed to load state: " + ex.Message);
try
{
if (File.Exists(_path))
File.Move(_path, _path + ".corrupt");
}
catch { }
_state = new AppState();
}
}
public void Save()
{
lock (_lock)
{
try
{
string dir = Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
_state.Updated = DateTime.Now;
XmlSerializer ser = new XmlSerializer(typeof(AppState));
string tmp = _path + ".tmp";
FileStream fs = new FileStream(tmp, FileMode.Create, FileAccess.Write);
try
{
ser.Serialize(fs, _state);
}
finally
{
fs.Close();
}
if (File.Exists(_path)) File.Delete(_path);
File.Move(tmp, _path);
}
catch (Exception ex)
{
Log.Warn("Failed to save state: " + ex.Message);
}
}
}
public bool IsProcessed(string file)
{
lock (_lock)
{
return _state.ProcessedFiles.Contains(Normalize(file));
}
}
public void MarkProcessed(string file)
{
lock (_lock)
{
string n = Normalize(file);
if (!_state.ProcessedFiles.Contains(n))
_state.ProcessedFiles.Add(n);
_state.LastFile = file;
Save();
}
}
public void SetLastFile(string file)
{
lock (_lock)
{
_state.LastFile = file;
}
}
public void StartTimer()
{
if (_opts.CheckpointMinutes <= 0) return;
long msLong = (long)_opts.CheckpointMinutes * 60000L;
int ms = msLong > int.MaxValue ? int.MaxValue : (int)msLong;
if (ms < 1000) ms = 1000;
_timer = new System.Threading.Timer(new TimerCallback(OnTimer), null, ms, ms);
Log.Info("State checkpoint every " + _opts.CheckpointMinutes + " min.");
}
public void StopTimer()
{
if (_timer != null)
{
try { _timer.Dispose(); }
catch { }
_timer = null;
}
}
void OnTimer(object state)
{
Save();
Log.Debug("Checkpoint state saved.");
}
string Normalize(string path)
{
if (string.IsNullOrEmpty(path)) return string.Empty;