-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlugin.cs
More file actions
1344 lines (1064 loc) · 43.1 KB
/
Copy pathPlugin.cs
File metadata and controls
1344 lines (1064 loc) · 43.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
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 Dalamud.Game.Command;
using Dalamud.IoC;
using Dalamud.Interface;
using Dalamud.Game.Text.SeStringHandling;
using Dalamud.Interface.Windowing;
using Dalamud.Plugin;
using Dalamud.Plugin.Services;
using CreateXIV.Windows;
using CreateXIV.Services;
using FFXIVClientStructs.FFXIV.Client.System.String;
using FFXIVClientStructs.FFXIV.Client.UI;
using FFXIVClientStructs.FFXIV.Client.UI.Misc;
using FFXIVClientStructs.FFXIV.Client.UI.Shell;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json;
namespace CreateXIV;
public sealed unsafe class Plugin : IDalamudPlugin
{
[PluginService] internal static IDalamudPluginInterface PluginInterface { get; private set; } = null!;
[PluginService] internal static ICommandManager CommandManager { get; private set; } = null!;
[PluginService] internal static IChatGui ChatGui { get; private set; } = null!;
[PluginService] internal static IPluginLog Log { get; private set; } = null!;
[PluginService] internal static IDataManager DataManager { get; private set; } = null!;
[PluginService] internal static IFramework Framework { get; private set; } = null!;
private const string CreateCommandName = "/create";
private const string CreateAliasUsage = "Usage: /create <alias> <command|macro:##|shared:##> [category-Optional]\nExample: /create mv mastervolume\nUse /create list to print all aliases.";
private const ushort AliasListAliasColor = 43;
private const ushort AliasListCommandColor = 500;
public Configuration Configuration { get; init; }
public readonly WindowSystem WindowSystem = new("CreateXIV");
private ConfigWindow ConfigWindow { get; init; }
private MainWindow MainWindow { get; init; }
private readonly Dictionary<string, List<string>> registeredAliasCommands = new(StringComparer.OrdinalIgnoreCase);
// ===== Undo =====
private readonly Stack<List<AliasEntry>> undoStack = new();
// ===== Delayed alias execution =====
private readonly List<(string Alias, DateTime DueUtc)> pendingAliasRuns = new();
public Plugin()
{
Configuration = PluginInterface.GetPluginConfig() as Configuration ?? new Configuration();
NormalizeSavedAliases();
MigrateOldDefaultWaitOnce();
ConfigWindow = new ConfigWindow(this);
MainWindow = new MainWindow(this);
WindowSystem.AddWindow(ConfigWindow);
WindowSystem.AddWindow(MainWindow);
CommandManager.AddHandler(CreateCommandName, new CommandInfo(OnCreateCommand)
{
HelpMessage = "Opens the CreateXIV window, or creates an alias with /create <alias> <command|macro:##|shared:##> [category-Optional]."
});
RegisterAllAliasCommands();
PluginInterface.UiBuilder.Draw += WindowSystem.Draw;
PluginInterface.UiBuilder.OpenConfigUi += ToggleConfigUi;
PluginInterface.UiBuilder.OpenMainUi += ToggleMainUi;
Framework.Update += OnFrameworkUpdate;
Log.Information($"=== {PluginInterface.Manifest.Name} loaded ===");
}
public void Dispose()
{
PluginInterface.UiBuilder.Draw -= WindowSystem.Draw;
PluginInterface.UiBuilder.OpenConfigUi -= ToggleConfigUi;
PluginInterface.UiBuilder.OpenMainUi -= ToggleMainUi;
Framework.Update -= OnFrameworkUpdate;
UnregisterAllAliasCommands();
CommandManager.RemoveHandler(CreateCommandName);
WindowSystem.RemoveAllWindows();
ConfigWindow.Dispose();
MainWindow.Dispose();
}
internal void OpenDalamudPluginListForFeedback()
{
// Dalamud exposes this as a supported way to open the plugin installer with search text.
// The search string intentionally uses the plugin name without a space because that is how it is listed and how I was told to do so.
var opened = PluginInterface.OpenPluginInstallerTo(PluginInstallerOpenKind.AllPlugins, "CreateXIV");
if (!opened)
CommandManager.ProcessCommand("/xlplugins");
}
private void OnCreateCommand(string command, string args)
{
if (string.IsNullOrWhiteSpace(args))
{
MainWindow.Toggle();
return;
}
if (TryHandleCreateListCommand(args))
return;
if (TryCreateAliasFromChat(args, out var message, out var ok))
{
if (ok)
ChatGui.Print(message, "CreateXIV");
else
ChatGui.PrintError(message, "CreateXIV");
}
}
public void ToggleConfigUi() => ConfigWindow.Toggle();
internal void OpenSettingsWindow() => ConfigWindow.IsOpen = true;
internal void PrintConfirmation(string message)
{
// These messages are useful while editing aliases but some users prefer a quieter chat.
// Errors still bypass this helper so important failures will never be hidden.
if (Configuration.SendChatConfirmations)
ChatGui.Print(message, "CreateXIV");
}
private bool TryHandleCreateListCommand(string args)
{
if (!string.Equals((args ?? string.Empty).Trim(), "list", StringComparison.OrdinalIgnoreCase))
return false;
if (Configuration.Aliases.Count == 0)
{
ChatGui.Print("No aliases registered.", "CreateXIV");
return true;
}
foreach (var entry in Configuration.Aliases
.OrderBy(x => NormalizeAlias(x.Alias), StringComparer.OrdinalIgnoreCase))
{
var alias = NormalizeAlias(entry.Alias);
var target = entry.Kind == AliasKind.Command
? EnsureSlashCommand(entry.Command)
: NormalizeCommand(entry.Command);
if (string.IsNullOrWhiteSpace(alias) || string.IsNullOrWhiteSpace(target))
continue;
var line = new SeStringBuilder()
.AddUiForeground(AliasListAliasColor)
.AddText(alias)
.AddUiForegroundOff()
.AddText(" -> ")
.AddUiForeground(AliasListCommandColor)
.AddText(target)
.AddUiForegroundOff()
.Build();
ChatGui.Print(line, "CreateXIV");
}
return true;
}
public void ToggleMainUi() => MainWindow.Toggle();
internal bool TryGetAliasProblem(AliasEntry entry, out string message)
{
message = string.Empty;
var alias = NormalizeAlias(entry.Alias);
var command = NormalizeCommand(entry.Command);
if (string.IsNullOrWhiteSpace(alias))
{
message = "Alias is empty.";
return true;
}
if (string.Equals(alias, CreateCommandName, StringComparison.OrdinalIgnoreCase))
{
message = "Alias uses CreateXIV's own /create command.";
return true;
}
if (string.IsNullOrWhiteSpace(command))
{
message = entry.Kind == AliasKind.Macro
? "Empty/deleted macro."
: "Target command is empty.";
return true;
}
if (entry.Kind == AliasKind.Macro)
{
if (!TryParseSingleMacroReference(command, out var macroRef))
{
message = "Invalid macro reference. Use macro:## or shared:##.";
return true;
}
if (!CommandSuggestionService.IsMacroAvailable(macroRef.Set, macroRef.Number))
{
message = "Empty/deleted macro.";
return true;
}
return false;
}
if (!IsKnownCommandAvailable(command))
{
message = "Target command no longer exists.";
return true;
}
return false;
}
internal bool TryGetAliasInputProblem(string aliasInput, out string message)
{
var alias = NormalizeAlias(aliasInput);
if (string.IsNullOrWhiteSpace(alias) || alias.Length <= 1)
{
message = "Alias cannot be empty.";
return true;
}
if (string.Equals(alias, CreateCommandName, StringComparison.OrdinalIgnoreCase))
{
message = "Alias /create is reserved by CreateXIV.";
return true;
}
if (CommandSuggestionService.IsKnownNativeCommand(DataManager, alias))
{
message = $"Alias {alias} conflicts with a native FFXIV command.";
return true;
}
if (CommandManager.Commands.ContainsKey(alias) &&
!Configuration.Aliases.Any(a => string.Equals(NormalizeAlias(a.Alias), alias, StringComparison.OrdinalIgnoreCase)))
{
message = $"Alias {alias} is already registered by Dalamud or another plugin.";
return true;
}
message = string.Empty;
return false;
}
internal IReadOnlyList<CommandSuggestion> GetCommandSuggestions(string query)
=> CommandSuggestionService.GetCommandSuggestions(this, query);
internal IReadOnlyList<MacroSuggestion> GetMacroSuggestions(string query)
=> CommandSuggestionService.GetMacroSuggestions(query);
internal string GetMacroDisplayName(string commandInput)
{
if (!TryParseSingleMacroReference(commandInput, out var macroRef))
return string.Empty;
return CommandSuggestionService.GetMacroDisplayName(macroRef.Set, macroRef.Number);
}
internal bool TryFindAliasUsingCommand(string commandInput, string? ignoredAliasInput, out string alias)
{
alias = string.Empty;
var wanted = NormalizeCommand(commandInput);
var ignored = NormalizeAlias(ignoredAliasInput ?? string.Empty);
if (string.IsNullOrWhiteSpace(wanted))
return false;
var existing = Configuration.Aliases.FirstOrDefault(a =>
!string.Equals(NormalizeAlias(a.Alias), ignored, StringComparison.OrdinalIgnoreCase) &&
string.Equals(NormalizeCommand(a.Command), wanted, StringComparison.OrdinalIgnoreCase));
if (existing == null)
return false;
alias = NormalizeAlias(existing.Alias);
return true;
}
internal bool IsAliasNameUsableForInput(string aliasInput)
=> !TryGetAliasInputProblem(aliasInput, out _);
internal bool IsKnownCommandAvailable(string commandInput)
{
if (!TryGetCommandToken(commandInput, out var token))
return false;
if (IsCreateXivManagedCommand(token))
return false;
return CommandManager.Commands.ContainsKey(token) ||
CommandSuggestionService.IsKnownNativeCommand(DataManager, token);
}
internal bool IsMacroReferenceAvailable(string commandInput)
{
if (!TryParseSingleMacroReference(commandInput, out var macroRef))
return false;
return CommandSuggestionService.IsMacroAvailable(macroRef.Set, macroRef.Number);
}
internal bool IsCreateXivManagedCommand(string commandInput)
{
if (!TryGetCommandToken(commandInput, out var token))
return false;
if (string.Equals(token, CreateCommandName, StringComparison.OrdinalIgnoreCase))
return true;
return Configuration.Aliases.Any(a =>
string.Equals(NormalizeAlias(a.Alias), token, StringComparison.OrdinalIgnoreCase));
}
public static bool TryGetCommandToken(string commandInput, out string token)
{
token = string.Empty;
var command = NormalizeCommand(commandInput);
if (string.IsNullOrWhiteSpace(command))
return false;
if (!command.StartsWith('/'))
command = "/" + command;
var split = command.Split([' ', '\t'], 2, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 0)
return false;
token = NormalizeAlias(split[0]);
return token.Length > 1;
}
private static string EnsureSlashCommand(string commandInput)
{
var command = NormalizeCommand(commandInput);
if (string.IsNullOrWhiteSpace(command))
return string.Empty;
return command.StartsWith('/') ? command : "/" + command;
}
// =====================
// Public helpers for UI
// =====================
public bool AddOrUpdateMacroAlias(string aliasInput, string commandInput, string category, bool pinned, out string message)
=> AddOrUpdateAliasInternal(aliasInput, commandInput, category, pinned, AliasKind.Macro, out message);
public bool AddOrUpdateCommandAlias(string aliasInput, string commandInput, string category, bool pinned, out string message)
=> AddOrUpdateAliasInternal(aliasInput, commandInput, category, pinned, AliasKind.Command, out message);
// Enable/disable alias without deleting the saved entry.
// Disabled aliases are unregistered from Dalamud so they cannot be executed from chat,
// while re-enabled aliases are only registered again if the saved target still validates.
// This is for keeping the toggle safe for broken/imported aliases and also makes the change undoable.
public void SetAliasEnabled(string aliasInput, bool enabled)
{
var normalizedAlias = NormalizeAlias(aliasInput);
var existing = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (existing == null || existing.Enabled == enabled)
return;
PushUndoSnapshot();
if (!enabled)
UnregisterAliasCommand(existing.Alias);
else if (ValidateEntry(existing, out _))
RegisterAliasCommand(existing);
existing.Enabled = enabled;
Configuration.Save();
}
public void SetAliasPinned(string aliasInput, bool pinned)
{
var normalizedAlias = NormalizeAlias(aliasInput);
var existing = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (existing == null || existing.Pinned == pinned)
return;
PushUndoSnapshot();
existing.Pinned = pinned;
SortAliases();
Configuration.Save();
}
public void SetAliasCooldownSeconds(string aliasInput, float seconds)
{
// The UI works in seconds with decimals, while the saved model uses milliseconds.
// Clamp here as well as in the slider so imported/old configs cannot sneak in odd values.
var normalizedAlias = NormalizeAlias(aliasInput);
var existing = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (existing == null)
return;
seconds = MathF.Min(5f, MathF.Max(0f, seconds));
var ms = Math.Max(0, (int)MathF.Round(seconds * 1000f));
if (existing.CooldownMs == ms)
return;
PushUndoSnapshot();
existing.CooldownMs = ms;
Configuration.Save();
}
public void DeleteAlias(string aliasInput)
{
var normalizedAlias = NormalizeAlias(aliasInput);
var existing = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (existing == null)
return;
PushUndoSnapshot();
UnregisterAliasCommand(existing.Alias);
Configuration.Aliases.Remove(existing);
Configuration.Save();
PrintConfirmation($"Deleted alias: {normalizedAlias}.");
}
public bool UndoLastChange(out string message)
{
if (undoStack.Count == 0)
{
message = "Nothing to undo.";
return false;
}
var previous = undoStack.Pop();
UnregisterAllAliasCommands();
Configuration.Aliases = previous.Select(CloneEntry).ToList();
NormalizeSavedAliases();
RegisterAllAliasCommands();
Configuration.Save();
message = "Undone.";
return true;
}
public bool DuplicateAlias(string aliasInput, out string message)
{
var normalizedAlias = NormalizeAlias(aliasInput);
var existing = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
message = "Alias not found.";
return false;
}
// Create a new alias name
var baseName = existing.Alias.TrimStart('/');
var newAlias = "/" + baseName + "_copy";
var n = 1;
while (Configuration.Aliases.Any(a => string.Equals(NormalizeAlias(a.Alias), NormalizeAlias(newAlias), StringComparison.OrdinalIgnoreCase)))
{
n++;
newAlias = "/" + baseName + "_copy" + n;
if (n > 9999)
break;
}
var copy = CloneEntry(existing);
copy.Number = GetNextAliasNumber();
copy.Alias = NormalizeAlias(newAlias);
if (!ValidateEntry(copy, out message))
return false;
if (!RegisterAliasCommand(copy))
{
message = $"Could not register alias {copy.Alias}.";
return false;
}
PushUndoSnapshot();
Configuration.Aliases.Add(copy);
SortAliases();
Configuration.Save();
message = $"Duplicated to: {copy.Alias}";
return true;
}
public bool TestAlias(string aliasInput, out string message)
{
var normalizedAlias = NormalizeAlias(aliasInput);
var entry = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (entry == null)
{
message = "Alias not found.";
return false;
}
ExecuteAlias(entry.Alias);
message = "Executed.";
return true;
}
public string ExportAliasesJson()
{
// Deterministic export order
var export = Configuration.Aliases
.OrderByDescending(x => x.Pinned)
.ThenBy(x => x.Number)
.ToList();
return JsonSerializer.Serialize(export, new JsonSerializerOptions
{
WriteIndented = true
});
}
public bool ImportAliasesJson(string json, out string message)
{
// Invalid clipboard content is a normal user mistake, not a plugin failure.
// These errors are kept as chat feedback instead of logging exceptions that make Dalamud send warn notification to the user.
if (string.IsNullOrWhiteSpace(json))
{
message = "Clipboard is empty. Copy a CreateXIV export first, then try importing again.";
return false;
}
List<AliasEntry>? imported;
try
{
imported = JsonSerializer.Deserialize<List<AliasEntry>>(json);
}
catch (JsonException)
{
message = "Clipboard does not contain a valid CreateXIV alias export.";
return false;
}
catch (NotSupportedException)
{
message = "Clipboard data is not a supported CreateXIV alias export.";
return false;
}
if (imported == null || imported.Count == 0)
{
message = "No aliases were found in the clipboard export.";
return false;
}
PushUndoSnapshot();
UnregisterAllAliasCommands();
Configuration.Aliases = imported;
Configuration.NextAliasNumber = 1;
foreach (var a in Configuration.Aliases)
a.Number = 0;
NormalizeSavedAliases();
RegisterAllAliasCommands();
Configuration.Save();
var commands = Configuration.Aliases.Count(x => x.Kind == AliasKind.Command);
var macros = Configuration.Aliases.Count(x => x.Kind == AliasKind.Macro);
message = $"Imported {Configuration.Aliases.Count} aliases from clipboard ({commands} commands, {macros} macros).";
return true;
}
// Handles the chat-side creation flow for /create without opening the UI.
// This keeps the command strict on purpose: it only accepts alias + target + optional existing category,
// returns user-facing validation messages and then reuses the same add/update path as the main window
// so chat-created aliases behave exactly like aliases created from the editor interface.
private bool TryCreateAliasFromChat(string rawArgs, out string message, out bool ok)
{
ok = false;
message = string.Empty;
var parts = (rawArgs ?? string.Empty)
.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2 || parts.Length > 3)
{
message = CreateAliasUsage;
return true;
}
var alias = parts[0];
var target = parts[1];
var category = string.Empty;
if (parts.Length == 3)
{
category = parts[2].Trim();
if (!CategoryExists(category))
{
message = $"Category '{category}' does not exist. Use an existing category or leave it empty.";
return true;
}
}
if (TryGetAliasInputProblem(alias, out var aliasProblem))
{
message = aliasProblem + " " + CreateAliasUsage;
return true;
}
var kind = TryParseSingleMacroReference(target, out _) ? AliasKind.Macro : AliasKind.Command;
var created = kind == AliasKind.Macro
? AddOrUpdateMacroAlias(alias, target, category, false, out message)
: AddOrUpdateCommandAlias(alias, target, category, false, out message);
ok = created;
if (created)
{
var catText = string.IsNullOrWhiteSpace(category) ? string.Empty : $" in '{category}'";
message = $"Created {GetKindLabel(kind)} alias {NormalizeAlias(alias)} -> {(kind == AliasKind.Command ? EnsureSlashCommand(target) : NormalizeCommand(target))}{catText}.";
}
else
{
message += " " + CreateAliasUsage;
}
return true;
}
private bool CategoryExists(string category)
{
var cat = (category ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(cat))
return true;
return Configuration.Aliases.Any(a => string.Equals((a.Category ?? string.Empty).Trim(), cat, StringComparison.OrdinalIgnoreCase)) ||
Configuration.CategoryColors.Keys.Any(k => string.Equals((k ?? string.Empty).Trim(), cat, StringComparison.OrdinalIgnoreCase));
}
// =========================
// Core add/update logic
// =========================
private bool AddOrUpdateAliasInternal(string aliasInput, string commandInput, string category, bool pinned, AliasKind kind, out string message)
{
var normalizedAlias = NormalizeAlias(aliasInput);
var normalizedCommand = kind == AliasKind.Command ? EnsureSlashCommand(commandInput) : NormalizeCommand(commandInput);
if (string.IsNullOrWhiteSpace(normalizedAlias))
{
message = "Alias cannot be empty.";
return false;
}
if (string.IsNullOrWhiteSpace(normalizedCommand))
{
message = "Command cannot be empty.";
return false;
}
if (string.Equals(normalizedAlias, CreateCommandName, StringComparison.OrdinalIgnoreCase))
{
message = "You cannot use /create as an alias.";
return false;
}
// Security: don't allow pointing to /create
if (string.Equals(NormalizeAlias(normalizedCommand), CreateCommandName, StringComparison.OrdinalIgnoreCase))
{
message = "You cannot point a command to /create.";
return false;
}
// Security: prevent self-call
if (string.Equals(NormalizeAlias(normalizedCommand), normalizedAlias, StringComparison.OrdinalIgnoreCase))
{
message = "Alias cannot point to itself.";
return false;
}
// Security: prevent alias-to-alias chaining/loops
// If the command starts with "/" and matches ANY of our aliases, block it.
if (normalizedCommand.StartsWith('/') &&
Configuration.Aliases.Any(a => string.Equals(NormalizeAlias(a.Alias), NormalizeAlias(normalizedCommand.Split(' ', '\t')[0]), StringComparison.OrdinalIgnoreCase)))
{
message = "For safety, CreateXIV aliases cannot call other CreateXIV aliases (prevents loops).";
return false;
}
// Macro: only one in-game macro is allowed
if (kind == AliasKind.Macro)
{
if (!TryParseSingleMacroReference(normalizedCommand, out var macroRef))
{
message = "Macro aliases must use exactly one macro reference: macro:## or shared:##. Example: shared:47";
return false;
}
if (!CommandSuggestionService.IsMacroAvailable(macroRef.Set, macroRef.Number))
{
message = "Macro does not exist or is empty.";
return false;
}
}
if (kind == AliasKind.Command && !IsKnownCommandAvailable(normalizedCommand))
{
message = "Command was not found in the active command list or the native game command list.";
return false;
}
var existing = Configuration.Aliases.FirstOrDefault(x =>
string.Equals(NormalizeAlias(x.Alias), normalizedAlias, StringComparison.OrdinalIgnoreCase));
if (existing == null && TryGetAliasInputProblem(normalizedAlias, out message))
return false;
if (existing != null)
{
PushUndoSnapshot();
UnregisterAliasCommand(existing.Alias);
existing.Alias = normalizedAlias;
existing.Command = normalizedCommand;
existing.Kind = kind;
existing.Category = (category ?? string.Empty).Trim();
existing.Pinned = pinned;
if (!ValidateEntry(existing, out message))
return false;
if (existing.Enabled && !RegisterAliasCommand(existing))
{
message = $"Could not register alias {normalizedAlias}.";
return false;
}
SortAliases();
Configuration.Save();
message = $"Updated {GetKindLabel(kind)} alias: {normalizedAlias} -> {normalizedCommand}";
return true;
}
var newEntry = new AliasEntry
{
Number = GetNextAliasNumber(),
Alias = normalizedAlias,
Command = normalizedCommand,
Kind = kind,
Category = (category ?? string.Empty).Trim(),
Pinned = pinned,
Enabled = true,
CooldownMs = 0
};
if (!ValidateEntry(newEntry, out message))
return false;
if (!RegisterAliasCommand(newEntry))
{
message = $"Could not register alias {normalizedAlias}.";
return false;
}
PushUndoSnapshot();
Configuration.Aliases.Add(newEntry);
SortAliases();
Configuration.Save();
message = $"Created {GetKindLabel(kind)} alias: {normalizedAlias} -> {normalizedCommand}";
return true;
}
private bool ValidateEntry(AliasEntry entry, out string message)
{
// Validation is intentionally stricter than the UI hints because imported aliases and chat-created aliases
// can bypass some of the normal input flow.
var alias = NormalizeAlias(entry.Alias);
var cmd = NormalizeCommand(entry.Command);
if (string.IsNullOrWhiteSpace(alias) || string.IsNullOrWhiteSpace(cmd))
{
message = "Alias/Command cannot be empty.";
return false;
}
if (string.Equals(alias, CreateCommandName, StringComparison.OrdinalIgnoreCase))
{
message = "You cannot use /create as an alias.";
return false;
}
if (entry.Kind == AliasKind.Macro)
{
if (!TryParseSingleMacroReference(cmd, out var macroRef))
{
message = "Invalid macro format. Use macro:## or shared:## only.";
return false;
}
if (!CommandSuggestionService.IsMacroAvailable(macroRef.Set, macroRef.Number))
{
message = "Macro does not exist or is empty.";
return false;
}
}
else
// This rejects command aliases that do not resolve to either a currently registered Dalamud/plugin command
// or a known native game command. It is intentionally checked at validation time so broken aliases are
// caught before saving/importing instead of failing later when the user tries to execute them.
{
if (!IsKnownCommandAvailable(cmd))
{
message = "Command was not found in the active command list or the native game command list.";
return false;
}
}
message = string.Empty;
return true;
}
private void PushUndoSnapshot()
{
undoStack.Push(Configuration.Aliases.Select(CloneEntry).ToList());
}
private static AliasEntry CloneEntry(AliasEntry src)
{
return new AliasEntry
{
Number = src.Number,
Alias = src.Alias,
Command = src.Command,
Kind = src.Kind,
Category = src.Category,
Pinned = src.Pinned,
Enabled = src.Enabled,
CooldownMs = src.CooldownMs,
};
}
// =========================
// Normalization / numbering
// =========================
public static string NormalizeAlias(string alias)
{
alias = (alias ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(alias))
return string.Empty;
if (!alias.StartsWith('/'))
alias = "/" + alias;
return alias.ToLowerInvariant();
}
public static string NormalizeCommand(string command)
=> (command ?? string.Empty).Trim();
public static string GetKindLabel(AliasKind kind)
=> kind == AliasKind.Macro ? "macro" : "command";
private int GetNextAliasNumber()
{
if (Configuration.NextAliasNumber < 1)
Configuration.NextAliasNumber = 1;
var number = Configuration.NextAliasNumber;
if (Configuration.NextAliasNumber < 999)
Configuration.NextAliasNumber++;
else
Configuration.NextAliasNumber = 999;
return number;
}
private void NormalizeSavedAliases()
{
foreach (var entry in Configuration.Aliases)
{
entry.Alias = NormalizeAlias(entry.Alias);
entry.Command = NormalizeCommand(entry.Command);
entry.Category = (entry.Category ?? string.Empty).Trim();
if (entry.Number <= 0)
entry.Number = 0;
if (entry.CooldownMs < 0)
entry.CooldownMs = 0;
else if (entry.CooldownMs > 5000)
entry.CooldownMs = 5000;
}
var orderedWithoutNumbers = Configuration.Aliases
.Where(x => x.Number <= 0)
.OrderBy(x => x.Alias, StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (var entry in orderedWithoutNumbers)
entry.Number = GetNextAliasNumber();
var highestNumber = Configuration.Aliases.Count == 0 ? 0 : Configuration.Aliases.Max(x => x.Number);
if (highestNumber >= Configuration.NextAliasNumber)
Configuration.NextAliasNumber = Math.Min(highestNumber + 1, 999);
Configuration.Aliases = Configuration.Aliases
.Where(x => !string.IsNullOrWhiteSpace(x.Alias) && !string.IsNullOrWhiteSpace(x.Command))
.OrderBy(x => x.Number)
.ToList();
Configuration.Save();
}
private void MigrateOldDefaultWaitOnce()
{
if (Configuration.WaitOneToZeroMigrationDone)
return;
var changed = false;
foreach (var entry in Configuration.Aliases)
{
if (entry.CooldownMs != 1000)
continue;
entry.CooldownMs = 0;
changed = true;
}
Configuration.WaitOneToZeroMigrationDone = true;
if (changed)
Configuration.Save();
else
Configuration.Save();
}
private void SortAliases()
{
// Pinned first, then number
Configuration.Aliases = Configuration.Aliases
.OrderByDescending(x => x.Pinned)
.ThenBy(x => x.Number)
.ToList();
}
// =========================
// Register / Unregister
// =========================
private void RegisterAllAliasCommands()
{
foreach (var entry in Configuration.Aliases
.OrderByDescending(x => x.Pinned)
.ThenBy(x => x.Number))
{
entry.Alias = NormalizeAlias(entry.Alias);
entry.Command = NormalizeCommand(entry.Command);
if (!entry.Enabled || !CanRegisterSavedAlias(entry))
continue;
RegisterAliasCommand(entry);