-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
608 lines (496 loc) · 24.1 KB
/
MainWindow.xaml.cs
File metadata and controls
608 lines (496 loc) · 24.1 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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using DataTool.Flag;
using DataTool.SaveLogic;
using DataTool.ToolLogic.Extract;
using Microsoft.WindowsAPICodePack.Dialogs;
using TankView.Helper;
using TankView.Properties;
using TankView.ViewModel;
using TACTLib.Client;
using TACTLib.Client.HandlerArgs;
using TACTLib.Core.Product.Tank;
using TankLib;
using TankLib.TACT;
// ReSharper disable MemberCanBeMadeStatic.Local
namespace TankView {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : INotifyPropertyChanged {
public SynchronizationContext ViewContext { get; }
public NGDPPatchHosts NGDPPatchHosts { get; set; }
public RecentLocations RecentLocations { get; set; }
public ProgressInfo ProgressInfo { get; set; }
public CASCSettings CASCSettings { get; set; }
public AppSettings AppSettings { get; set; }
public GUIDCollection GUIDTree { get; set; } = new GUIDCollection();
public ProductLocations ProductAgent { get; set; }
public ExtractionSettings ExtractionSettings { get; set; }
public ImageExtractionFormats ImageExtractionFormats { get; set; }
public static ClientCreateArgs ClientArgs = new ClientCreateArgs();
private bool ready = true;
public bool IsReady {
get => ready;
set {
ready = value;
if (value) {
_progressWorker.ReportProgress(0, "Idle");
}
NotifyPropertyChanged(nameof(IsReady));
NotifyPropertyChanged(nameof(IsDataReady));
NotifyPropertyChanged(nameof(IsDataToolSafe));
}
}
public string SearchQuery {
get {
return GUIDTree.Search;
}
set {
if (GUIDTree == null) return;
GUIDTree.Search = value;
}
}
public bool IsDataReady => IsReady && GUIDTree?.Data?.Folders.Count > 1;
public bool IsDataToolSafe => IsDataReady && DataTool.Program.TankHandler?.m_rootContentManifest?.m_hashList != null; // todo
private ProgressWorker _progressWorker = new ProgressWorker();
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string name) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public MainWindow() {
ClientArgs.HandlerArgs = new ClientCreateArgs_Tank();
ViewContext = SynchronizationContext.Current;
NGDPPatchHosts = new NGDPPatchHosts();
RecentLocations = new RecentLocations();
ProgressInfo = new ProgressInfo();
CASCSettings = new CASCSettings();
AppSettings = new AppSettings();
ProductAgent = new ProductLocations();
ExtractionSettings = new ExtractionSettings();
ImageExtractionFormats = new ImageExtractionFormats();
_progressWorker.OnProgress += UpdateProgress;
if (!NGDPPatchHosts.Any(x => x.Active)) {
NGDPPatchHosts[0].Active = true;
}
if (!ImageExtractionFormats.Any(x => x.Active)) {
ImageExtractionFormats[0].Active = true;
}
InitializeComponent();
DataContext = this;
// FolderView.ItemsSource = ;
// FolderItemList.ItemsSource = ;
}
GridViewColumnHeader _lastHeaderClicked = null;
private ListSortDirection _lastDirection = ListSortDirection.Descending;
void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e) {
var headerClicked = e.OriginalSource as GridViewColumnHeader;
if (headerClicked == null) return;
if (headerClicked.Role == GridViewColumnHeaderRole.Padding) return;
ListSortDirection direction;
if (headerClicked != _lastHeaderClicked) {
direction = ListSortDirection.Descending;
} else {
direction = _lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
}
var columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
var sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;
GUIDTree.OrderBy(sortBy, direction);
if (direction == ListSortDirection.Ascending) {
headerClicked.Column.HeaderTemplate = Resources["HeaderTemplateArrowUp"] as DataTemplate;
} else {
headerClicked.Column.HeaderTemplate = Resources["HeaderTemplateArrowDown"] as DataTemplate;
}
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked) {
_lastHeaderClicked.Column.HeaderTemplate = null;
}
_lastHeaderClicked = headerClicked;
_lastDirection = direction;
}
private void UpdateProgress(object sender, ProgressChangedEventArgs @event) {
ViewContext.Send(x => {
if (!(x is ProgressChangedEventArgs evt)) return;
if (evt.UserState != null && evt.UserState is string state) {
ProgressInfo.State = state;
}
ProgressInfo.Percentage = evt.ProgressPercentage;
}, @event);
}
public string ModuloTitle => "TankView";
private void Exit(object sender, RoutedEventArgs e) {
Environment.Exit(0);
}
private void NGDPHostChange(object sender, RoutedEventArgs e) {
if (!(sender is MenuItem menuItem)) return;
foreach (PatchHost node in NGDPPatchHosts.Where(x => x.Active && x.GetHashCode() != ((PatchHost) menuItem.DataContext).GetHashCode())) {
node.Active = false;
}
CollectionViewSource.GetDefaultView(NGDPPatchHosts).Refresh();
}
private void ImageExtractionFormatChange(object sender, RoutedEventArgs e) {
if (!(sender is MenuItem menuItem)) return;
foreach (ImageFormat node in ImageExtractionFormats.Where(x => x.Active && x.GetHashCode() != ((ImageFormat) menuItem.DataContext).GetHashCode())) {
node.Active = false;
}
CollectionViewSource.GetDefaultView(ImageExtractionFormats).Refresh();
}
private void OpenNGDP(object sender, RoutedEventArgs e) {
throw new NotImplementedException(nameof(OpenNGDP));
}
private void OpenCASC(object sender, RoutedEventArgs e) {
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
OpenCASC(dialog.FileName);
}
}
private void OpenRecent(object sender, RoutedEventArgs e) {
if (!(sender is MenuItem menuItem)) return;
string path = menuItem.DataContext as string;
RecentLocations.Add(path);
CollectionViewSource.GetDefaultView(RecentLocations).Refresh();
if (path?.StartsWith("ngdp://") == true) {
OpenNGDP(path);
} else {
OpenCASC(path);
}
}
private void OpenAgent(object sender, RoutedEventArgs e) {
if (sender is MenuItem menuItem) {
OpenCASC(menuItem.Tag as string);
}
}
private void OpenNGDP(string path) {
throw new NotImplementedException(nameof(OpenNGDP));
// todo: can be supported again
#pragma warning disable 162
// ReSharper disable once HeuristicUnreachableCode
PrepareTank(path);
Task.Run(delegate {
try {
DataTool.Program.Client = new ClientHandler(null, ClientArgs);
DataTool.Program.TankHandler = DataTool.Program.Client.ProductHandler as ProductHandler_Tank;
} catch (Exception e) {
MessageBox.Show(e.Message, "Error while loading CASC", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
IsReady = true;
if (Debugger.IsAttached) {
throw;
}
} finally {
GCSettings.LatencyMode = GCLatencyMode.Interactive;
GC.Collect();
DataTool.Program.InitTrackedFiles();
}
});
#pragma warning restore 162
}
private void OpenCASC(string path) {
PrepareTank(path);
Task.Run(delegate {
try {
var flags = FlagParser.Parse<ToolFlags>();
if (flags != null) {
ClientArgs.TextLanguage = flags.Language;
ClientArgs.SpeechLanguage = flags.SpeechLanguage;
ClientArgs.Online = flags.Online;
} else {
ClientArgs.Online = false;
}
DataTool.Program.Client = new ClientHandler(path, ClientArgs);
LoadHelper.PostLoad(DataTool.Program.Client);
DataTool.Helper.IO.LoadGUIDTable(false);
DataTool.Program.TankHandler = DataTool.Program.Client.ProductHandler as ProductHandler_Tank;
BuildTree();
} catch (Exception e) {
MessageBox.Show(e.Message, "Error while loading CASC", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
if (Debugger.IsAttached) {
throw;
}
} finally {
GCSettings.LatencyMode = GCLatencyMode.Interactive;
GC.Collect();
if (Settings.Default.LoadManifest) {
DataTool.Program.InitTrackedFiles();
}
ViewContext.Send(delegate { IsReady = true; NotifyPropertyChanged(nameof(IsReady)); }, null);
}
var productCode = DataTool.Program.Client.ProductCode;
if (productCode != null && productCode != "pro") {
MessageBox.Show($"The branch \"{productCode}\" is not supported!\nThis might result in failure to load.\nProceed with caution.", "Unsupported Branch", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
}
});
}
private void PrepareTank(string path) {
RecentLocations.Add(path);
CollectionViewSource.GetDefaultView(RecentLocations).Refresh();
_progressWorker.ReportProgress(0, $"Preparing to load {path}");
IsReady = false;
DataTool.Program.Client = null;
DataTool.Program.TankHandler = null;
GUIDTree?.Dispose();
GUIDTree = new GUIDCollection();
NotifyPropertyChanged(nameof(GUIDTree));
GCSettings.LatencyMode = GCLatencyMode.Batch;
}
private void BuildTree() {
GUIDTree?.Dispose();
GUIDTree = new GUIDCollection(DataTool.Program.Client, DataTool.Program.TankHandler, _progressWorker);
NotifyPropertyChanged(nameof(GUIDTree));
}
private void ChangeActiveNode(object sender, RoutedEventArgs e) {
if (e.Handled) {
return;
}
if (!(sender is TreeViewItem item)) return;
if (item.DataContext is Folder folder) GUIDTree.SelectedEntries = folder.Files.ToArray();
NotifyPropertyChanged(nameof(GUIDTree));
e.Handled = true;
}
private void ExtractFiles(object sender, RoutedEventArgs e) {
GUIDEntry[] files = { };
switch (Tabs.SelectedIndex) {
case 0: {
files = FolderItemList.SelectedItems.OfType<GUIDEntry>().ToArray();
if (files.Length == 0) {
files = FolderItemList.Items.OfType<GUIDEntry>().ToArray();
}
break;
}
case 1: {
files = FolderImageList.SelectedItems.OfType<GUIDEntry>().ToArray();
break;
}
}
if (files.Length == 0) {
return;
}
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
ExtractFiles(dialog.FileName, files);
}
}
private void ExtractFiles_OLD(string outPath, IEnumerable<GUIDEntry> files) {
IsReady = false;
IEnumerable<GUIDEntry> guidEntries = files as GUIDEntry[] ?? files.ToArray();
HashSet<string> directories = new HashSet<string>(guidEntries.Select(x => Path.Combine(outPath, Path.GetDirectoryName(x.FullPath.Substring(1)) ?? string.Empty)));
foreach (string directory in directories) {
if (!Directory.Exists(directory)) {
Directory.CreateDirectory(directory);
}
}
var imageExtractFlags = new ExtractFlags {
ConvertTexturesType = Settings.Default.ImageExtractionFormat
};
Task.Run(delegate {
int c = 0;
int t = guidEntries.Count();
_progressWorker?.ReportProgress(0, "Saving files...");
Parallel.ForEach(guidEntries, new ParallelOptions {
MaxDegreeOfParallelism = 4
}, (entry) => {
c++;
if (c % ((int) (t * 0.005) + 1) == 0) {
var progress = (int) ((c / (float) t) * 100);
_progressWorker?.ReportProgress(progress, $"Saving files... {progress}% ({c}/{t})");
}
var dataType = DataHelper.GetDataType(teResourceGUID.Type(entry.GUID));
var fileType = Path.GetExtension(entry.FullPath)?.Substring(1);
var filePath = Path.ChangeExtension(entry.FullPath.Substring(1), null);
var fileOutput = $"{filePath}.{GetFileType(dataType) ?? fileType}";
try {
if (dataType == DataHelper.DataType.Image && ExtractionSettings.EnableConvertImages) {
DataTool.FindLogic.Combo.ComboInfo info = new DataTool.FindLogic.Combo.ComboInfo();
DataTool.FindLogic.Combo.Find(info, entry.GUID);
var newPath = Path.GetFullPath(Path.Combine(outPath, filePath, @"..\")); // filepath includes the filename which we don't want here as combo already does that
var context = new Combo.SaveContext(info);
Combo.SaveLooseTextures(imageExtractFlags, newPath, context);
return;
}
using (Stream i = IOHelper.OpenFile(entry))
using (Stream o = File.OpenWrite(Path.Combine(outPath, fileOutput))) {
switch (dataType) {
case DataHelper.DataType.Sound when ExtractionSettings.EnableConvertSounds:
o.SetLength(0);
Combo.ConvertSoundFileWw2Ogg(i, o);
break;
// not used, image extraction is handled above
case DataHelper.DataType.Image when ExtractionSettings.EnableConvertImages:
DataHelper.SaveImage(entry, i, o);
break;
default:
i.CopyTo(o);
break;
}
}
} catch {
// ignored
}
});
ViewContext.Send(delegate { IsReady = true; }, null);
});
}
private void ExtractFiles(string outPath, IEnumerable<GUIDEntry> files) {
IsReady = false;
IEnumerable<GUIDEntry> guidEntries = files as GUIDEntry[] ?? files.ToArray();
HashSet<string> directories = new HashSet<string>(guidEntries.Select(x => Path.Combine(outPath, Path.GetDirectoryName(x.FullPath.Substring(1)) ?? string.Empty)));
foreach (string directory in directories) {
if (!Directory.Exists(directory)) {
Directory.CreateDirectory(directory);
}
}
var imageExtractFlags = new ExtractFlags {
ConvertTexturesType = Settings.Default.ImageExtractionFormat
};
//Task.Run(delegate {
int c = 0;
int t = guidEntries.Count();
_progressWorker?.ReportProgress(0, "Saving files...");
//Parallel.ForEach(guidEntries, new ParallelOptions { MaxDegreeOfParallelism = 4 },
//(entry) => {
foreach (var entry in guidEntries) {
c++;
if (c % ((int) (t * 0.005) + 1) == 0) {
var progress = (int) ((c / (float) t) * 100);
_progressWorker?.ReportProgress(progress, $"Saving files... {progress}% ({c}/{t})");
}
var dataType = DataHelper.GetDataType(teResourceGUID.Type(entry.GUID));
var fileType = Path.GetExtension(entry.FullPath)?.Substring(1);
var filePath = Path.ChangeExtension(entry.FullPath.Substring(1), null);
var fileOutput = $"{filePath}.{GetFileType(dataType) ?? fileType}";
try {
if (dataType == DataHelper.DataType.Image && ExtractionSettings.EnableConvertImages) {
DataTool.FindLogic.Combo.ComboInfo info = new DataTool.FindLogic.Combo.ComboInfo();
DataTool.FindLogic.Combo.Find(info, entry.GUID);
var newPath = Path.GetFullPath(Path.Combine(outPath, filePath, @"..\")); // filepath includes the filename which we don't want here as combo already does that
var context = new Combo.SaveContext(info);
Combo.SaveLooseTextures(imageExtractFlags, newPath, context);
return;
}
using (Stream i = IOHelper.OpenFile(entry))
using (Stream o = File.OpenWrite(Path.Combine(outPath, fileOutput))) {
switch (dataType) {
case DataHelper.DataType.Sound when ExtractionSettings.EnableConvertSounds:
o.SetLength(0);
Combo.ConvertSoundFileWw2Ogg(i, o);
break;
// not used, image extraction is handled above
case DataHelper.DataType.Image when ExtractionSettings.EnableConvertImages:
DataHelper.SaveImage(entry, i, o);
break;
default:
i.CopyTo(o);
break;
}
}
} catch {
// ignored
}
}
//});
ViewContext.Send(delegate { IsReady = true; }, null);
//});
}
private string GetFileType(DataHelper.DataType dataType) {
switch (dataType) {
case DataHelper.DataType.Sound when ExtractionSettings.EnableConvertSounds:
return "ogg";
case DataHelper.DataType.Image when ExtractionSettings.EnableConvertImages:
return "dds"; // todo, support other formats??
default:
return null;
}
}
private void ExtractFolder(Folder folder, ref List<GUIDEntry> files) {
files.AddRange(folder.Files);
foreach (Folder f in folder.Folders) {
ExtractFolder(f, ref files);
}
}
private void ExtractFolder(string outPath, Folder folder) {
List<GUIDEntry> files = new List<GUIDEntry>();
ExtractFolder(folder, ref files);
ExtractFiles(outPath, files);
}
private void ExtractFolder(object sender, RoutedEventArgs e) {
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
ExtractFolder(dialog.FileName, (sender as FrameworkElement)?.DataContext as Folder);
}
}
/// <summary>
/// Adds a small delay when holding the arrow key down so it doesn't go through like a million rows a second
/// </summary>
private bool _filJustPressedKeyDown;
private void FolderItemList_OnKeyDown(object sender, KeyEventArgs e) {
if (_filJustPressedKeyDown) {
e.Handled = true;
return;
}
_filJustPressedKeyDown = true;
Task.Delay(90).ContinueWith(t => _filJustPressedKeyDown = false);
}
private void FolderItemList_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) {
if (e.Source is ListView listView && listView.SelectedItem is GUIDEntry guidEntry) {
Clipboard.SetText(guidEntry.Filename);
}
}
private void ExtractAsObj(object sender, RoutedEventArgs e) {
GUIDEntry[] files = { };
if (Tabs.SelectedIndex == 0) {
files = FolderItemList.SelectedItems.OfType<GUIDEntry>().ToArray();
if (files.Length == 0) {
files = FolderItemList.Items.OfType<GUIDEntry>().ToArray();
}
}
if (files.Length == 0) return;
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
IsFolderPicker = true,
EnsurePathExists = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
ExtractFilesAsObj(dialog.FileName, files);
}
}
private void ExtractFilesAsObj(string outPath, IEnumerable<GUIDEntry> files) {
var logFile = Path.Combine(outPath, "export.log");
if (File.Exists(logFile)) File.Delete(logFile);
foreach (var entry in files) {
try {
using (Stream i = IOHelper.OpenFile(entry)) {
var chunkedData = new teChunkedData(i);
foreach (var chunk in chunkedData.Chunks) {
if (chunk is TankLib.Chunks.teModelChunk_RenderMesh) {
ProgressInfo.State = $"Converting {entry.Filename} to obj";
(chunk as TankLib.Chunks.teModelChunk_RenderMesh).ExportToObj(path: outPath, file: entry.Filename + ".obj");
}
}
}
} catch (Exception ex) {
using (TextWriter str = new StreamWriter(path: logFile, append: true)) {
str.WriteLine($"Unable to convert { entry.Filename}");
str.WriteLine(ex.Message);
}
}
}
}
}
}