-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
614 lines (526 loc) · 21.3 KB
/
Copy pathMainForm.cs
File metadata and controls
614 lines (526 loc) · 21.3 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
using System.Drawing;
using System.Drawing.Drawing2D;
namespace DQ5SaveEditor;
public partial class MainForm : Form
{
private SaveData? _save;
private string? _filePath;
private Character? _selectedChar;
private bool _isDirty; // true = unsaved changes in memory
private readonly string? _initialFile;
public MainForm() : this(null) { }
public MainForm(string? initialFile)
{
InitializeComponent();
ApplyDqTheme();
_initialFile = initialFile;
}
private void LoadInitialFile()
{
if (_initialFile == null)
{
return;
}
try
{
_save = SaveData.LoadSaveState(_initialFile);
_filePath = _initialFile;
_isDirty = false;
PopulateUI();
SetStatus($"Loaded: {Path.GetFileName(_filePath)} — {_save.Characters.Count} characters found.");
Text = $"DQ5 Save Editor — {Path.GetFileName(_filePath)}";
}
catch (Exception ex)
{
MessageBox.Show($"Failed to load save state:\n{ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// ── Dragon Quest V "command window" theme ──────────────────────────────────
private void ApplyDqTheme()
{
BackColor = Theme.Backdrop;
ForeColor = Theme.Text;
Font = new Font(Theme.FontName, 9F);
// Menu — navy with a custom renderer so dropdowns match.
_menu.Renderer = new DqMenuRenderer();
_menu.BackColor = Theme.Backdrop;
_menu.ForeColor = Theme.Text;
StyleMenuItems(_menu.Items);
// Top bar (gold) and status strip.
Theme.FrameContainer(_topBar, radius: 10, pad: 8);
_goldLabel.ForeColor = Theme.Gold;
_goldField.BackColor = Theme.Window;
_goldField.ForeColor = Theme.Text;
_goldField.BorderStyle = BorderStyle.FixedSingle;
Theme.StyleButton(_applyGoldBtn);
_status.BackColor = Theme.Backdrop;
_statusLabel.ForeColor = Theme.SubText;
// Character list window (Split.Panel1).
_split.BackColor = Theme.Backdrop;
_split.Panel1.BackColor = Theme.Backdrop;
_split.Panel2.BackColor = Theme.Backdrop;
Theme.FrameContainer(_split.Panel1, radius: 12, pad: 7);
_listHeader.BackColor = Color.FromArgb(10, 22, 62);
_listHeader.ForeColor = Theme.Gold;
_charList.BackColor = Theme.Window;
_charList.ForeColor = Theme.Text;
_charList.BorderStyle = BorderStyle.None;
// Tabs — owner-drawn navy/gold headers, framed pages.
_tabs.BackColor = Theme.Backdrop;
_tabs.DrawMode = TabDrawMode.OwnerDrawFixed;
_tabs.SizeMode = TabSizeMode.Fixed;
_tabs.ItemSize = new Size(120, 30);
_tabs.Padding = new Point(0, 0);
_tabs.DrawItem += Tabs_DrawItem;
foreach (TabPage tp in _tabs.TabPages)
{
// The tab control supplies the border; just navy-fill the page. (A custom
// Paint frame on a TabPage suppresses its child controls, so avoid it here.)
tp.BackColor = Theme.Window;
tp.ForeColor = Theme.Text;
tp.Padding = new Padding(6);
}
// Stats tab inner panels.
_charNameLabel.BackColor = Color.FromArgb(10, 22, 62);
_charNameLabel.ForeColor = Theme.Gold;
_statsRows.BackColor = Theme.Window;
_bottomStrip.BackColor = Theme.Window;
foreach (var btn in new[] { _maxStatsBtn, _maxExpBtn, _fullHpMpBtn })
{
Theme.StyleButton(btn);
}
Theme.StyleButton(_applyStatsBtn, primary: true);
_applyStatsBtn.Text = "▶ Apply to Character";
// Read-only footer buttons stay subdued.
foreach (var btn in new[] { _applyItemsBtn, _applyBagBtn })
{
btn.FlatStyle = FlatStyle.Flat;
btn.BackColor = Color.FromArgb(10, 22, 62);
btn.ForeColor = Theme.SubText;
btn.FlatAppearance.BorderColor = Theme.FrameDim;
}
_itemsNote.ForeColor = Theme.SubText;
_itemsHost.BackColor = Theme.Window;
_itemsHeader.BackColor = Color.FromArgb(10, 22, 62);
_itemsHeader.ForeColor = Theme.Gold;
_itemsHeader.Font = new Font(Theme.FontName, 9.5F, FontStyle.Bold);
Theme.StyleGrid(_itemsGrid);
Theme.StyleGrid(_bagGrid);
_statsTab.Resize += (s, e) => LayoutStatsColumns();
}
/// <summary>
/// Size the stat column to just fit the "Stat [value]" pair (the items list fills
/// the rest), clamped so it never swallows more than ~55% on a narrow window.
/// </summary>
private void LayoutStatsColumns()
{
if (_statsTab.ClientSize.Width <= 0)
{
return;
}
int want = (int)(370 * (DeviceDpi / 96.0));
int cap = (int)(_statsTab.ClientSize.Width * 0.55);
_statsRows.Width = Math.Min(want, cap);
}
private static void StyleMenuItems(ToolStripItemCollection items)
{
foreach (ToolStripItem item in items)
{
item.BackColor = Theme.Window;
item.ForeColor = Theme.Text;
if (item is ToolStripMenuItem mi && mi.HasDropDownItems)
{
StyleMenuItems(mi.DropDownItems);
}
}
}
// Owner-draw the tab headers as DQ command tabs (gold cursor on the active tab).
private void Tabs_DrawItem(object? sender, DrawItemEventArgs e)
{
var tab = _tabs.GetTabRect(e.Index);
bool active = _tabs.SelectedIndex == e.Index;
using (var bg = new SolidBrush(active ? Theme.Window : Color.FromArgb(9, 18, 52)))
{
e.Graphics.FillRectangle(bg, tab);
}
if (active)
{
using var pen = new Pen(Theme.Gold, 2f);
e.Graphics.DrawLine(pen, tab.Left + 6, tab.Bottom - 2, tab.Right - 6, tab.Bottom - 2);
}
TextRenderer.DrawText(
e.Graphics, _tabs.TabPages[e.Index].Text,
new Font(Theme.FontName, 9.5F, active ? FontStyle.Bold : FontStyle.Regular),
tab, active ? Theme.Gold : Theme.SubText,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}
// ── Menu events ───────────────────────────────────────────────────────────
private void OpenMenuItem_Click(object? sender, EventArgs e) => OpenFile();
private void SaveMenuItem_Click(object? sender, EventArgs e) => SaveFile();
private void SaveAsMenuItem_Click(object? sender, EventArgs e) => SaveFileAs();
private void ExitMenuItem_Click(object? sender, EventArgs e) => Close();
// ── Gold ──────────────────────────────────────────────────────────────────
private void ApplyGoldBtn_Click(object? sender, EventArgs e)
{
if (_save == null)
{
return;
}
_save.Gold = (uint)_goldField.Value;
MarkDirty($"Gold set to {_goldField.Value:N0}. Use File → Save (Ctrl+S) to write to disk.");
}
// ── Character list ────────────────────────────────────────────────────────
private void CharList_SelectedIndexChanged(object? sender, EventArgs e)
{
if (_charList.SelectedItem is Character ch)
{
_selectedChar = ch;
LoadCharIntoEditor(ch);
}
}
private void CharList_DrawItem(object? sender, DrawItemEventArgs e)
{
if (e.Index < 0 || _save == null)
{
return;
}
var ch = (Character)_charList.Items[e.Index];
bool sel = (e.State & DrawItemState.Selected) != 0;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
// Selected row: a brighter navy "highlight" pill with a gold cursor arrow.
using (var bg = new SolidBrush(sel ? Color.FromArgb(40, 72, 146) : Theme.Window))
{
e.Graphics.FillRectangle(bg, e.Bounds);
}
if (sel)
{
using var arrow = new SolidBrush(Theme.Gold);
int cy = e.Bounds.Y + e.Bounds.Height / 2;
e.Graphics.FillPolygon(arrow, new[]
{
new Point(e.Bounds.X + 4, cy - 6),
new Point(e.Bounds.X + 12, cy),
new Point(e.Bounds.X + 4, cy + 6),
});
}
using var nameFont = new Font(Theme.FontName, 10F, FontStyle.Bold);
using var infoFont = new Font(Theme.FontName, 8F);
// Lay the two lines out from the actual font height so the row scales with
// DPI instead of relying on fixed pixel offsets (which overlap at >100%).
int x = e.Bounds.X + 18;
int top = e.Bounds.Y + 2;
int nameHeight = (int)Math.Ceiling(nameFont.GetHeight(e.Graphics));
// Tint monster names so they stand out from the human roster.
Color nameColor = ch.IsMonster ? Theme.MonsterName : Theme.Text;
using (var nameBrush = new SolidBrush(nameColor))
{
e.Graphics.DrawString(ch.Name, nameFont, nameBrush, x, top);
}
string info = $"Lv{ch.Level} HP:{ch.HpMax} MP:{ch.MpMax}";
if (ch.IsMonster && ch.SpeciesName.Length > 0)
{
info += $" · {ch.SpeciesName}";
}
using (var infoBrush = new SolidBrush(Theme.InfoGreen))
{
e.Graphics.DrawString(info, infoFont, infoBrush, x, top + nameHeight);
}
}
/// <summary>
/// Size each character-list row to fit both text lines at the current DPI.
/// Called on load and whenever the DPI changes; fixed heights overlapped on
/// high-DPI displays.
/// </summary>
private void UpdateCharListItemHeight()
{
if (!_charList.IsHandleCreated)
{
return;
}
using var nameFont = new Font("Segoe UI", 10F, FontStyle.Bold);
using var infoFont = new Font("Segoe UI", 8F);
using var g = _charList.CreateGraphics();
_charList.ItemHeight = (int)Math.Ceiling(nameFont.GetHeight(g) + infoFont.GetHeight(g)) + 8;
_charList.Invalidate();
}
private void LoadCharIntoEditor(Character ch)
{
_charNameLabel.Text = ch.IsMonster && ch.SpeciesName.Length > 0
? $"{ch.Name} ({ch.SpeciesName})"
: ch.Name;
// Clamp every value to its field's range so an out-of-range stored value
// (e.g. Maria's Level 0, or glitched HP/MP) can never throw on load.
SetField(_levelField, ch.Level);
SetField(_strField, ch.Str);
SetField(_resField, ch.Res);
SetField(_aglField, ch.Agl);
SetField(_wisField, ch.Wis);
SetField(_lckField, ch.Lck);
SetField(_expField, ch.Exp);
SetField(_hpCurField, ch.HpCur);
SetField(_hpMaxField, ch.HpMax);
SetField(_mpCurField, ch.MpCur);
SetField(_mpMaxField, ch.MpMax);
PopulateItemsGrid(ch);
}
/// <summary>Assign a value to a NumericUpDown, clamped to its [Minimum, Maximum].</summary>
private static void SetField(NumericUpDown field, decimal value)
=> field.Value = Math.Clamp(value, field.Minimum, field.Maximum);
// ── Stats buttons ─────────────────────────────────────────────────────────
private void MaxStatsBtn_Click(object? sender, EventArgs e)
{
_strField.Value = _resField.Value = _aglField.Value =
_wisField.Value = _lckField.Value = 255;
_levelField.Value = 99;
}
private void MaxExpBtn_Click(object? sender, EventArgs e) => _expField.Value = 9_999_999;
private void FullHpMpBtn_Click(object? sender, EventArgs e)
{
if (_hpMaxField.Value > 0)
{
_hpCurField.Value = _hpMaxField.Value;
}
if (_mpMaxField.Value > 0)
{
_mpCurField.Value = _mpMaxField.Value;
}
}
private void ApplyStatsBtn_Click(object? sender, EventArgs e)
{
if (_selectedChar == null || _save == null)
{
return;
}
_selectedChar.Level = (byte)_levelField.Value;
_selectedChar.Str = (byte)_strField.Value;
_selectedChar.Res = (byte)_resField.Value;
_selectedChar.Agl = (byte)_aglField.Value;
_selectedChar.Wis = (byte)_wisField.Value;
_selectedChar.Lck = (byte)_lckField.Value;
_selectedChar.Exp = (uint)_expField.Value;
_selectedChar.HpCur = (ushort)_hpCurField.Value;
_selectedChar.HpMax = (ushort)_hpMaxField.Value;
_selectedChar.MpCur = (ushort)_mpCurField.Value;
_selectedChar.MpMax = (ushort)_mpMaxField.Value;
_save.FlushCharacter(_selectedChar);
_charList.Invalidate();
MarkDirty($"Changes applied to {_selectedChar.Name}. Use File → Save (Ctrl+S) to write to disk.");
}
// ── Items grid ────────────────────────────────────────────────────────────
private void PopulateItemsGrid(Character ch)
{
_itemsGrid.Rows.Clear();
for (int s = 0; s < ch.Items.Length; s++)
{
var item = ch.Items[s];
if (item == null || item.IsEmpty)
{
continue; // skip empty slots
}
string name = item.ItemName + (item.Qty > 1 ? $" x{item.Qty}" : "");
_itemsGrid.Rows.Add(s + 1, name, $"0x{item.ItemId:X2}",
item.IsEquipped ? "✔" : "");
}
}
// ── Bag / item display is read-only; no edit handlers needed. ──────────────
private void CommitBag() { /* read-only: no-op */ }
// ── File operations ───────────────────────────────────────────────────────
private void OpenFile()
{
using var dlg = new OpenFileDialog
{
Title = "Open melonDS Save State",
Filter = "melonDS Save State (*.ml1)|*.ml1|All Files (*.*)|*.*",
InitialDirectory = @"D:\Emulation\DS\Saves"
};
if (dlg.ShowDialog() != DialogResult.OK)
{
return;
}
try
{
if (_isDirty && !ConfirmDiscardChanges())
{
return;
}
_save = SaveData.LoadSaveState(dlg.FileName);
_filePath = dlg.FileName;
_isDirty = false;
PopulateUI();
SetStatus($"Loaded: {Path.GetFileName(_filePath)} — {_save.Characters.Count} characters found. " +
$"(Close melonDS before editing, then load state with F1)");
Text = $"DQ5 Save Editor — {Path.GetFileName(_filePath)}";
}
catch (Exception ex)
{
MessageBox.Show($"Failed to load save state:\n{ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SaveFile()
{
if (_save == null || _filePath == null)
{
SaveFileAs();
return;
}
// Editor is .ml1 focused — no checksum needed for save states.
ApplyStatsBtn_Click(null, EventArgs.Empty);
CommitBag();
_save.Gold = (uint)_goldField.Value;
string bak = _filePath + ".bak";
if (!File.Exists(bak))
{
File.Copy(_filePath, bak);
}
_save.Save(_filePath);
ClearDirty($"Saved — load with F1 in melonDS to apply changes.");
}
private void SaveFileAs()
{
if (_save == null)
{
return;
}
using var dlg = new SaveFileDialog
{
Title = "Save melonDS Save State",
Filter = "melonDS Save State (*.ml1)|*.ml1|All Files (*.*)|*.*",
FileName = _filePath ?? "save.ml1",
DefaultExt = "ml1",
};
if (dlg.ShowDialog() != DialogResult.OK)
{
return;
}
ApplyStatsBtn_Click(null, EventArgs.Empty);
CommitBag();
_save!.Gold = (uint)_goldField.Value;
_save.Save(dlg.FileName);
_filePath = dlg.FileName;
ClearDirty($"Saved to {Path.GetFileName(_filePath)}");
Text = $"DQ5 Save Editor — {Path.GetFileName(_filePath)}";
}
// ── Populate UI ───────────────────────────────────────────────────────────
private void PopulateUI()
{
if (_save == null)
{
return;
}
_goldField.Value = Math.Min(_save.Gold, 9_999_999);
_charList.Items.Clear();
foreach (var ch in _save.Characters)
{
_charList.Items.Add(ch);
}
// For save states, read live in-game data for every party character + bag
if (_save.IsSaveState && _save.HasLiveHeroData)
{
foreach (var ch in _save.Characters)
{
if (ch.SlotIndex == 0)
{
_save.ReadHeroLiveData(ch);
}
else if (ch.LiveStatOffset >= 0)
{
_save.ReadLiveStats(ch, ch.LiveStatOffset);
}
}
_save.ReadLiveBag();
}
if (_charList.Items.Count > 0)
{
_charList.SelectedIndex = 0;
}
PopulateBagGrid();
}
private void PopulateBagGrid()
{
if (_save == null)
{
return;
}
_bagGrid.Rows.Clear();
for (int i = 0; i < _save.BagSlotCount; i++)
{
var item = _save.BagItems[i];
if (item == null || item.IsEmpty)
{
continue; // skip empty slots
}
_bagGrid.Rows.Add(i + 1, item.ItemName, $"0x{item.ItemId:X2}",
item.Quantity.ToString());
}
}
// Shared DataError handler — suppresses the default error dialog for both grids.
private void Grid_DataError(object? sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
// ── Dirty-state helpers ───────────────────────────────────────────────────
private void MarkDirty(string statusMsg)
{
_isDirty = true;
_statusLabel.ForeColor = Color.Gold;
SetStatus("⚠ " + statusMsg);
if (_filePath != null && !Text.StartsWith('*'))
{
Text = "* " + Text;
}
}
private void ClearDirty(string statusMsg)
{
_isDirty = false;
_statusLabel.ForeColor = Color.LightGray;
SetStatus(statusMsg);
if (_filePath != null)
{
Text = $"DQ5 Save Editor — {Path.GetFileName(_filePath)}";
}
}
private bool ConfirmDiscardChanges()
{
var r = MessageBox.Show(
"You have unsaved changes. Save before continuing?",
"Unsaved Changes",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
if (r == DialogResult.Yes)
{
SaveFile(); return !_isDirty;
}
return r == DialogResult.No;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (_isDirty && !ConfirmDiscardChanges())
{
e.Cancel = true;
}
base.OnFormClosing(e);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
UpdateCharListItemHeight();
LoadInitialFile();
// Keep the character list at a constant, readable width (FixedPanel.Panel1);
// clamp in case DPI scaling pushed the designer value out of range.
int target = (int)(330 * (DeviceDpi / 96.0));
int maxDist = _split.Width - _split.Panel2MinSize - _split.SplitterWidth;
if (maxDist > _split.Panel1MinSize)
{
_split.SplitterDistance = Math.Clamp(target, _split.Panel1MinSize, maxDist);
}
LayoutStatsColumns();
}
protected override void OnDpiChanged(DpiChangedEventArgs e)
{
base.OnDpiChanged(e);
UpdateCharListItemHeight();
}
private void SetStatus(string msg) => _statusLabel.Text = msg;
}