-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
330 lines (277 loc) · 9.96 KB
/
Copy pathMainForm.cs
File metadata and controls
330 lines (277 loc) · 9.96 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
using System.ComponentModel;
using System.Text.Json;
namespace ModManifestEditor;
public partial class MainForm : Form
{
private BindingList<ModEntry> _bindingList = new();
private string? _currentFilePath;
private bool _isDirty;
private bool _forceClose;
private static readonly string DefaultFilePath =
Path.Combine(Application.StartupPath, "onward_forever_mod_list.json");
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNamingPolicy = null
};
public MainForm()
{
InitializeComponent();
dataGridView.DataSource = _bindingList;
_bindingList.ListChanged += (_, _) => MarkDirty();
LoadDefaultFile();
}
private void LoadDefaultFile()
{
_currentFilePath = DefaultFilePath;
if (File.Exists(DefaultFilePath))
{
try
{
var json = File.ReadAllText(DefaultFilePath);
var entries = JsonSerializer.Deserialize<List<ModEntry>>(json, JsonOptions);
if (entries != null)
{
_bindingList.RaiseListChangedEvents = false;
foreach (var entry in entries)
_bindingList.Add(entry);
_bindingList.RaiseListChangedEvents = true;
_bindingList.ResetBindings();
}
}
catch { }
}
_isDirty = false;
UpdateTitle();
UpdateStatus();
}
private void MarkDirty()
{
if (!_isDirty)
{
_isDirty = true;
UpdateTitle();
}
}
private void UpdateTitle()
{
var fileName = _currentFilePath != null ? Path.GetFileName(_currentFilePath) : "Untitled";
var dirty = _isDirty ? " *" : "";
Text = $"Mod Manifest Editor - {fileName}{dirty}";
}
private void UpdateStatus()
{
var fileInfo = _currentFilePath ?? "No file";
statusLabel.Text = $"{fileInfo} | {_bindingList.Count} entries";
}
private async Task<bool> PromptSaveIfDirtyAsync()
{
if (!_isDirty) return true;
var result = MessageBox.Show(
"You have unsaved changes. Save before continuing?",
"Unsaved Changes",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.Cancel) return false;
if (result == DialogResult.Yes) return await SaveAsync();
return true;
}
private async void NewMenuItem_Click(object? sender, EventArgs e)
{
if (!await PromptSaveIfDirtyAsync()) return;
_bindingList.Clear();
_currentFilePath = null;
_isDirty = false;
UpdateTitle();
UpdateStatus();
}
private async void OpenMenuItem_Click(object? sender, EventArgs e)
{
if (!await PromptSaveIfDirtyAsync()) return;
using var dialog = new OpenFileDialog
{
Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*",
Title = "Open Mod Manifest",
InitialDirectory = Application.StartupPath
};
if (dialog.ShowDialog() != DialogResult.OK) return;
try
{
var json = File.ReadAllText(dialog.FileName);
var entries = JsonSerializer.Deserialize<List<ModEntry>>(json, JsonOptions);
if (entries == null)
{
MessageBox.Show("File contains null or invalid data.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_bindingList.RaiseListChangedEvents = false;
_bindingList.Clear();
foreach (var entry in entries)
_bindingList.Add(entry);
_bindingList.RaiseListChangedEvents = true;
_bindingList.ResetBindings();
_currentFilePath = dialog.FileName;
_isDirty = false;
UpdateTitle();
UpdateStatus();
}
catch (Exception ex)
{
MessageBox.Show($"Failed to open file:\n{ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async void SaveMenuItem_Click(object? sender, EventArgs e) => await SaveAsync();
private async Task<bool> SaveAsync()
{
if (_currentFilePath == null) return await SaveAsAsync();
if (!await VerifyAllEntriesAsync()) return false;
return WriteFile(_currentFilePath);
}
private async void SaveAsMenuItem_Click(object? sender, EventArgs e) => await SaveAsAsync();
private async Task<bool> SaveAsAsync()
{
using var dialog = new SaveFileDialog
{
Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*",
Title = "Save Mod Manifest As",
DefaultExt = "json"
};
if (dialog.ShowDialog() != DialogResult.OK) return false;
if (!await VerifyAllEntriesAsync()) return false;
if (!WriteFile(dialog.FileName)) return false;
_currentFilePath = dialog.FileName;
UpdateTitle();
return true;
}
/// <summary>
/// Downloads and unpacks every mod in the list and checks the GUID and version
/// baked into its DLL against the manifest. Nothing is written unless all pass.
/// </summary>
private async Task<bool> VerifyAllEntriesAsync()
{
var entries = _bindingList.ToList();
if (entries.Count == 0) return true;
var failures = new List<VerificationResult>();
var progress = new Progress<string>(message => statusLabel.Text = message);
menuStrip.Enabled = false;
toolStrip.Enabled = false;
dataGridView.Enabled = false;
Cursor = Cursors.WaitCursor;
try
{
for (var i = 0; i < entries.Count; i++)
{
statusLabel.Text = $"Verifying {i + 1} of {entries.Count}: {entries[i].Name}...";
var result = await ModVerifier.VerifyAsync(entries[i], progress, CancellationToken.None);
if (!result.Ok) failures.Add(result);
}
}
catch (Exception ex)
{
MessageBox.Show($"Verification failed:\n{ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
UpdateStatus();
return false;
}
finally
{
menuStrip.Enabled = true;
toolStrip.Enabled = true;
dataGridView.Enabled = true;
Cursor = Cursors.Default;
}
if (failures.Count == 0) return true;
var details = string.Join("\n\n", failures.Select(f => $"{f.Entry.Name}\n {f.Error}"));
MessageBox.Show(
$"{failures.Count} of {entries.Count} mod(s) did not match their downloaded files. " +
$"The manifest was NOT saved.\n\n{details}",
"Verification Failed",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
statusLabel.Text = $"Not saved - {failures.Count} mod(s) failed verification.";
return false;
}
private bool WriteFile(string path)
{
try
{
var entries = _bindingList.ToList();
var json = JsonSerializer.Serialize(entries, JsonOptions);
File.WriteAllText(path, json);
_isDirty = false;
UpdateTitle();
statusLabel.Text = "Done and Saved";
return true;
}
catch (Exception ex)
{
MessageBox.Show($"Failed to save file:\n{ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void ExitMenuItem_Click(object? sender, EventArgs e) => Close();
private void AddButton_Click(object? sender, EventArgs e)
{
using var dialog = new EditEntryDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
_bindingList.Add(dialog.GetEntry());
UpdateStatus();
}
}
private void EditButton_Click(object? sender, EventArgs e) => EditSelectedEntry();
private void EditSelectedEntry()
{
if (dataGridView.CurrentRow == null) return;
var index = dataGridView.CurrentRow.Index;
var entry = _bindingList[index];
using var dialog = new EditEntryDialog(entry);
if (dialog.ShowDialog() == DialogResult.OK)
{
var updated = dialog.GetEntry();
_bindingList[index] = updated;
}
}
private void RemoveButton_Click(object? sender, EventArgs e)
{
if (dataGridView.CurrentRow == null) return;
var entry = _bindingList[dataGridView.CurrentRow.Index];
var result = MessageBox.Show(
$"Remove \"{entry.Name}\"?",
"Confirm Remove",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
_bindingList.RemoveAt(dataGridView.CurrentRow.Index);
UpdateStatus();
}
}
private void GenerateUuidButton_Click(object? sender, EventArgs e)
{
var uuid = Guid.NewGuid().ToString();
Clipboard.SetText(uuid);
statusLabel.Text = $"Copied UUID to clipboard: {uuid}";
}
private void DataGridView_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0) EditSelectedEntry();
}
private void DataGridView_KeyDown(object? sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete) RemoveButton_Click(sender, e);
if (e.KeyCode == Keys.Enter) { EditSelectedEntry(); e.Handled = true; }
}
private async void MainForm_FormClosing(object? sender, FormClosingEventArgs e)
{
if (_forceClose || !_isDirty) return;
// Verification is async, so cancel this close and re-issue it once we know the outcome.
e.Cancel = true;
if (!await PromptSaveIfDirtyAsync()) return;
_forceClose = true;
Close();
}
}