-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1675 lines (1471 loc) · 68.5 KB
/
Copy pathMainForm.cs
File metadata and controls
1675 lines (1471 loc) · 68.5 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 RaGuideDesigner.Commands;
using RaGuideDesigner.Models;
using RaGuideDesigner.Services;
using RaGuideDesigner.Views;
using RAGuideDesigner.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace RaGuideDesigner
{
public partial class MainForm : Form
{
private WikiGuide _currentProject;
private readonly ProjectService _projectService;
private readonly RaJsonParserService _raJsonParserService;
private readonly MarkdownGenerationService _markdownGenerationService;
private readonly MarkdownImportService _markdownImportService;
private readonly UndoRedoService _undoRedoService;
private readonly TreeViewManagerService _treeViewManagerService;
private string? _currentProjectPath = null;
private bool _isDirty = false;
private bool _isProgrammaticChange = false;
private Control? _contextControlForEditMenu;
private readonly List<TreeNode> _selectedNodes = new List<TreeNode>();
private TreeNode? _dragStartNode;
private Point _dragStartPoint;
private TreeNode? _rightClickedNode;
// These are the different editor panels (User Controls) that get swapped in and out.
private readonly HeaderEditor _headerEditor;
private readonly AchievementEditor _achievementEditor;
private readonly CategoryEditor _categoryEditor;
private readonly WalkthroughsEditor _walkthroughsEditor;
private readonly LeaderboardEditor _leaderboardEditor;
private readonly CreditsEditor _creditsEditor;
private readonly CollectibleEditor _collectibleEditor;
private readonly LeaderboardRootEditor _leaderboardRootEditor;
private readonly Panel _placeholderPanel;
public MainForm()
{
InitializeComponent();
this.FormClosing += MainForm_FormClosing;
spellCheckToolStripMenuItem.Checked = Settings.Default.IsSpellCheckEnabled;
if (Settings.Default.IsSpellCheckEnabled)
{
SpellCheckService.Instance.Initialize();
}
// --- RECENT FILES: Initialize settings if they don't exist ---
if (Settings.Default.RecentFiles == null)
{
Settings.Default.RecentFiles = new System.Collections.Specialized.StringCollection();
}
UpdateRecentFilesMenu();
// --- END RECENT FILES ---
_currentProject = new WikiGuide();
_projectService = new ProjectService();
_raJsonParserService = new RaJsonParserService();
_markdownGenerationService = new MarkdownGenerationService();
_markdownImportService = new MarkdownImportService();
_undoRedoService = new UndoRedoService();
_treeViewManagerService = new TreeViewManagerService();
_undoRedoService.CommandHistoryChanged += OnCommandHistoryChanged;
_undoRedoService.CommandUndone += (cmd) => OnUndoRedo(cmd, true);
_undoRedoService.CommandRedone += (cmd) => OnUndoRedo(cmd, false);
_headerEditor = new HeaderEditor(_undoRedoService) { Dock = DockStyle.Fill };
_achievementEditor = new AchievementEditor(_undoRedoService) { Dock = DockStyle.Fill };
_categoryEditor = new CategoryEditor(_undoRedoService) { Dock = DockStyle.Fill };
_walkthroughsEditor = new WalkthroughsEditor(_undoRedoService) { Dock = DockStyle.Fill };
_leaderboardEditor = new LeaderboardEditor(_undoRedoService) { Dock = DockStyle.Fill };
_creditsEditor = new CreditsEditor(_undoRedoService) { Dock = DockStyle.Fill };
_collectibleEditor = new CollectibleEditor(_undoRedoService) { Dock = DockStyle.Fill };
_leaderboardRootEditor = new LeaderboardRootEditor(_undoRedoService) { Dock = DockStyle.Fill };
_placeholderPanel = new Panel { Dock = DockStyle.Fill };
var placeholderLabel = new Label { Text = "Select an item from the tree to edit it.", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleCenter };
_placeholderPanel.Controls.Add(placeholderLabel);
pnlEditor.Controls.AddRange(new Control[] {
_headerEditor, _achievementEditor, _categoryEditor,
_walkthroughsEditor, _leaderboardEditor, _creditsEditor,
_collectibleEditor, _leaderboardRootEditor, _placeholderPanel
});
CreateNewGuide();
}
public void SetDirty()
{
_isDirty = true;
UpdateWindowTitle();
}
// Recursively finds the currently focused control, which is useful for context-sensitive menus.
private Control? FindFocusedControl(Control container)
{
foreach (Control child in container.Controls)
{
if (child.Focused) return child;
var focusedChild = FindFocusedControl(child);
if (focusedChild != null) return focusedChild;
}
return null;
}
private void OnCommandHistoryChanged(ICommand? command)
{
_isDirty = true;
UpdateWindowTitle();
UpdateEditMenuState();
if (command != null)
{
ScheduleTreeViewUpdate(command, isUndo: false);
}
}
private void OnUndoRedo(ICommand command, bool isUndo)
{
_isDirty = true;
UpdateWindowTitle();
UpdateEditMenuState();
ScheduleTreeViewUpdate(command, isUndo);
}
// Schedules a UI update to happen safely after the current operation finishes.
// This prevents issues with modifying collections while they are being iterated over.
private void ScheduleTreeViewUpdate(ICommand command, bool isUndo)
{
if (this.IsHandleCreated)
{
this.BeginInvoke(new Action(() =>
{
UpdateTreeViewFromCommand(command, isUndo);
_headerEditor.UpdateStatistics(_currentProject);
// Also refresh the category editor stats if it's visible.
// This is less disruptive than a full SetData() call which causes focus loss.
if (_categoryEditor.Visible)
{
_categoryEditor.UpdateStatistics();
}
}));
}
}
// Commits changes in the currently visible editor panel.
private void CommitPendingEditorChanges()
{
pnlEditor.Controls.OfType<BaseEditorControl>().FirstOrDefault(c => c.Visible)?.CommitChanges();
}
#region Unsaved Changes Prompt
private bool PromptToSaveChanges()
{
if (!_isDirty) return true;
var result = MessageBox.Show(
"You have unsaved changes. Would you like to save them now?",
"Unsaved Changes",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
switch (result)
{
case DialogResult.Yes:
saveProjectToolStripMenuItem_Click(this, EventArgs.Empty);
return !_isDirty; // Return true only if the save was successful.
case DialogResult.No:
return true;
case DialogResult.Cancel:
return false;
default:
return false;
}
}
private void MainForm_FormClosing(object? sender, FormClosingEventArgs e)
{
CommitPendingEditorChanges();
if (!PromptToSaveChanges())
{
e.Cancel = true;
}
}
#endregion
#region File Menu Handlers
private void newGuideToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
if (PromptToSaveChanges())
{
CreateNewGuide();
}
}
private void loadProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
if (!PromptToSaveChanges()) return;
using (var ofd = new OpenFileDialog())
{
ofd.Filter = "RA Guide Project (*.raguide)|*.raguide|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
LoadProject(ofd.FileName);
}
}
}
private void LoadProject(string filePath)
{
if (!File.Exists(filePath))
{
var result = MessageBox.Show($"The file '{Path.GetFileName(filePath)}' could not be found.\n\nWould you like to remove it from the recent projects list?", "File Not Found", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (result == DialogResult.Yes)
{
RemoveRecentFile(filePath);
}
return;
}
_headerEditor.ClearCaches();
var loadedProject = _projectService.Load(filePath);
if (loadedProject != null)
{
_currentProject = loadedProject;
_currentProjectPath = filePath;
_undoRedoService.Clear();
_isDirty = false;
UpdateWindowTitle();
PopulateTreeView();
AddRecentFile(filePath);
}
else
{
MessageBox.Show("Failed to load project file.", "Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void saveProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
if (string.IsNullOrEmpty(_currentProjectPath))
{
saveProjectAsToolStripMenuItem_Click(sender, e);
}
else
{
_projectService.Save(_currentProject, _currentProjectPath);
_isDirty = false;
UpdateWindowTitle();
AddRecentFile(_currentProjectPath);
}
}
private void saveProjectAsToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
using (var sfd = new SaveFileDialog())
{
sfd.Filter = "RA Guide Project (*.raguide)|*.raguide|All files (*.*)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
_currentProjectPath = sfd.FileName;
saveProjectToolStripMenuItem_Click(sender, e);
}
}
}
private void AddRecentFile(string path)
{
var recentFiles = Settings.Default.RecentFiles;
recentFiles.Remove(path);
recentFiles.Insert(0, path);
while (recentFiles.Count > 10)
{
recentFiles.RemoveAt(10);
}
Settings.Default.Save();
UpdateRecentFilesMenu();
}
private void RemoveRecentFile(string path)
{
Settings.Default.RecentFiles.Remove(path);
Settings.Default.Save();
UpdateRecentFilesMenu();
}
private void UpdateRecentFilesMenu()
{
recentProjectsToolStripMenuItem.DropDownItems.Clear();
var recentFiles = Settings.Default.RecentFiles;
if (recentFiles != null && recentFiles.Count > 0)
{
recentProjectsToolStripMenuItem.Enabled = true;
// Changed loop variable to nullable 'string?' to resolve CS8600 warning when iterating a StringCollection.
foreach (string? path in recentFiles)
{
if (string.IsNullOrEmpty(path)) continue;
var menuItem = new ToolStripMenuItem(Path.GetFileName(path))
{
Tag = path
};
menuItem.Click += RecentFile_Click;
recentProjectsToolStripMenuItem.DropDownItems.Add(menuItem);
}
}
else
{
recentProjectsToolStripMenuItem.Enabled = false;
}
}
private void RecentFile_Click(object? sender, EventArgs e)
{
if (sender is ToolStripMenuItem menuItem && menuItem.Tag is string path)
{
CommitPendingEditorChanges();
if (PromptToSaveChanges())
{
LoadProject(path);
}
}
}
private void importFromRAJSONToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
bool shouldOverwrite = true;
if (_currentProject.AchievementCategories.SelectMany(c => c.Achievements).Any())
{
var result = MessageBox.Show(
"You have an active project. Would you like to merge achievement data (titles, points, badges) from the JSON file into your current project?\n\nChoosing 'No' will discard your current project and import a new one from the JSON file.",
"Merge or Overwrite?",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Cancel) return;
shouldOverwrite = (result == DialogResult.No);
}
if (shouldOverwrite && !PromptToSaveChanges()) return;
using (var ofd = new OpenFileDialog())
{
ofd.Filter = "JSON File (*.json)|*.json|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_headerEditor.ClearCaches();
var jsonData = _raJsonParserService.Parse(ofd.FileName);
if (shouldOverwrite)
{
var newProject = CreateDefaultGuide();
newProject.GameTitle = jsonData.GameTitle;
newProject.MasteryIconUrl = jsonData.MasteryIconUrl;
newProject.AchievementCategories = jsonData.AchievementCategories;
newProject.Leaderboards = jsonData.Leaderboards;
_currentProject = newProject;
AddAsolidSnackCreditIfNeeded(_currentProject);
_currentProjectPath = null;
_undoRedoService.Clear();
_isDirty = true;
UpdateWindowTitle();
PopulateTreeView();
}
else
{
if (!string.Equals(_currentProject.GameTitle.Trim(), jsonData.GameTitle.Trim(), StringComparison.OrdinalIgnoreCase))
{
var mismatchResult = MessageBox.Show(
$"Warning: The JSON file appears to be for a different game ('{jsonData.GameTitle}') than your current project ('{_currentProject.GameTitle}').\n\nDo you want to proceed with merging the data anyway?",
"Game Title Mismatch",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (mismatchResult == DialogResult.No) return;
}
MergeAchievementData(jsonData);
MessageBox.Show("Achievement titles, points, and badge URLs have been successfully merged into the current project.", "Merge Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Failed to parse RA JSON file. Error: {ex.Message}", "Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
// Handles merging achievement data (like titles and points) from a JSON file into the current project.
private void MergeAchievementData(WikiGuide sourceGuide)
{
var commands = new List<ICommand>();
var sourceAchievements = sourceGuide.AchievementCategories
.SelectMany(c => c.Achievements)
.ToDictionary(a => a.Id);
foreach (var achievement in _currentProject.AchievementCategories.SelectMany(c => c.Achievements))
{
if (sourceAchievements.TryGetValue(achievement.Id, out var sourceAch))
{
if (!string.Equals(achievement.Title, sourceAch.Title, StringComparison.Ordinal))
{
commands.Add(new EditPropertyCommand(achievement, nameof(Achievement.Title), achievement.Title, sourceAch.Title));
}
if (achievement.Points != sourceAch.Points)
{
commands.Add(new EditPropertyCommand(achievement, nameof(Achievement.Points), achievement.Points, sourceAch.Points));
}
if (achievement.BadgeUrl != sourceAch.BadgeUrl)
{
commands.Add(new EditPropertyCommand(achievement, nameof(Achievement.BadgeUrl), achievement.BadgeUrl, sourceAch.BadgeUrl));
}
}
}
if (commands.Any())
{
_undoRedoService.Execute(new CompositeCommand(commands));
}
}
private void importFromMarkdownToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
if (!PromptToSaveChanges()) return;
using (var ofd = new OpenFileDialog())
{
ofd.Filter = "RA Wiki Guide (*.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_headerEditor.ClearCaches();
_currentProject = _markdownImportService.Parse(ofd.FileName);
AddAsolidSnackCreditIfNeeded(_currentProject);
_currentProjectPath = null;
_undoRedoService.Clear();
_isDirty = true;
UpdateWindowTitle();
PopulateTreeView();
MessageBox.Show("Markdown guide imported successfully!", "Import Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to parse Markdown file. The file may not match the expected format.\n\nError: {ex.Message}", "Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void generateMarkdownToolStripMenuItem_Click(object sender, EventArgs e)
{
CommitPendingEditorChanges();
var markdown = _markdownGenerationService.Generate(_currentProject);
using (var sfd = new SaveFileDialog())
{
sfd.Filter = "Text File (*.txt)|*.txt";
sfd.FileName = "Markdown.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllText(sfd.FileName, markdown);
MessageBox.Show("Markdown file generated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e) => Application.Exit();
#endregion
#region Edit Menu Handlers
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
Control? context = _contextControlForEditMenu ?? FindFocusedControl(this);
if (context is RichTextBox rtb && rtb.CanUndo)
{
rtb.Undo();
}
else
{
CommitPendingEditorChanges();
_undoRedoService.Undo();
}
UpdateEditMenuState();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
Control? context = _contextControlForEditMenu ?? FindFocusedControl(this);
if (context is RichTextBox rtb && rtb.CanRedo)
{
rtb.Redo();
}
else
{
CommitPendingEditorChanges();
_undoRedoService.Redo();
}
UpdateEditMenuState();
}
private void editToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
_contextControlForEditMenu = FindFocusedControl(this);
UpdateEditMenuState();
}
private void UpdateEditMenuState()
{
Control? currentContext = _contextControlForEditMenu ?? FindFocusedControl(this);
bool canGlobalUndo = _undoRedoService.CanUndo;
bool canGlobalRedo = _undoRedoService.CanRedo;
bool canLocalUndo = false;
bool canLocalRedo = false;
if (currentContext is RichTextBox rtb)
{
canLocalUndo = rtb.CanUndo;
canLocalRedo = rtb.CanRedo;
}
undoToolStripMenuItem.Enabled = canGlobalUndo || canLocalUndo;
redoToolStripMenuItem.Enabled = canGlobalRedo || canLocalRedo;
}
private void spellCheckToolStripMenuItem_Click(object sender, EventArgs e)
{
Settings.Default.IsSpellCheckEnabled = spellCheckToolStripMenuItem.Checked;
Settings.Default.Save();
MessageBox.Show(
"Please restart the application for the spell check setting to take full effect.",
"Restart Required",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
#endregion
#region Help Menu Handlers
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var aboutForm = new AboutForm())
{
aboutForm.ShowDialog(this);
}
}
private void tutorialToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var ps = new System.Diagnostics.ProcessStartInfo("https://cyslaytor.github.io/RAGuideDesigner/")
{
UseShellExecute = true,
Verb = "open"
};
System.Diagnostics.Process.Start(ps);
}
catch (Exception)
{
MessageBox.Show("Could not open the tutorial link.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region UI and Data Logic
private string ReadEmbeddedResource(string resourceName)
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
// Instead of asking for a specific name, find the resource that matches.
// This solves issues where the compiler gives it a slightly different name than expected.
string? actualResourceName = assembly.GetManifestResourceNames()
.FirstOrDefault(name => name.EndsWith("Default.txt"));
if (string.IsNullOrEmpty(actualResourceName))
{
// Add all found names to the error for easier debugging if it fails again.
string allNames = string.Join("\n", assembly.GetManifestResourceNames());
throw new FileNotFoundException($"Embedded resource ending with 'Default.txt' not found. Available resources:\n{allNames}");
}
using (Stream? stream = assembly.GetManifestResourceStream(actualResourceName))
{
// The original null check is still good practice.
if (stream == null)
{
throw new FileNotFoundException($"Could not load the embedded resource stream for '{actualResourceName}'.");
}
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
private WikiGuide CreateDefaultGuide()
{
string defaultMarkdown = ReadEmbeddedResource("RAGuideDesigner.Resources.Default.txt");
return _markdownImportService.ParseFromString(defaultMarkdown);
}
private void CreateNewGuide()
{
_headerEditor.ClearCaches();
_currentProject = CreateDefaultGuide();
_currentProjectPath = null;
_undoRedoService.Clear();
_isDirty = false;
UpdateWindowTitle();
PopulateTreeView();
}
private Credit GetDefaultCredit() => new Credit
{
Username = "ASolidSnack",
AvatarUrl = "https://media.retroachievements.org/UserPic/ASolidSnack.png",
Role = "🟉 Contributor | RA-Guide Design",
ContributionDetails = "Provided the template design and feature specifications for this tool."
};
private void AddAsolidSnackCreditIfNeeded(WikiGuide guide)
{
if (!guide.Credits.Any(c => c.Username.Equals("ASolidSnack", StringComparison.OrdinalIgnoreCase)))
{
guide.Credits.Add(GetDefaultCredit());
}
}
private void PopulateTreeView()
{
_isProgrammaticChange = true;
tvGuideStructure.BeginUpdate();
tvGuideStructure.Nodes.Clear();
_treeViewManagerService.PopulateTreeView(tvGuideStructure, _currentProject);
ClearAndSelectNode(tvGuideStructure.Nodes[0]);
UpdateSelectionAppearance();
tvGuideStructure.SelectedNode = tvGuideStructure.Nodes[0];
tvGuideStructure.EndUpdate();
_isProgrammaticChange = false;
UpdateEditorPanel();
}
private void tvGuideStructure_AfterSelect(object sender, TreeViewEventArgs e)
{
if (_isProgrammaticChange) return;
UpdateEditorPanel();
}
// The main logic for showing the correct editor panel based on the selected tree node.
private void UpdateEditorPanel()
{
var lastSelectedNode = _selectedNodes.LastOrDefault() ?? tvGuideStructure.SelectedNode;
if (lastSelectedNode?.Tag == null)
{
ShowEditor(_placeholderPanel);
return;
}
var tag = lastSelectedNode.Tag;
if (tag is string stringTag)
{
switch (stringTag)
{
case "Header": ShowEditor(_headerEditor, _currentProject); break;
case "Walkthroughs": ShowEditor(_walkthroughsEditor, _currentProject); break;
case "LeaderboardGuideRoot": ShowEditor(_leaderboardRootEditor, _currentProject); break;
default: ShowEditor(_placeholderPanel); break;
}
}
else if (tag is IGuideItem item)
{
switch (item)
{
case Achievement ach:
var parentNode = lastSelectedNode.Parent;
var parentCategory = parentNode?.Tag as AchievementCategory;
if (parentCategory != null && parentCategory.IsCollectible)
{
ShowEditor(_collectibleEditor, ach, parentCategory);
}
else
{
ShowEditor(_achievementEditor, ach, parentCategory);
}
break;
case AchievementCategory cat: ShowEditor(_categoryEditor, cat); break;
case Leaderboard lb: ShowEditor(_leaderboardEditor, lb); break;
case Credit credit: ShowEditor(_creditsEditor, credit); break;
default: ShowEditor(_placeholderPanel); break;
}
}
else
{
ShowEditor(_placeholderPanel);
}
}
// Swaps the visible editor panel in the UI.
private void ShowEditor(Control editor, object? data = null, object? parentData = null)
{
CommitPendingEditorChanges();
foreach (Control c in pnlEditor.Controls) c.Visible = false;
var method = editor.GetType().GetMethod("SetData");
if (method?.GetParameters().Length == 2)
{
method.Invoke(editor, new[] { data, parentData });
}
else if (method?.GetParameters().Length == 1)
{
method.Invoke(editor, new[] { data });
}
editor.Visible = true;
}
private void UpdateWindowTitle()
{
var title = "RetroAchievements Guide Designer";
if (!string.IsNullOrEmpty(_currentProjectPath))
title += $" - {System.IO.Path.GetFileName(_currentProjectPath)}";
if (_isDirty) title += "*";
this.Text = title;
}
#endregion
#region Multi-Select, Context Menu & Drag-Drop Logic
private void tvGuideStructure_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
_rightClickedNode = e.Node;
if (!_selectedNodes.Contains(e.Node))
{
ClearAndSelectNode(e.Node);
UpdateSelectionAppearance();
tvGuideStructure.SelectedNode = e.Node;
}
return;
}
_isProgrammaticChange = true;
if (ModifierKeys == Keys.Control)
{
if (_selectedNodes.Contains(e.Node))
_selectedNodes.Remove(e.Node);
else
_selectedNodes.Add(e.Node);
}
else if (ModifierKeys == Keys.Shift)
{
var lastNode = _selectedNodes.LastOrDefault();
if (lastNode != null && lastNode.Parent == e.Node.Parent && lastNode != e.Node)
{
var parent = e.Node.Parent;
if (parent != null)
{
var nodes = parent.Nodes;
int index1 = nodes.IndexOf(lastNode);
int index2 = nodes.IndexOf(e.Node);
int start = Math.Min(index1, index2);
int end = Math.Max(index1, index2);
for (int i = start; i <= end; i++)
{
if (!_selectedNodes.Contains(nodes[i]))
_selectedNodes.Add(nodes[i]);
}
}
}
else
{
ClearAndSelectNode(e.Node);
}
}
else
{
ClearAndSelectNode(e.Node);
}
UpdateSelectionAppearance();
tvGuideStructure.SelectedNode = e.Node;
_isProgrammaticChange = false;
tvGuideStructure_AfterSelect(sender, new TreeViewEventArgs(e.Node));
tvGuideStructure.Focus();
}
private void ClearAndSelectNode(TreeNode? node)
{
_selectedNodes.Clear();
if (node != null) _selectedNodes.Add(node);
}
private void UpdateSelectionAppearance()
{
foreach (TreeNode node in tvGuideStructure.Nodes)
{
ResetNodeAppearance(node);
}
foreach (var node in _selectedNodes)
{
node.BackColor = SystemColors.Highlight;
node.ForeColor = SystemColors.HighlightText;
}
}
private void ResetNodeAppearance(TreeNode rootNode)
{
rootNode.BackColor = tvGuideStructure.BackColor;
rootNode.ForeColor = tvGuideStructure.ForeColor;
foreach (TreeNode node in rootNode.Nodes)
{
ResetNodeAppearance(node);
}
}
private void tvGuideStructure_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down))
{
e.SuppressKeyPress = true;
if (e.KeyCode == Keys.Up)
{
MoveSelectedItemsUp();
}
else
{
MoveSelectedItemsDown();
}
}
else if (e.Shift && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down))
{
e.SuppressKeyPress = true;
TreeNode? lastSelected = _selectedNodes.LastOrDefault();
if (lastSelected == null) return;
TreeNode? nextNode = (e.KeyCode == Keys.Up) ? lastSelected.PrevVisibleNode : lastSelected.NextVisibleNode;
if (nextNode != null)
{
// If the next node is already selected, and we are moving away from it, deselect the last node.
if (_selectedNodes.Contains(nextNode))
{
_selectedNodes.Remove(lastSelected);
}
else
{
_selectedNodes.Add(nextNode);
}
tvGuideStructure.SelectedNode = nextNode;
UpdateSelectionAppearance();
UpdateEditorPanel();
}
}
else if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
e.SuppressKeyPress = true; // Prevent default TreeView behavior
TreeNode? currentNode = tvGuideStructure.SelectedNode;
if (currentNode == null) return;
TreeNode? nextNode = (e.KeyCode == Keys.Up) ? currentNode.PrevVisibleNode : currentNode.NextVisibleNode;
if (nextNode != null)
{
CommitPendingEditorChanges(); // Save any changes from the current editor
// Use our custom selection logic
ClearAndSelectNode(nextNode);
UpdateSelectionAppearance();
// Update the TreeView's own selection and the editor panel
_isProgrammaticChange = true;
tvGuideStructure.SelectedNode = nextNode;
_isProgrammaticChange = false;
UpdateEditorPanel();
}
}
}
private enum MenuType { ExpandCollapse, EditItems }
private void ShowContextMenu(MenuType type)
{
bool isExpandCollapse = type == MenuType.ExpandCollapse;
expandAllToolStripMenuItem.Visible = isExpandCollapse;
collapseAllToolStripMenuItem.Visible = isExpandCollapse;
toolStripSeparator5.Visible = isExpandCollapse;
foreach (ToolStripItem item in cmTree.Items)
{
if (item != expandAllToolStripMenuItem && item != collapseAllToolStripMenuItem && item != toolStripSeparator5)
{
item.Visible = !isExpandCollapse;
}
}
if (isExpandCollapse) return;
var selectedItems = _selectedNodes.Select(n => n.Tag).ToList();
var clickedItem = _rightClickedNode?.Tag;
addAchievementCategoryToolStripMenuItem.Visible = clickedItem is string s && s == "AchievementGuideRoot";
addAchievementToolStripMenuItem.Visible = clickedItem is AchievementCategory && _selectedNodes.Count == 1;
addLeaderboardToolStripMenuItem.Visible = clickedItem is string s2 && s2 == "LeaderboardGuideRoot";
addCreditToolStripMenuItem.Visible = clickedItem is string s3 && s3 == "CreditsRoot";
if (clickedItem is AchievementCategory category)
{
markAsCollectibleToolStripMenuItem.Visible = true;
markAsCollectibleToolStripMenuItem.Checked = category.IsCollectible;
markAsCollectibleToolStripMenuItem.Enabled = !category.Title.Equals("Progression", StringComparison.OrdinalIgnoreCase);
markAsSimpleToolStripMenuItem.Visible = true;
markAsSimpleToolStripMenuItem.Checked = category.IsSimple;
markAsSimpleToolStripMenuItem.Enabled = !category.Title.Equals("Progression", StringComparison.OrdinalIgnoreCase) && !category.IsCollectible;
}
else
{
markAsCollectibleToolStripMenuItem.Visible = false;
markAsSimpleToolStripMenuItem.Visible = false;
}
var firstItem = selectedItems.FirstOrDefault();
if (firstItem == null) return;
bool areAllSameType = selectedItems.All(i => i?.GetType() == firstItem.GetType());
bool canMoveOrDelete = areAllSameType && firstItem is IGuideItem;
bool canDuplicate = areAllSameType && (firstItem is Achievement || firstItem is AchievementCategory);
deleteToolStripMenuItem.Visible = canMoveOrDelete;
duplicateToolStripMenuItem.Visible = canDuplicate;
moveUpToolStripMenuItem.Visible = canMoveOrDelete;
moveDownToolStripMenuItem.Visible = canMoveOrDelete;
toolStripSeparator4.Visible = addAchievementCategoryToolStripMenuItem.Visible || addAchievementToolStripMenuItem.Visible || addLeaderboardToolStripMenuItem.Visible || addCreditToolStripMenuItem.Visible;
toolStripSeparator3.Visible = duplicateToolStripMenuItem.Visible || moveUpToolStripMenuItem.Visible || moveDownToolStripMenuItem.Visible || markAsCollectibleToolStripMenuItem.Visible;
}
private void cmTree_Opening(object sender, CancelEventArgs e)
{
if (_rightClickedNode == null)
{
e.Cancel = true;
return;
}
var tag = _rightClickedNode.Tag;
if (tag is WikiGuide)
{
ShowContextMenu(MenuType.ExpandCollapse);
}
else if (tag is string strTag && strTag == "AchievementGuideRoot")
{
ShowContextMenu(MenuType.EditItems);
expandAllToolStripMenuItem.Visible = true;
collapseAllToolStripMenuItem.Visible = true;
toolStripSeparator5.Visible = true;
}