-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.cs
More file actions
2334 lines (1955 loc) · 85.8 KB
/
Copy pathPlugin.cs
File metadata and controls
2334 lines (1955 loc) · 85.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;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Dalamud.Game.ClientState.Conditions;
using Dalamud.Game.ClientState.Keys;
using Dalamud.Bindings.ImGui;
using Dalamud.Game.Command;
using Dalamud.Game.Gui.Toast;
using Dalamud.Game.Text.SeStringHandling;
using Dalamud.Game.Text.SeStringHandling.Payloads;
using Dalamud.Plugin;
using Dalamud.Plugin.Services;
using Dalamud.Utility;
using Dalamud.Interface.Windowing;
using Dalamud.Interface.ManagedFontAtlas;
using System.Text.RegularExpressions;
using FFXIVClientStructs.FFXIV.Client.UI;
using FFXIVClientStructs.FFXIV.Component.GUI;
using Clock.Services;
using Clock.Windows;
// bryer // The plugin class is a bit of a hub, so the ordering here favours "where I look first" over perfect layering.
namespace Clock;
// Main plugin entry point. It wires services together and owns the Dalamud-facing lifecycle.
public sealed class Plugin : IDalamudPlugin
{
// I keep one shared Lodestone state because Events/Maintenance hit different pages but they still share the same external site.
private enum LodestoneCheckKind
{
None,
Maintenance,
SeasonalEvents
}
private const string CommandName = "/clock";
private const string AlarmsCommand = "/clockalarms";
private const string DirectAlarmsCommand = "/alarms";
public const int MinAlarmSoundEffectId = 1;
public const int MaxAlarmSoundEffectId = 16;
private readonly IDalamudPluginInterface pluginInterface;
private readonly ICommandManager commandManager;
private readonly IPluginLog log;
private readonly IClientState clientState;
private readonly ICondition condition;
private readonly IChatGui chatGui;
private readonly IToastGui toastGui;
private readonly IKeyState keyState;
private readonly LodestoneMaintenanceService maintenanceService = new();
private readonly EventService eventService = new();
private readonly ChatTimestampService chatTimestampService;
private readonly ChatTimeHoverService chatTimeHoverService;
private readonly QuickSymbolsIpcService quickSymbolsIpcService;
private readonly IFontHandle? digitalClockFontHandle;
private readonly IFontHandle? alarmSessionDigitalFontHandle;
private readonly IFontHandle? technologyClockFontHandle;
private readonly IFontHandle? ka1ClockFontHandle;
private readonly IFontHandle? countdownClockFontHandle;
private readonly IFontHandle? alarmPanelFont;
private readonly IFontHandle? alarmTitleFont;
private readonly IFontHandle? largeAlarmIconFont;
private bool digitalFontQueued;
private bool digitalReadyLogged;
private bool digitalLoadLogged;
private bool alarmFontQueued;
private bool alarmReadyLogged;
private bool alarmLoadLogged;
private bool techFontQueued;
private bool techReadyLogged;
private bool techLoadLogged;
private bool ka1ClockFontBuildQueued;
private bool ka1ClockFontReadyLogged;
private bool ka1ClockFontLoadLogged;
private bool countdownFontQueued;
private bool countdownReadyLogged;
private bool countdownLoadLogged;
private bool alarmPanelAlarmFontBuildQueued;
private bool alarmPanelAlarmFontReadyLogged;
private bool alarmPanelAlarmFontLoadLogged;
private bool alarmPanelAlarmTitleFontBuildQueued;
private bool alarmPanelAlarmTitleFontReadyLogged;
private bool alarmPanelAlarmTitleFontLoadLogged;
private bool largeAlarmIconFontBuildQueued;
private bool largeAlarmIconFontReadyLogged;
private bool largeAlarmIconFontLoadLogged;
private bool hasAutoStarted;
private bool wantedMainWindowOpen;
private DateTime lastReminderCheckUtc = DateTime.MinValue;
private DateTime lastMaintenanceCheckUtc = DateTime.MinValue;
private Task<LodestoneMaintenanceInfo?>? maintenanceRefreshTask;
private bool maintenanceManual;
private bool maintenanceQueued;
private bool maintenanceQueuedManual;
private long maintenanceQueueOrder;
private bool eventQueued;
private bool eventQueuedManual;
private long eventQueueOrder;
private long lodestoneQueueOrder;
private LodestoneCheckKind lodestoneCheckKind = LodestoneCheckKind.None;
private DateTime alarmOverlayUntilUtc = DateTime.MinValue;
private DateTime alarmOverlayTriggerUtc = DateTime.MinValue;
private string alarmOverlayTimeZoneId = string.Empty;
private bool alarmOverlayPreviewActive;
private bool alarmsWindowHotkeyWasDown;
private Guid repeatingAlarmSoundId;
private int repeatingAlarmSoundEffectId;
private DateTime repeatingAlarmSoundNextUtc = DateTime.MinValue;
private Task<IReadOnlyList<EventInfo>>? eventTask;
private bool eventTaskManual;
private DateTime lastEventCheckUtc = DateTime.MinValue;
private bool wasLoggedIn;
private bool loginEventNoticePending;
private int loginEventSession;
private readonly HashSet<string> maintenanceKeys = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<Guid> recentAlarmIds = new();
public Configuration Configuration { get; private set; }
public readonly WindowSystem WindowSystem = new("Clock");
public IDalamudPluginInterface PluginInterface => pluginInterface;
public IPluginLog Log => log;
public IKeyState KeyState => keyState;
public QuickSymbolsIpcService QuickSymbolsIpc => quickSymbolsIpcService;
public ConfigWindow ConfigWindow { get; private init; }
private MainWindow MainWindow { get; init; }
private AlarmOverlayWindow AlarmOverlayWindow { get; init; }
private CommandHintWindow CommandHintWindow { get; init; }
private ChatTimeHoverPopupWindow ChatTimeHoverPopupWindow { get; init; }
public Plugin(
IDalamudPluginInterface pluginInterface,
ICommandManager commandManager,
IPluginLog log,
IClientState clientState,
ICondition condition,
IChatGui chatGui,
IToastGui toastGui,
IKeyState keyState,
IGameInteropProvider gameInteropProvider,
IGameGui gameGui)
{
this.pluginInterface = pluginInterface;
this.commandManager = commandManager;
this.log = log;
this.clientState = clientState;
this.condition = condition;
this.chatGui = chatGui;
this.toastGui = toastGui;
this.keyState = keyState;
Configuration = pluginInterface.GetPluginConfig() as Configuration ?? new Configuration();
Configuration.Initialize(pluginInterface);
Configuration.EnsureInitialized();
Configuration.Save();
// Theme fonts are registered once at startup and then reused by every clock draw path;
// keeping them centralized to avoid rebuilding font atlases while the UI is rendering.
digitalClockFontHandle = CreateClockFontHandle("DS-DIGI.ttf", "digital");
alarmSessionDigitalFontHandle = CreateClockFontHandle("DS-DIGI.ttf", "alarm session digital", pluginInterface.UiBuilder.FontDefaultSizePx * 1.95f);
technologyClockFontHandle = CreateClockFontHandle("E1234.ttf", "technology");
ka1ClockFontHandle = CreateClockFontHandle("ka1.ttf", "ka1");
countdownClockFontHandle = CreateClockFontHandle("DigitTech7-Regular.otf", "countdown");
alarmPanelFont = CreateWindowsFontHandle("segoeui.ttf", 42f, "alarmPanel alarm");
alarmTitleFont = CreateWindowsFontHandle("segoeui.ttf", 34f, "alarmPanel alarm title");
largeAlarmIconFont = CreateDalamudIconFontHandle(48f, "large alarm icon");
QueueClockFontBuild(digitalClockFontHandle, ref digitalFontQueued);
QueueClockFontBuild(alarmSessionDigitalFontHandle, ref alarmFontQueued);
QueueClockFontBuild(technologyClockFontHandle, ref techFontQueued);
QueueClockFontBuild(ka1ClockFontHandle, ref ka1ClockFontBuildQueued);
QueueClockFontBuild(countdownClockFontHandle, ref countdownFontQueued);
QueueClockFontBuild(alarmPanelFont, ref alarmPanelAlarmFontBuildQueued);
QueueClockFontBuild(alarmTitleFont, ref alarmPanelAlarmTitleFontBuildQueued);
QueueClockFontBuild(largeAlarmIconFont, ref largeAlarmIconFontBuildQueued);
ConfigWindow = new ConfigWindow(this);
MainWindow = new MainWindow(this);
AlarmOverlayWindow = new AlarmOverlayWindow(this);
CommandHintWindow = new CommandHintWindow(T);
ChatTimeHoverPopupWindow = new ChatTimeHoverPopupWindow(Configuration, pluginInterface, log, T, SetupAlarmFromChatTime);
WindowSystem.AddWindow(ConfigWindow);
WindowSystem.AddWindow(MainWindow);
WindowSystem.AddWindow(AlarmOverlayWindow);
WindowSystem.AddWindow(CommandHintWindow);
WindowSystem.AddWindow(ChatTimeHoverPopupWindow);
chatTimestampService = new ChatTimestampService(Configuration, gameInteropProvider, log);
chatTimeHoverService = new ChatTimeHoverService(Configuration, chatGui, log, T, ChatTimeHoverPopupWindow);
quickSymbolsIpcService = new QuickSymbolsIpcService(pluginInterface, log, keyState);
commandManager.AddHandler(CommandName, new CommandInfo(OnCommand)
{
HelpMessage =
"Clock commands: /clock, /clock on, /clock off, /clock help, /clock timezone <TimeZoneInfo ID>, /clock format 12|24|12s|24s|weekday|date, " +
"/clock colon default|always|hidden|slow|fast, /clock layout horizontal|vertical, " +
"/clock <timezone> to <timezone>, /clock lock, /clock unlock, " +
"/clock profile next|list|set <n>|add <name>|rename <name>|delete"
});
commandManager.AddHandler(AlarmsCommand, new CommandInfo(OnAlarmsCommand)
{
HelpMessage = T("Open alarm overlay")
});
commandManager.AddHandler(DirectAlarmsCommand, new CommandInfo(OnAlarmsCommand)
{
HelpMessage = T("Open alarm overlay")
});
pluginInterface.UiBuilder.DisableCutsceneUiHide = !Configuration.HideDuringCutscenes;
pluginInterface.UiBuilder.Draw += DrawUI;
pluginInterface.UiBuilder.OpenConfigUi += ToggleConfigUi;
pluginInterface.UiBuilder.OpenMainUi += ToggleMainUi;
}
private IFontHandle? CreateClockFontHandle(string fileName, string label, float? sizePx = null)
{
var baseDir = pluginInterface.AssemblyLocation.DirectoryName;
if (string.IsNullOrWhiteSpace(baseDir))
{
log.Warning("Clock {Label} font path could not be resolved: assembly directory is empty.", label);
return null;
}
var fontPath = FindClockFontPath(baseDir, fileName);
if (fontPath == null)
{
log.Warning("Clock {Label} font file was not found. Expected {FileName} inside a Fonts folder near the plugin output or source folder.", label, fileName);
return null;
}
return pluginInterface.UiBuilder.FontAtlas.NewDelegateFontHandle(e => e.OnPreBuild(tk =>
{
var config = new SafeFontConfig
{
SizePx = sizePx ?? pluginInterface.UiBuilder.FontDefaultSizePx,
OversampleH = 3,
OversampleV = 1
};
var font = tk.AddFontFromFile(fontPath, config);
tk.Font = font;
}));
}
private IFontHandle? CreateWindowsFontHandle(string fileName, float sizePx, string label)
{
var fontsDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
if (string.IsNullOrWhiteSpace(fontsDir))
return null;
var fontPath = Path.Combine(fontsDir, fileName);
if (!File.Exists(fontPath))
return null;
return pluginInterface.UiBuilder.FontAtlas.NewDelegateFontHandle(e => e.OnPreBuild(tk =>
{
var config = new SafeFontConfig
{
SizePx = sizePx,
OversampleH = 3,
OversampleV = 2
};
var font = tk.AddFontFromFile(fontPath, config);
tk.Font = font;
}));
}
private IFontHandle? CreateDalamudIconFontHandle(float sizePx, string label)
{
try
{
return pluginInterface.UiBuilder.FontAtlas.NewDelegateFontHandle(e => e.OnPreBuild(tk =>
tk.AddFontAwesomeIconFont(new() { SizePx = sizePx })));
}
catch (Exception ex)
{
log.Warning(ex, "Clock {Label} icon font could not be created.", label);
return null;
}
}
private static string? FindClockFontPath(string baseDir, string fileName)
{
var dir = new DirectoryInfo(baseDir);
for (var i = 0; i < 7 && dir != null; i++, dir = dir.Parent)
{
var inFonts = Path.Combine(dir.FullName, "Fonts", fileName);
if (File.Exists(inFonts))
return inFonts;
var beside = Path.Combine(dir.FullName, fileName);
if (File.Exists(beside))
return beside;
}
return null;
}
private void QueueClockFontBuild(IFontHandle? handle, ref bool queued)
{
if (handle == null || queued || handle.Available)
return;
queued = true;
try
{
pluginInterface.UiBuilder.FontAtlas.BuildFontsOnNextFrame();
}
catch (InvalidOperationException)
{
try
{
_ = pluginInterface.UiBuilder.FontAtlas.BuildFontsAsync();
}
catch (Exception ex)
{
queued = false;
log.Warning(ex, "Could not start async Clock font rebuild.");
}
}
catch (Exception ex)
{
queued = false;
log.Warning(ex, "Could not queue Clock font rebuild.");
}
}
private void CheckClockFontState(IFontHandle? handle, ref bool queued, ref bool readyLogged, ref bool loadLogged, string label)
{
if (handle == null)
return;
if (!handle.Available && handle.LoadException == null)
QueueClockFontBuild(handle, ref queued);
if (!readyLogged && handle.Available)
{
readyLogged = true;
log.Information("Clock {Label} font is ready.", label);
}
if (!loadLogged && handle.LoadException != null)
{
loadLogged = true;
log.Warning(handle.LoadException, "Clock {Label} font failed to load.", label);
}
}
private void CheckDigitalClockFontState()
{
CheckClockFontState(digitalClockFontHandle, ref digitalFontQueued, ref digitalReadyLogged, ref digitalLoadLogged, "digital");
}
private void CheckAlarmSessionDigitalFontState()
{
CheckClockFontState(alarmSessionDigitalFontHandle, ref alarmFontQueued, ref alarmReadyLogged, ref alarmLoadLogged, "alarm session digital");
}
public ILockedImFont? LockAlarmSessionDigitalFont()
{
if (alarmSessionDigitalFontHandle == null)
return null;
CheckAlarmSessionDigitalFontState();
return alarmSessionDigitalFontHandle.Available ? alarmSessionDigitalFontHandle.Lock() : null;
}
private void CheckTechnologyClockFontState()
{
CheckClockFontState(technologyClockFontHandle, ref techFontQueued, ref techReadyLogged, ref techLoadLogged, "technology");
}
private void CheckKa1ClockFontState()
{
CheckClockFontState(ka1ClockFontHandle, ref ka1ClockFontBuildQueued, ref ka1ClockFontReadyLogged, ref ka1ClockFontLoadLogged, "ka1");
}
private void CheckCountdownClockFontState()
{
CheckClockFontState(countdownClockFontHandle, ref countdownFontQueued, ref countdownReadyLogged, ref countdownLoadLogged, "countdown");
CheckClockFontState(alarmPanelFont, ref alarmPanelAlarmFontBuildQueued, ref alarmPanelAlarmFontReadyLogged, ref alarmPanelAlarmFontLoadLogged, "alarmPanel alarm");
}
public IDisposable PushClockTimeFont(ClockTimeTextFont font)
{
if (font == ClockTimeTextFont.Digital)
{
if (digitalClockFontHandle == null)
return EmptyFontScope.Instance;
CheckDigitalClockFontState();
return digitalClockFontHandle.Available ? digitalClockFontHandle.Push() : EmptyFontScope.Instance;
}
if (font == ClockTimeTextFont.Technology)
{
if (technologyClockFontHandle == null)
return EmptyFontScope.Instance;
CheckTechnologyClockFontState();
return technologyClockFontHandle.Available ? technologyClockFontHandle.Push() : EmptyFontScope.Instance;
}
if (font == ClockTimeTextFont.Ka1)
{
if (ka1ClockFontHandle == null)
return EmptyFontScope.Instance;
CheckKa1ClockFontState();
return ka1ClockFontHandle.Available ? ka1ClockFontHandle.Push() : EmptyFontScope.Instance;
}
if (font == ClockTimeTextFont.Countdown)
{
if (countdownClockFontHandle == null)
return EmptyFontScope.Instance;
CheckCountdownClockFontState();
return countdownClockFontHandle.Available ? countdownClockFontHandle.Push() : EmptyFontScope.Instance;
}
return EmptyFontScope.Instance;
}
public bool IsDigitalClockFontReady()
{
CheckDigitalClockFontState();
return digitalClockFontHandle?.Available == true;
}
public bool IsTechnologyClockFontReady()
{
CheckTechnologyClockFontState();
return technologyClockFontHandle?.Available == true;
}
public bool IsKa1ClockFontReady()
{
CheckKa1ClockFontState();
return ka1ClockFontHandle?.Available == true;
}
public bool IsCountdownClockFontReady()
{
CheckCountdownClockFontState();
return countdownClockFontHandle?.Available == true;
}
private void CheckAlarmPanelAlarmFontState()
{
CheckClockFontState(alarmPanelFont, ref alarmPanelAlarmFontBuildQueued, ref alarmPanelAlarmFontReadyLogged, ref alarmPanelAlarmFontLoadLogged, "alarmPanel alarm");
}
public IDisposable PushAlarmPanelAlarmFont()
{
if (alarmPanelFont == null)
return EmptyFontScope.Instance;
CheckAlarmPanelAlarmFontState();
return alarmPanelFont.Available ? alarmPanelFont.Push() : EmptyFontScope.Instance;
}
private void CheckAlarmPanelAlarmTitleFontState()
{
CheckClockFontState(alarmTitleFont, ref alarmPanelAlarmTitleFontBuildQueued, ref alarmPanelAlarmTitleFontReadyLogged, ref alarmPanelAlarmTitleFontLoadLogged, "alarmPanel alarm title");
}
public IDisposable PushAlarmPanelAlarmTitleFont()
{
if (alarmTitleFont == null)
return PushAlarmPanelAlarmFont();
CheckAlarmPanelAlarmTitleFontState();
return alarmTitleFont.Available ? alarmTitleFont.Push() : PushAlarmPanelAlarmFont();
}
private void CheckLargeAlarmIconFontState()
{
CheckClockFontState(largeAlarmIconFont, ref largeAlarmIconFontBuildQueued, ref largeAlarmIconFontReadyLogged, ref largeAlarmIconFontLoadLogged, "large alarm icon");
}
public IDisposable PushLargeAlarmIconFont()
{
if (largeAlarmIconFont == null)
return pluginInterface.UiBuilder.IconFontHandle.Push();
CheckLargeAlarmIconFontState();
return largeAlarmIconFont.Available ? largeAlarmIconFont.Push() : pluginInterface.UiBuilder.IconFontHandle.Push();
}
public ILockedImFont? LockLargeAlarmIconFont()
{
if (largeAlarmIconFont == null)
return null;
CheckLargeAlarmIconFontState();
return largeAlarmIconFont.Available ? largeAlarmIconFont.Lock() : null;
}
private sealed class EmptyFontScope : IDisposable
{
public static readonly EmptyFontScope Instance = new();
public void Dispose() { }
}
// Chat tooltip alarms are intentionally committed immediately instead of opening the UI first (old behavior)
// because the clicked chat timestamp already contains the final target time.
private void SetupAlarmFromChatTime(ChatTimeHoverService.ChatAlarmSetupRequest request)
{
if (!ConfigWindow.CreateAlarmFromChatConversion(request.TargetLocal, request.TargetTimeZoneId))
return;
AlarmOverlayWindow.ShowHistory();
OpenAlarmOverlay();
}
public void RefreshChatTimestampSettings()
{
chatTimestampService.ApplyConfiguration();
}
public void PrintChatTimeHoverTestMessage()
{
// These local-only chat lines aim to give users a quick way to verify the whole hover pipeline without needing a real message in chat:
// single time parsing, range parsing, date context, tooltip display and alarm creation.
var (singleTime, rangeTime, venueDate) = BuildChatTimeHoverTestBits();
chatGui.Print(string.Format(CultureInfo.InvariantCulture, T("This is a test message showing how Time like {0} is detected. Please hover your mouse above the time and click it."), singleTime), "Clock");
chatGui.Print(string.Format(CultureInfo.InvariantCulture, T("This is a second test message showing how Time like {0} is detected. Please hover your mouse above the time and click it."), rangeTime), "Clock");
chatGui.Print(string.Format(CultureInfo.InvariantCulture, T("Clock Venue is opening on Exo-Gob-W0-P00 {0} at {1}! And we have gone crazy with 50mil Giveaways and prizes!!"), venueDate, singleTime), "Clock");
}
private (string SingleTime, string RangeTime, string VenueDate) BuildChatTimeHoverTestBits()
{
// Test chat uses a different source timezone on purpose, otherwise the hover path can look like a no-op for the user.
var zoneId = PickChatTimeHoverTestSourceZone();
var startUtc = DateTime.UtcNow.AddHours(1);
var start = TimeZoneHelper.ConvertFromUtc(startUtc, zoneId);
if (start.Minute != 0 || start.Second != 0 || start.Millisecond != 0)
{
start = new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0).AddHours(1);
startUtc = TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(start, DateTimeKind.Unspecified), TimeZoneHelper.GetTimeZone(zoneId));
}
var end = TimeZoneHelper.ConvertFromUtc(startUtc.AddHours(5), zoneId);
var shortZone = TimeZoneHelper.ToShortText(zoneId);
var single = $"{start:hhtt} {shortZone}".ToUpperInvariant();
var range = $"{start:hhtt}-{end:hhtt} {shortZone}".ToUpperInvariant();
var venueDate = FormatEnglishMonthDay(DateTime.Now.Date.AddDays(1));
return (single, range, venueDate);
}
private string PickChatTimeHoverTestSourceZone()
{
var primaryId = Configuration.SelectedTimeZoneId;
if (!TimeZoneHelper.TryResolveTimeZone(primaryId, out primaryId))
primaryId = TimeZoneInfo.Local.Id;
var nowUtc = DateTime.UtcNow;
var localOffset = TimeZoneInfo.Local.GetUtcOffset(nowUtc);
// Used only by the Test button for generated examples readable by the parser. doesn't affect real chat detection.
// Keep this list boring and OS-resolvable; the helper below tries both Windows and IANA ids so the same build works outside Windows dev boxes too.
var known = new[]
{
(Windows: "GMT Standard Time", Iana: "Europe/London"),
(Windows: "W. Europe Standard Time", Iana: "Europe/Berlin"),
(Windows: "Romance Standard Time", Iana: "Europe/Paris"),
(Windows: "Tokyo Standard Time", Iana: "Asia/Tokyo"),
(Windows: "Singapore Standard Time", Iana: "Asia/Singapore"),
(Windows: "AUS Eastern Standard Time", Iana: "Australia/Sydney"),
(Windows: "UTC", Iana: "Etc/UTC"),
};
string? picked = null;
TimeSpan? pickedOffset = null;
foreach (var item in known)
{
var zoneId = ResolveForThisMachine(item.Windows, item.Iana);
if (string.IsNullOrWhiteSpace(zoneId) || string.Equals(zoneId, primaryId, StringComparison.OrdinalIgnoreCase))
continue;
var offset = TimeZoneHelper.GetTimeZone(zoneId).GetUtcOffset(nowUtc);
if (offset < localOffset.Add(TimeSpan.FromHours(1)))
continue;
if (picked == null || pickedOffset == null || offset < pickedOffset.Value)
{
picked = zoneId;
pickedOffset = offset;
}
}
if (!string.IsNullOrWhiteSpace(picked))
return picked;
var fallback = ResolveForThisMachine("Tokyo Standard Time", "Asia/Tokyo");
if (!string.IsNullOrWhiteSpace(fallback) && !string.Equals(fallback, primaryId, StringComparison.OrdinalIgnoreCase))
return fallback;
return TimeZoneInfo.Local.Id;
}
private static string? ResolveForThisMachine(string windowsId, string ianaId)
{
if (TimeZoneHelper.TryResolveTimeZone(windowsId, out var resolved))
return resolved;
return TimeZoneHelper.TryResolveTimeZone(ianaId, out resolved)
? resolved
: null;
}
private static string FormatEnglishMonthDay(DateTime date)
{
var day = date.Day;
var suffix = "th";
var teen = day % 100;
if (teen != 11 && teen != 12 && teen != 13)
{
var lastDigit = day % 10;
if (lastDigit == 1)
suffix = "st";
else if (lastDigit == 2)
suffix = "nd";
else if (lastDigit == 3)
suffix = "rd";
}
// The test string intentionally uses English month text because the parser supports it and it mirrors common venue ads.
return $"{date.ToString("MMMM", CultureInfo.InvariantCulture)} {day}{suffix}";
}
public void Dispose()
{
Configuration.Save();
chatTimestampService.Dispose();
chatTimeHoverService.Dispose();
quickSymbolsIpcService.Dispose();
maintenanceService.Dispose();
eventService.Dispose();
pluginInterface.UiBuilder.Draw -= DrawUI;
pluginInterface.UiBuilder.OpenConfigUi -= ToggleConfigUi;
pluginInterface.UiBuilder.OpenMainUi -= ToggleMainUi;
WindowSystem.RemoveAllWindows();
ConfigWindow.Dispose();
MainWindow.Dispose();
AlarmOverlayWindow.Dispose();
CommandHintWindow.Dispose();
ChatTimeHoverPopupWindow.Dispose();
digitalClockFontHandle?.Dispose();
technologyClockFontHandle?.Dispose();
ka1ClockFontHandle?.Dispose();
countdownClockFontHandle?.Dispose();
alarmPanelFont?.Dispose();
alarmTitleFont?.Dispose();
commandManager.RemoveHandler(CommandName);
commandManager.RemoveHandler(AlarmsCommand);
commandManager.RemoveHandler(DirectAlarmsCommand);
}
// A bit verbose, but UI rendering is nicer to adjust when each step is visible.
private void DrawUI()
{
pluginInterface.UiBuilder.DisableCutsceneUiHide = !Configuration.HideDuringCutscenes;
var activeFont = Configuration.GetActiveProfile().TimeTextFont;
if (activeFont == ClockTimeTextFont.Digital)
CheckDigitalClockFontState();
else if (activeFont == ClockTimeTextFont.Technology)
CheckTechnologyClockFontState();
else if (activeFont == ClockTimeTextFont.Ka1)
CheckKa1ClockFontState();
else if (activeFont == ClockTimeTextFont.Countdown)
CheckCountdownClockFontState();
if (!hasAutoStarted && Configuration.AutoStart && clientState.IsLoggedIn)
{
hasAutoStarted = true;
wantedMainWindowOpen = true;
}
CheckReminders();
MonitorCommandHints();
CheckAlarmsWindowKeybind();
CheckRepeatingAlarmSound();
MainWindow.IsOpen = wantedMainWindowOpen && !ShouldHideClock();
WindowSystem.Draw();
}
private void CheckAlarmsWindowKeybind()
{
var keys = Configuration.AlarmsWindowHotkey ?? [];
if (keys.Length == 0 || ConfigWindow.IsCapturingAlarmsWindowKeybind)
{
alarmsWindowHotkeyWasDown = false;
return;
}
var validKeys = keyState.GetValidVirtualKeys().ToHashSet();
foreach (var key in keys)
{
if (!validKeys.Contains(key) || !keyState[key])
{
alarmsWindowHotkeyWasDown = false;
return;
}
}
if (alarmsWindowHotkeyWasDown)
return;
alarmsWindowHotkeyWasDown = true;
foreach (var key in keys)
keyState[key] = false;
ToggleAlarmOverlay();
}
public string FormatAlarmsWindowKeybind()
{
var keys = Configuration.AlarmsWindowHotkey ?? [];
return keys.Length == 0 ? "None" : string.Join("+", keys.Select(FormatVirtualKey));
}
public static string FormatVirtualKey(VirtualKey key)
{
return key switch
{
VirtualKey.KEY_0 => "0",
VirtualKey.KEY_1 => "1",
VirtualKey.KEY_2 => "2",
VirtualKey.KEY_3 => "3",
VirtualKey.KEY_4 => "4",
VirtualKey.KEY_5 => "5",
VirtualKey.KEY_6 => "6",
VirtualKey.KEY_7 => "7",
VirtualKey.KEY_8 => "8",
VirtualKey.KEY_9 => "9",
VirtualKey.CONTROL => "Ctrl",
VirtualKey.MENU => "Alt",
VirtualKey.SHIFT => "Shift",
_ => key.ToString().Replace("KEY_", string.Empty, StringComparison.Ordinal)
};
}
private unsafe void MonitorCommandHints()
{
CommandHintWindow.IsOpen = false;
if (!Configuration.CommandSuggestionEnabled)
return;
var module = RaptureAtkModule.Instance();
if (module == null || !module->IsTextInputActive())
return;
var typed = module->TextInput.RawInputString.ToString();
if (string.IsNullOrWhiteSpace(typed) || !typed.TrimStart().StartsWith("/clock", StringComparison.OrdinalIgnoreCase))
return;
// The input text comes from RaptureAtkModule's active text input state instead of an addon lookup.
// That keeps the hint list independent from chat addon names while still only opening when the user is actually typing a /clock command.
CommandHintWindow.Update(typed.TrimStart(), Vector2.Zero);
CommandHintWindow.IsOpen = true;
}
// This only reads the currently focused chat text input so command suggestions can follow what the user is typing.
// It should avoid addon-name lookups and doesn't write into the game UI; callers will still null-check the pointer before using it.
private unsafe AtkComponentTextInput* GetActiveChatTextInput()
{
var module = RaptureAtkModule.Instance();
if (module == null)
return null;
ref var textInput = ref module->TextInput;
if (textInput.TargetTextInputEventInterface == null || !module->IsTextInputActive())
return null;
var stage = AtkStage.Instance();
if (stage == null || stage->AtkInputManager == null)
return null;
var focusNode = stage->AtkInputManager->FocusedNode;
if (focusNode == null || focusNode->GetNodeType() != NodeType.Text)
return null;
var node = focusNode->ParentNode;
for (var i = 0; i < 6 && node != null; i++)
{
var input = node->GetAsAtkComponentTextInput();
if (input != null)
return input;
node = node->ParentNode;
}
return null;
}
private bool ShouldHideClock()
{
if (!Configuration.HideDuringCutscenes)
return false;
if (pluginInterface.UiBuilder.CutsceneActive)
return true;
return condition[ConditionFlag.WatchingCutscene]
|| condition[ConditionFlag.WatchingCutscene78]
|| condition[ConditionFlag.OccupiedInCutSceneEvent];
}
private void CheckReminders()
{
var nowUtc = DateTime.UtcNow;
if ((nowUtc - lastReminderCheckUtc).TotalSeconds < 1.0)
return;
lastReminderCheckUtc = nowUtc;
var loggedIn = clientState.IsLoggedIn;
var loginDetected = loggedIn && !wasLoggedIn;
if (loginDetected)
{
loginEventSession++;
loginEventNoticePending = true;
}
wasLoggedIn = loggedIn;
CheckAllAlarms(nowUtc);
UpdateMaintenanceDetection(nowUtc);
CheckMaintenanceReminder(nowUtc);
CheckEvents(nowUtc, loginDetected);
}
private void CheckAllAlarms(DateTime nowUtc)
{
if (Configuration.Alarms == null || Configuration.Alarms.Count == 0)
return;
bool changed = false;
foreach (var alarm in Configuration.Alarms)
{
if (!alarm.Enabled)
continue;
var hasPendingSnooze = alarm.SnoozedUntilUtc > DateTime.MinValue && !alarm.SnoozeTriggered;
if (alarm.HasTriggered && !hasPendingSnooze)
continue;
if (!AlarmConfigurationService.TryGetPendingTriggerUtc(alarm, out var alarmUtc))
continue;
if (nowUtc < alarmUtc)
{
recentAlarmIds.Remove(alarm.Id);
continue;
}
if ((nowUtc - alarmUtc).TotalSeconds > 60)
{
if (alarm.RepeatMode != AlarmRepeatMode.None && AlarmConfigurationService.MoveRecurringForward(alarm, nowUtc))
changed = true;
continue;
}
if (recentAlarmIds.Contains(alarm.Id))
continue;
recentAlarmIds.Add(alarm.Id);
changed = true;
var isSnoozeTrigger = hasPendingSnooze;
var triggerMessage = alarm.BuildTriggerMessage(Configuration.TimeFormat, isSnoozeTrigger);
StartAlarmOverlayVisual(alarm, isSnoozeTrigger ? alarm.SnoozedUntilUtc : alarmUtc, nowUtc);
ShowAlarmWindowTriggerSession(alarm, alarmUtc);
SendAlarmOutput(triggerMessage);
if (isSnoozeTrigger)
{
alarm.SnoozedUntilUtc = DateTime.MinValue;
alarm.SnoozeTriggered = true;
alarm.HasTriggered = true;
if (alarm.RepeatMode != AlarmRepeatMode.None)
AlarmConfigurationService.MoveRecurringForward(alarm, alarmUtc);
continue;
}
alarm.HasTriggered = true;
alarm.SnoozeTriggered = false;
alarm.SnoozeCanceled = false;
if (!AlarmConfigurationService.ScheduleSnooze(alarm, nowUtc))
{
alarm.SnoozedUntilUtc = DateTime.MinValue;
if (alarm.RepeatMode != AlarmRepeatMode.None)
AlarmConfigurationService.MoveRecurringForward(alarm, alarmUtc);
}
}
if (changed)
Configuration.Save();
}
private void StartAlarmOverlayVisual(AlarmEntry alarm, DateTime utc, DateTime nowUtc)
{
if (!Configuration.AlarmAnimationsEnabled)
return;
alarmOverlayPreviewActive = false;
alarmOverlayTriggerUtc = utc;
alarmOverlayTimeZoneId = alarm.GetEffectiveTimeZoneId();
alarmOverlayUntilUtc = nowUtc.AddSeconds(5.0);
}
private void ShowAlarmWindowTriggerSession(AlarmEntry alarm, DateTime utc)
{
if (!Configuration.OpenAlarmsOverlayOnAlarmTrigger)
return;
var alarmLocal = TimeZoneHelper.ConvertFromUtcForDisplay(utc, alarm.GetEffectiveTimeZoneId());
var alarmTimeText = FormatAlarmSessionTime(alarmLocal, alarm.GetEffectiveTimeZoneId());
AlarmOverlayWindow.ShowTriggeredAlarm(alarm.Id, alarm.Message, Configuration.AlarmSoundId, alarmTimeText, !alarm.SnoozeEnabled);
AlarmOverlayWindow.IsOpen = true;
if (Configuration.AlarmSoundRepeats)
StartRepeatingAlarmSound(alarm.Id, Configuration.AlarmSoundId);
}
private string FormatAlarmSessionTime(DateTime local, string timeZoneId)
{
var hour = local.Hour % 12;
if (hour == 0)
hour = 12;
var suffix = local.Hour >= 12 ? "P.M" : "A.M";
var zone = TimeZoneHelper.ToShortText(timeZoneId);
return $"{hour:00}:{local.Minute:00} {suffix} {zone}";
}
public void SnoozeAlarmFromOverlay(Guid alarmId, int minutes)
{
var alarm = Configuration.Alarms.FirstOrDefault(a => a.Id == alarmId);
if (alarm == null)
return;
alarm.SnoozeEnabled = true;
alarm.SnoozeMinutes = Math.Clamp(minutes, 1, 120);
alarm.SnoozedUntilUtc = TimeZoneHelper.IsEorzeaTime(alarm.GetEffectiveTimeZoneId())
? TimeZoneHelper.AddEorzeaMinutes(DateTime.UtcNow, alarm.SnoozeMinutes)
: DateTime.UtcNow.AddMinutes(alarm.SnoozeMinutes);
alarm.SnoozeTriggered = false;
alarm.SnoozeCanceled = false;
alarm.HasTriggered = true;
alarm.Enabled = true;
recentAlarmIds.Remove(alarm.Id);
StopRepeatingAlarmSound(alarmId);
Configuration.Save();
ShowAlarmToast(T("Alarm snoozed for the next 10 minutes"));
}
public void DismissAlarmOverlaySession(Guid alarmId)
{
StopRepeatingAlarmSound(alarmId);
}
public void StopAlarmOverlaySessionSound()
{
StopRepeatingAlarmSound(Guid.Empty, true);
}