-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1119 lines (949 loc) · 36.8 KB
/
Copy pathMainForm.cs
File metadata and controls
1119 lines (949 loc) · 36.8 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
using System.Runtime.InteropServices;
using BreathOfFireSaveEditor.Game;
using BreathOfFireSaveEditor.Ui;
namespace BreathOfFireSaveEditor;
public sealed class MainForm : Form
{
private const string FileFilter =
"SNES9x save states (*.000-*.009)|*.000;*.001;*.002;*.003;*.004;*.005;*.006;*.007;*.008;*.009|" +
"All files (*.*)|*.*";
private BofSave? _save;
private BofCharacter? _current;
private bool _loading;
private readonly ComboBox _slotPicker = new();
private readonly SnesPortrait _portrait = new();
private readonly Label _nameLabel = new();
private readonly Label _statusLabel = new();
private readonly Label _addressLabel = new();
private readonly SnesStatField _atk = new() { Caption = "ATK", Maximum = 9999, BoxWidth = 96 };
private readonly SnesStatField _def = new() { Caption = "DEF", Maximum = 9999, BoxWidth = 96 };
private readonly SnesStatField _act = new() { Caption = "ACT", Maximum = 255, BoxWidth = 96 };
private readonly SnesStatField _mag = new() { Caption = "MAG", Maximum = 255, BoxWidth = 96 };
private readonly SnesStatField _int = new() { Caption = "INT", Maximum = 255, BoxWidth = 96 };
private readonly SnesStatField _fate = new() { Caption = "FATE", Maximum = 255, BoxWidth = 96 };
private readonly SnesStatField _level = new() { Caption = "LEVEL", Locked = true };
private readonly SnesStatField _exp = new() { Caption = "EXP", Maximum = 0xFFFFFF, BoxWidth = 150 };
private readonly SnesStatField _hp = new() { Caption = "H P", Maximum = 9999, Paired = true };
private readonly SnesStatField _ap = new() { Caption = "A P", Maximum = 9999, Paired = true };
// Read only: the game owns equipment, the editor only reports it. The two
// "Etc." accessory slots have not been found in the record yet, so they stay
// blank whatever the character is wearing.
private readonly SnesTextField _wepn = new() { Caption = "Wepn" };
private readonly SnesTextField _shld = new() { Caption = "Shld" };
private readonly SnesTextField _armr = new() { Caption = "Armr" };
private readonly SnesTextField _helm = new() { Caption = "Helm" };
private readonly SnesTextField _etc1 = new() { Caption = "Etc." };
private readonly SnesTextField _etc2 = new() { Caption = "Etc." };
private readonly SnesStatField _str = new() { Caption = "Str.", Maximum = 255 };
private readonly SnesStatField _vigor = new() { Caption = "Vigor", Maximum = 255 };
private readonly SnesStatField _agil = new() { Caption = "Agil.", Maximum = 255 };
private readonly SnesStatField _wisdom = new() { Caption = "Wisdom", Maximum = 255 };
private readonly SnesStatField _luck = new() { Caption = "Luck", Maximum = 255 };
// Gold belongs to the party rather than to a character, so it sits on the Items
// tab with the inventory instead of on the per-character Stats tab.
private readonly SnesStatField _gold = new() { Caption = "GOLD", Maximum = BofSave.MaxGold, BoxWidth = 150 };
private readonly SnesTabStrip _tabs = new() { Tabs = ["Stats", "Items", "Magic"] };
private readonly Panel _pageHost = new();
private IReadOnlyList<Control> _pages = [];
private TableLayoutPanel _itemGrid = null!;
private Label _itemEmptyLabel = null!;
private TableLayoutPanel _spellGrid = null!;
private Label _spellEmptyLabel = null!;
private readonly List<(SnesStatField Field, BofItemSlot Slot)> _itemFields = [];
private ToolStripMenuItem _saveItem = null!;
private ToolStripMenuItem _saveAsItem = null!;
private ToolStripMenuItem _reloadItem = null!;
private IEnumerable<SnesStatField> AllFields =>
[
_atk, _def, _act, _mag, _int, _fate,
_level, _exp, _hp, _ap,
_str, _vigor, _agil, _wisdom, _luck,
];
public MainForm()
{
Text = "Breath of Fire Save State Editor";
BackColor = SnesTheme.Background;
ForeColor = SnesTheme.TextLabel;
Font = SnesTheme.Font(15f);
ClientSize = new Size(940, 880);
MinimumSize = new Size(800, 780);
StartPosition = FormStartPosition.CenterScreen;
BuildLayout();
HookFields();
UpdateEnabledState();
Shown += (_, _) => TryReopenLastFile();
FormClosing += OnFormClosing;
}
/// <summary>Ask the desktop window manager for a dark title bar to match the theme.</summary>
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
int enabled = 1;
try
{
DwmSetWindowAttribute(Handle, DwmwaUseImmersiveDarkMode, ref enabled, sizeof(int));
}
catch (DllNotFoundException)
{
// Older Windows: keep the default title bar.
}
catch (EntryPointNotFoundException)
{
}
}
private const int DwmwaUseImmersiveDarkMode = 20;
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size);
// ---------------------------------------------------------------- layout
private void BuildLayout()
{
var root = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.Background,
ColumnCount = 1,
RowCount = 4,
Padding = new Padding(14, 10, 14, 14),
};
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 52));
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 46));
root.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 148));
root.Controls.Add(BuildSlotRow(), 0, 0);
root.Controls.Add(BuildTabStrip(), 0, 1);
root.Controls.Add(BuildPages(), 0, 2);
root.Controls.Add(BuildFooterPanel(), 0, 3);
Controls.Add(root);
Controls.Add(BuildMenu());
}
private MenuStrip BuildMenu()
{
var open = new ToolStripMenuItem("&Open...", null, (_, _) => OpenFile())
{ ShortcutKeys = Keys.Control | Keys.O };
_saveItem = new ToolStripMenuItem("&Save", null, (_, _) => SaveFile(null))
{ ShortcutKeys = Keys.Control | Keys.S };
_saveAsItem = new ToolStripMenuItem("Save &As...", null, (_, _) => SaveAs());
_reloadItem = new ToolStripMenuItem("&Reload from disk", null, (_, _) => Reload())
{ ShortcutKeys = Keys.F5 };
var exit = new ToolStripMenuItem("E&xit", null, (_, _) => Close());
var file = new ToolStripMenuItem("&File");
file.DropDownItems.AddRange(new ToolStripItem[]
{
open, _saveItem, _saveAsItem, new ToolStripSeparator(), _reloadItem, new ToolStripSeparator(), exit,
});
var help = new ToolStripMenuItem("&Help");
help.DropDownItems.Add(new ToolStripMenuItem("&About", null, (_, _) => ShowAbout()));
var menu = new MenuStrip
{
BackColor = SnesTheme.PanelFill,
ForeColor = SnesTheme.TextLabel,
Renderer = new ToolStripProfessionalRenderer(new SnesMenuColours()),
Font = SnesTheme.Font(12f),
};
menu.Items.AddRange(new ToolStripItem[] { file, help });
MainMenuStrip = menu;
return menu;
}
private Control BuildSlotRow()
{
var host = new Panel { Dock = DockStyle.Fill, BackColor = SnesTheme.Background };
var caption = new Label
{
Text = "CHARACTER",
AutoSize = false,
Bounds = new Rectangle(6, 8, 170, 34),
ForeColor = SnesTheme.TextDim,
BackColor = SnesTheme.Background,
TextAlign = ContentAlignment.MiddleLeft,
Font = SnesTheme.Font(13f),
};
_slotPicker.DropDownStyle = ComboBoxStyle.DropDownList;
_slotPicker.FlatStyle = FlatStyle.Flat;
_slotPicker.BackColor = SnesTheme.FieldFill;
_slotPicker.ForeColor = SnesTheme.TextPrimary;
_slotPicker.Font = SnesTheme.Font(14f);
_slotPicker.Location = new Point(182, 6);
// Wide enough for the longest entry: slot, name, level and the reserve note.
_slotPicker.Width = 470;
_slotPicker.SelectedIndexChanged += (_, _) => BindCharacter();
host.Controls.Add(caption);
host.Controls.Add(_slotPicker);
return host;
}
private Control BuildCombatPanel()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
// A two column table rather than a docked grid with a left margin:
// DefaultLayout ignores Margin on a Dock.Fill child, which let the stat
// grid cover the portrait entirely.
var split = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.PanelFill,
ColumnCount = 2,
RowCount = 1,
};
split.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 152));
split.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
split.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
split.Controls.Add(BuildPortraitCell(), 0, 0);
var grid = NewGrid(columns: 2, rows: 3);
grid.Controls.Add(_atk, 0, 0);
grid.Controls.Add(_def, 1, 0);
grid.Controls.Add(_act, 0, 1);
grid.Controls.Add(_mag, 1, 1);
grid.Controls.Add(_int, 0, 2);
grid.Controls.Add(_fate, 1, 2);
split.Controls.Add(grid, 1, 0);
panel.Controls.Add(split);
return panel;
}
private Control BuildPortraitCell()
{
var cell = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.PanelFill,
ColumnCount = 1,
RowCount = 2,
Padding = new Padding(0, 14, 0, 0),
};
cell.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
cell.RowStyles.Add(new RowStyle(SizeType.Absolute, 112));
cell.RowStyles.Add(new RowStyle(SizeType.Absolute, 36));
_portrait.Anchor = AnchorStyles.None;
_portrait.Size = new Size(104, 104);
_nameLabel.Dock = DockStyle.Fill;
_nameLabel.AutoSize = false;
_nameLabel.TextAlign = ContentAlignment.MiddleCenter;
_nameLabel.BackColor = SnesTheme.PanelFill;
_nameLabel.ForeColor = SnesTheme.TextPrimary;
_nameLabel.Font = SnesTheme.Font(17f);
cell.Controls.Add(_portrait, 0, 0);
cell.Controls.Add(_nameLabel, 0, 1);
return cell;
}
private Control BuildVitalsPanel()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
var grid = NewGrid(columns: 2, rows: 5);
grid.Margin = new Padding(22, 16, 22, 16);
grid.Controls.Add(_level, 0, 0);
grid.Controls.Add(_exp, 0, 1);
grid.Controls.Add(_hp, 0, 2);
grid.Controls.Add(_ap, 0, 3);
grid.Controls.Add(_str, 1, 0);
grid.Controls.Add(_vigor, 1, 1);
grid.Controls.Add(_agil, 1, 2);
grid.Controls.Add(_wisdom, 1, 3);
grid.Controls.Add(_luck, 1, 4);
panel.Controls.Add(grid);
return panel;
}
private Control BuildTabStrip()
{
_tabs.Dock = DockStyle.Fill;
_tabs.Margin = new Padding(4, 0, 4, 4);
_tabs.SelectedIndexChanged += (_, _) => ShowPage(_tabs.SelectedIndex);
return _tabs;
}
private Control BuildPages()
{
_pageHost.Dock = DockStyle.Fill;
_pageHost.BackColor = SnesTheme.Background;
_pageHost.Margin = Padding.Empty;
_pages = [BuildStatsPage(), BuildItemsPage(), BuildMagicPage()];
foreach (var page in _pages) _pageHost.Controls.Add(page);
ShowPage(0);
return _pageHost;
}
private void ShowPage(int index)
{
for (int i = 0; i < _pages.Count; i++) _pages[i].Visible = i == index;
_pages[index].BringToFront();
}
private Control BuildStatsPage()
{
var page = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.Background,
ColumnCount = 1,
RowCount = 3,
Margin = Padding.Empty,
};
page.RowStyles.Add(new RowStyle(SizeType.Absolute, 216));
page.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
page.RowStyles.Add(new RowStyle(SizeType.Absolute, 158));
page.Controls.Add(BuildCombatPanel(), 0, 0);
page.Controls.Add(BuildVitalsPanel(), 0, 1);
page.Controls.Add(BuildEquipmentPanel(), 0, 2);
return page;
}
private Control BuildItemsPage()
{
var page = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.Background,
ColumnCount = 1,
RowCount = 2,
Margin = Padding.Empty,
};
page.RowStyles.Add(new RowStyle(SizeType.Absolute, 72));
page.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
page.Controls.Add(BuildGoldPanel(), 0, 0);
page.Controls.Add(BuildInventoryPanel(), 0, 1);
return page;
}
/// <summary>
/// The purse. It is party wide, so it lives here beside the inventory rather
/// than on the Stats tab, where it would read as belonging to one character.
/// </summary>
private Control BuildGoldPanel()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
var grid = NewGrid(columns: 1, rows: 1);
grid.Margin = new Padding(22, 14, 22, 14);
grid.Controls.Add(_gold, 0, 0);
panel.Controls.Add(grid);
return panel;
}
private Control BuildInventoryPanel()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
_itemGrid = new TableLayoutPanel
{
Dock = DockStyle.Top,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
BackColor = SnesTheme.PanelFill,
ColumnCount = 2,
Margin = Padding.Empty,
};
_itemGrid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
_itemGrid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
var itemScroll = NewScrollHost();
itemScroll.Controls.Add(_itemGrid);
_itemEmptyLabel = new Label
{
Dock = DockStyle.Fill,
AutoSize = false,
BackColor = SnesTheme.PanelFill,
ForeColor = SnesTheme.TextDim,
Font = SnesTheme.Font(13f, FontStyle.Regular),
TextAlign = ContentAlignment.MiddleCenter,
Text = "No save state loaded.",
Visible = true,
};
panel.Controls.Add(itemScroll);
panel.Controls.Add(_itemEmptyLabel);
return panel;
}
/// <summary>
/// A scrolling host for a grid that can outgrow the window. AutoScroll has to
/// sit on the container with the grid docked to its top and sizing itself,
/// never on the grid: a TableLayoutPanel that both scrolls and carries a
/// percent row sizes itself to the space it has been given, so it never
/// reports being taller than its own client area, no scrollbar appears and the
/// rows past the bottom edge are simply clipped. A 34 item bag lost its last
/// ten that way.
/// </summary>
private static Panel NewScrollHost() => new()
{
Dock = DockStyle.Fill,
AutoScroll = true,
BackColor = SnesTheme.PanelFill,
Margin = Padding.Empty,
};
/// <summary>
/// Rebuilds the item rows for the loaded save. Only occupied slots get a row:
/// quantities are editable but items cannot be added, so an empty slot has
/// nothing to offer.
/// </summary>
private void BuildItemRows()
{
_itemGrid.SuspendLayout();
foreach (var (field, _) in _itemFields) field.Dispose();
_itemFields.Clear();
_itemGrid.Controls.Clear();
_itemGrid.RowStyles.Clear();
_itemGrid.RowCount = 0;
var occupied = _save?.Inventory.Occupied.ToList() ?? [];
int row = 0;
for (int i = 0; i < occupied.Count; i++)
{
var slot = occupied[i];
// Equipment can sit in the bag, and its second byte is the id's page
// rather than a count - so there is nothing to spin, and editing it
// would turn the item into a different one.
var field = new SnesStatField
{
Caption = slot.Name,
Minimum = 0,
// A count the game cannot draw is still a count, and clamping a
// field on binding it would rewrite it on the next save without
// anyone asking. Whatever is already there sets its own ceiling.
Maximum = Math.Max(BofInventory.MaxQuantity, slot.Quantity),
Locked = slot.IsEquipment,
BoxWidth = 78,
Dock = DockStyle.Fill,
Margin = new Padding(10, 3, 10, 3),
Value = slot.Quantity,
};
var captured = slot;
field.UserEdited += (_, _) =>
{
if (_loading || _save is null)
{
return;
}
captured.Quantity = field.Value;
_save.MarkDirty();
UpdateStatus();
};
_itemFields.Add((field, slot));
int column = i % 2;
if (column == 0)
{
_itemGrid.RowCount = row + 1;
_itemGrid.RowStyles.Add(new RowStyle(SizeType.Absolute, 40));
}
_itemGrid.Controls.Add(field, column, row);
if (column == 1)
{
row++;
}
}
if (occupied.Count % 2 == 1)
{
row++;
}
// No trailing percent row here. The grid sizes itself to its rows and its
// host scrolls; a percent row would size it to the host instead and take
// the scrollbar away with it. See NewScrollHost.
_itemGrid.RowCount = row;
bool any = occupied.Count > 0;
_itemGrid.Visible = any;
_itemEmptyLabel.Visible = !any;
_itemEmptyLabel.Text = _save is null ? "No save state loaded." : "The party is not carrying any items.";
// The scroll host fills the page and sits over the label, so hiding the grid
// inside it leaves the host's own background covering the message. Lifting
// the label is what actually puts it on screen. See NewScrollHost.
if (!any)
{
_itemEmptyLabel.BringToFront();
}
_itemGrid.ResumeLayout();
}
/// <summary>
/// The magic list, laid out in three columns like the game's own screen.
/// Read only: spells are not stored in a save at all, so there is nothing
/// here to change. See <see cref="BofSpells"/>.
/// </summary>
private Control BuildMagicPage()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
_spellGrid = new TableLayoutPanel
{
Dock = DockStyle.Top,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
BackColor = SnesTheme.PanelFill,
ColumnCount = 3,
Margin = Padding.Empty,
Padding = new Padding(12, 10, 12, 10),
};
for (int c = 0; c < 3; c++)
{
_spellGrid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / 3));
}
_spellEmptyLabel = new Label
{
Dock = DockStyle.Fill,
AutoSize = false,
BackColor = SnesTheme.PanelFill,
ForeColor = SnesTheme.TextDim,
Font = SnesTheme.Font(13f),
TextAlign = ContentAlignment.MiddleCenter,
Text = "No save state loaded.",
};
var spellScroll = NewScrollHost();
spellScroll.Controls.Add(_spellGrid);
panel.Controls.Add(spellScroll);
panel.Controls.Add(_spellEmptyLabel);
return panel;
}
/// <summary>
/// Fills the magic page for the picked character. A character with no learn
/// table says so rather than pretending to know they have no magic.
/// </summary>
private void BuildSpellRows()
{
_spellGrid.SuspendLayout();
foreach (Control old in _spellGrid.Controls) old.Dispose();
_spellGrid.Controls.Clear();
_spellGrid.RowStyles.Clear();
_spellGrid.RowCount = 0;
var spells = _current?.Spells ?? [];
int row = 0;
for (int i = 0; i < spells.Count; i++)
{
int column = i % 3;
if (column == 0)
{
_spellGrid.RowCount = row + 1;
_spellGrid.RowStyles.Add(new RowStyle(SizeType.Absolute, 34));
}
_spellGrid.Controls.Add(new Label
{
Text = spells[i],
AutoSize = false,
Dock = DockStyle.Fill,
BackColor = SnesTheme.PanelFill,
ForeColor = SnesTheme.TextLocked,
Font = SnesTheme.Font(15f),
TextAlign = ContentAlignment.MiddleLeft,
Margin = new Padding(10, 2, 10, 2),
}, column, row);
if (column == 2)
{
row++;
}
}
if (spells.Count % 3 != 0)
{
row++;
}
// The grid sizes itself to its rows and its host scrolls, so the rows keep
// the height they were given without a percent row to soak up the rest -
// and Bleu's thirty one spells will have somewhere to go. See NewScrollHost.
_spellGrid.RowCount = row;
bool any = spells.Count > 0;
_spellGrid.Visible = any;
_spellEmptyLabel.Visible = !any;
_spellEmptyLabel.Text = SpellEmptyText();
// Same as the items page: the scroll host covers the label until it is lifted.
if (!any)
{
_spellEmptyLabel.BringToFront();
}
_spellGrid.ResumeLayout();
}
private string SpellEmptyText()
{
if (_save is null)
{
return "No save state loaded.";
}
if (_current is null)
{
return string.Empty;
}
if (BofSpells.HasNoMagic(_current.CharacterId))
{
return $"{_current.Name} has no magic.";
}
// The hero's forms are won from story trials, so an empty list is a place in
// the story rather than a low level - saying "not learned yet" would misplace
// the blame onto levelling, which has nothing to do with it.
if (_current.CharacterId == BofSpells.HeroId)
{
return $"{_current.Name} has not won a dragon transformation yet.";
}
if (BofSpells.IsKnown(_current.CharacterId))
{
return $"{_current.Name} has not learned any spells yet.";
}
return _current.IsInParty
? $"No spell list is known for {_current.Name}."
: $"{_current.Name} is not in the party, so there is nothing to look up.";
}
private Control BuildEquipmentPanel()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
var grid = NewGrid(columns: 2, rows: 3);
grid.Margin = new Padding(0);
grid.Controls.Add(_wepn, 0, 0);
grid.Controls.Add(_shld, 1, 0);
grid.Controls.Add(_armr, 0, 1);
grid.Controls.Add(_helm, 1, 1);
grid.Controls.Add(_etc1, 0, 2);
grid.Controls.Add(_etc2, 1, 2);
foreach (var slot in EquipmentFields)
{
slot.Dock = DockStyle.Fill;
slot.Margin = new Padding(10, 3, 10, 3);
}
panel.Controls.Add(grid);
return panel;
}
private IEnumerable<SnesTextField> EquipmentFields =>
[_wepn, _shld, _armr, _helm, _etc1, _etc2];
private Control BuildFooterPanel()
{
var panel = new SnesPanel { Dock = DockStyle.Fill };
// Stacked rows rather than absolute bounds, so the wrapped hint cannot
// spill past the bottom of the box at any window width.
var rows = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.PanelFill,
ColumnCount = 1,
RowCount = 3,
Padding = new Padding(10, 4, 10, 4),
};
rows.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
rows.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
rows.RowStyles.Add(new RowStyle(SizeType.Absolute, 26));
rows.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
StyleFooterLabel(_statusLabel, SnesTheme.Font(13f), SnesTheme.TextPrimary);
_statusLabel.Text = "No save state loaded.";
StyleFooterLabel(_addressLabel, SnesTheme.Font(11f, FontStyle.Regular), SnesTheme.TextDim);
var hint = new Label();
StyleFooterLabel(hint, SnesTheme.Font(11f, FontStyle.Regular), SnesTheme.TextDim);
hint.TextAlign = ContentAlignment.TopLeft;
hint.Text = "ATK, DEF, ACT, MAG, INT and FATE are derived values: the game recomputes them from the "
+ "base stats and equipment, so edits to them may not survive a level up or a change of gear.";
rows.Controls.Add(_statusLabel, 0, 0);
rows.Controls.Add(_addressLabel, 0, 1);
rows.Controls.Add(hint, 0, 2);
panel.Controls.Add(rows);
return panel;
}
private static void StyleFooterLabel(Label label, Font font, Color colour)
{
label.Dock = DockStyle.Fill;
label.AutoSize = false;
label.BackColor = SnesTheme.PanelFill;
label.ForeColor = colour;
label.Font = font;
label.TextAlign = ContentAlignment.MiddleLeft;
label.Margin = Padding.Empty;
}
private static TableLayoutPanel NewGrid(int columns, int rows)
{
var grid = new TableLayoutPanel
{
Dock = DockStyle.Fill,
BackColor = SnesTheme.PanelFill,
ColumnCount = columns,
RowCount = rows,
};
for (int c = 0; c < columns; c++)
{
grid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / columns));
}
for (int r = 0; r < rows; r++)
{
grid.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / rows));
}
return grid;
}
// ----------------------------------------------------------- data wiring
private void HookFields()
{
foreach (var field in AllFields)
{
field.Dock = DockStyle.Fill;
field.Margin = new Padding(10, 3, 10, 3);
field.UserEdited += (_, _) => PushToModel();
}
// Gold is party wide, so it is not part of the per-character push.
_gold.Dock = DockStyle.Fill;
_gold.Margin = new Padding(10, 3, 10, 3);
_gold.UserEdited += (_, _) => PushGold();
}
private void PushGold()
{
if (_loading || _save is null)
{
return;
}
_save.Gold = _gold.Value;
_save.MarkDirty();
UpdateStatus();
}
private void PushToModel()
{
if (_loading || _current is null || _save is null)
{
return;
}
_current.Atk = _atk.Value;
_current.Def = _def.Value;
_current.Act = _act.Value;
_current.Mag = _mag.Value;
_current.Int = _int.Value;
_current.Fate = _fate.Value;
_current.Exp = _exp.Value;
_current.HpCur = _hp.Value;
_current.HpMax = _hp.SecondValue;
_current.ApCur = _ap.Value;
_current.ApMax = _ap.SecondValue;
_current.Strength = _str.Value;
_current.Vigor = _vigor.Value;
_current.Agility = _agil.Value;
_current.Wisdom = _wisdom.Value;
_current.Luck = _luck.Value;
_save.MarkDirty();
UpdateStatus();
}
/// <summary>Loads the party wide values, which do not depend on the picked character.</summary>
private void BindSave()
{
if (_save is null)
{
return;
}
_loading = true;
_gold.Value = _save.Gold;
_loading = false;
}
private void BindCharacter()
{
if (_save is null)
{
return;
}
_current = _slotPicker.SelectedItem is SlotEntry entry ? entry.Character : null;
if (_current is null)
{
return;
}
_loading = true;
_portrait.CharacterName = _current.Name;
_nameLabel.Text = _current.Name;
_atk.Value = _current.Atk;
_def.Value = _current.Def;
_act.Value = _current.Act;
_mag.Value = _current.Mag;
_int.Value = _current.Int;
_fate.Value = _current.Fate;
_level.Value = _current.Level;
_exp.Value = _current.Exp;
_hp.Value = _current.HpCur;
_hp.SecondValue = _current.HpMax;
_ap.Value = _current.ApCur;
_ap.SecondValue = _current.ApMax;
_str.Value = _current.Strength;
_vigor.Value = _current.Vigor;
_agil.Value = _current.Agility;
_wisdom.Value = _current.Wisdom;
_luck.Value = _current.Luck;
_wepn.Value = _current.Weapon;
_shld.Value = _current.Shield;
_armr.Value = _current.Armour;
_helm.Value = _current.Helmet;
_etc1.Value = _current.Etc1;
_etc2.Value = _current.Etc2;
_loading = false;
BuildSpellRows();
// Worth saying out loud when there is no save block copy: those edits stand
// only until the game writes SRAM from the live record at the next save point.
string mirror = _current.HasSaveBlockRecord ? string.Empty : " no save block record";
_addressLabel.Text =
$"Slot {_current.Slot} record at ${_current.Address:X6} {BofCharacter.RecordSize} bytes{mirror}";
UpdateStatus();
}
private sealed record SlotEntry(BofCharacter Character)
{
// Records left behind by characters who have dropped out are still perfectly
// readable, and still worth editing for when they come back, so they are
// listed rather than hidden - just marked so the roster is not misread.
public override string ToString()
{
string reserve = Character.IsInParty ? string.Empty : " (not in party)";
return $"{Character.Slot} {Character.DisplayName} Lv {Character.Level}{reserve}";
}
}
// ------------------------------------------------------------ file verbs
private void TryReopenLastFile()
{
string? last = Settings.LastFile;
if (!string.IsNullOrWhiteSpace(last) && File.Exists(last))
{
LoadFile(last, quiet: true);
}
}
private void OpenFile()
{
if (!ConfirmDiscard())
{
return;
}
using var dialog = new OpenFileDialog
{
Title = "Open a SNES9x save state",
Filter = FileFilter,
InitialDirectory = InitialDirectory(),
};
if (dialog.ShowDialog(this) == DialogResult.OK)
{
LoadFile(dialog.FileName, quiet: false);
}
}
private string InitialDirectory()
{
string? last = _save?.FilePath ?? Settings.LastFile;
string? dir = string.IsNullOrWhiteSpace(last) ? null : Path.GetDirectoryName(last);
return Directory.Exists(dir) ? dir! : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
private void LoadFile(string path, bool quiet)
{
try
{
var save = BofSave.Load(path);
var present = save.Characters.Where(c => c.IsPresent).ToList();
if (present.Count == 0)
{
if (!quiet)
{
Warn($"No Breath of Fire party data was found in:\n\n{path}\n\n" +
"Check that this state is from Breath of Fire and was taken after the game had started.");
}
return;
}
_save = save;
Settings.LastFile = path;
_slotPicker.Items.Clear();
foreach (var character in present)
_slotPicker.Items.Add(new SlotEntry(character));
_slotPicker.SelectedIndex = 0;
UpdateEnabledState();
BindSave();
BuildItemRows();
BindCharacter();
}
catch (Exception ex) when (ex is IOException or InvalidDataException or KeyNotFoundException)
{
if (!quiet)
{
Warn($"Could not read that save state.\n\n{ex.Message}");
}
}
}
private void SaveFile(string? path)
{
if (_save is null)
{
return;
}
foreach (var field in AllFields)
{
field.CommitPending();
}
foreach (var (field, slot) in _itemFields)
{
field.CommitPending();
slot.Quantity = field.Value;
}
_gold.CommitPending();
PushToModel();
PushGold();
try
{