-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitDetailComponent.cs
More file actions
2799 lines (2429 loc) · 118 KB
/
Copy pathSplitDetailComponent.cs
File metadata and controls
2799 lines (2429 loc) · 118 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
// ============================================================================
// SplitDetailComponent.cs
// LiveSplit component: SplitDetail
//
// ── Subsplits Convention ─────────────────────────────────────────────────────
// Segments whose names begin with "-" are children (subsplits).
// The first segment in a group whose name does NOT begin with "-"
// is the parent / group header.
//
// Example:
// index 0: "-Room 1" ← child subsplit
// index 1: "-Room 2" ← child subsplit
// index 2: "Castle" ← PARENT (group spans [0,2])
// index 3: "Forest" ← standalone (group spans [3,3])
// index 4: "-Area A" ← child subsplit
// index 5: "Mountain" ← PARENT (group spans [4,5])
//
// If subsplits are not used every segment is its own group (start==end).
// Change SubsplitPrefix below if your splits use a different convention.
//
// ── Rendering approach ────────────────────────────────────────────────────────
// All text goes through DrawTextWithEffects / DrawTextWithEffectsClipped.
// These use GraphicsPath rendering to respect LiveSplit shadow/outline
// settings without clipping descenders (p, g, y, |, etc.).
// Do NOT replace these calls with plain g.DrawString.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using LiveSplit.Model;
using LiveSplit.TimeFormatters;
using LiveSplit.UI;
using LiveSplit.UI.Components;
namespace LiveSplit.UI.Components
{
public enum SplitDetailMode
{
CurrentSplit,
CurrentSegment,
PriorSplit,
PriorSubsplit
}
internal struct SegmentRange
{
public readonly int Start;
public readonly int End;
public bool IsValid => Start >= 0 && End >= 0 && Start <= End;
public SegmentRange(int start, int end) { Start = start; End = end; }
public static readonly SegmentRange Invalid = new SegmentRange(-1, -1);
}
internal static class SplitDetailLayoutLinks
{
private const int MaxGroup = 4;
private const int ReportLifetimeMs = 1000;
private static readonly object Sync = new object();
private static readonly List<WeakReference> Settings = new List<WeakReference>();
private static readonly Dictionary<int, float> GroupSpacing = new Dictionary<int, float>();
private static readonly Dictionary<int, float> GroupValueTimeGap = new Dictionary<int, float>();
private static readonly Dictionary<int, float> GroupLabelRightOffset = new Dictionary<int, float>();
private static readonly Dictionary<int, float> GroupLabelValueGap = new Dictionary<int, float>();
private static readonly Dictionary<int, Dictionary<int, MiddleEndReport>> GroupReports =
new Dictionary<int, Dictionary<int, MiddleEndReport>>();
private static readonly Dictionary<int, Dictionary<int, MiddleEndReport>> GroupLabelLeftReports =
new Dictionary<int, Dictionary<int, MiddleEndReport>>();
private struct MiddleEndReport
{
public readonly float Value;
public readonly int Tick;
public MiddleEndReport(float value, int tick)
{
Value = value;
Tick = tick;
}
}
public static void Register(SplitDetailSettings settings)
{
if (settings == null)
return;
lock (Sync)
{
CleanupSettingsLocked();
for (int i = 0; i < Settings.Count; i++)
{
if (ReferenceEquals(Settings[i].Target, settings))
return;
}
Settings.Add(new WeakReference(settings));
}
}
public static float ResolveColumnSpacing(int group, float localSpacing)
{
group = ClampGroup(group);
if (group == 0)
return Math.Max(0f, localSpacing);
lock (Sync)
{
float spacing;
if (GroupSpacing.TryGetValue(group, out spacing))
return Math.Max(0f, spacing);
}
return Math.Max(0f, localSpacing);
}
public static void PublishSpacing(SplitDetailSettings source, int group, float spacing)
{
PublishLinkedSetting(GroupSpacing, source, group, spacing,
(settings, value) => settings.ApplyLinkedColumnSpacing(value));
}
public static void PublishMiddleValueTimeGap(SplitDetailSettings source, int group, float gap)
{
PublishLinkedSetting(GroupValueTimeGap, source, group, gap,
(settings, value) => settings.ApplyLinkedMiddleValueTimeGap(value));
}
public static void PublishMiddleLabelRightOffset(SplitDetailSettings source, int group, float offset)
{
PublishLinkedSetting(GroupLabelRightOffset, source, group, offset,
(settings, value) => settings.ApplyLinkedMiddleLabelRightOffset(value));
}
public static void PublishMiddleLabelValueGap(SplitDetailSettings source, int group, float gap)
{
PublishLinkedSetting(GroupLabelValueGap, source, group, gap,
(settings, value) => settings.ApplyLinkedMiddleLabelValueGap(value));
}
public static void PublishBoldFonts(SplitDetailSettings source, int group,
bool left, bool middleLabel,
bool middleValue, bool right,
bool enableLinkedRecipients)
{
group = ClampGroup(group);
if (source == null || group == 0)
return;
List<SplitDetailSettings> linkedSettings = new List<SplitDetailSettings>();
lock (Sync)
{
CleanupSettingsLocked();
for (int i = 0; i < Settings.Count; i++)
{
SplitDetailSettings settings = Settings[i].Target as SplitDetailSettings;
if (settings == null ||
ReferenceEquals(settings, source) ||
settings.MiddleColumnLinkGroup != group ||
(!enableLinkedRecipients && !settings.LinkBoldFonts))
{
continue;
}
linkedSettings.Add(settings);
}
}
for (int i = 0; i < linkedSettings.Count; i++)
linkedSettings[i].ApplyLinkedBoldFonts(
left, middleLabel, middleValue, right, enableLinkedRecipients);
}
private static void PublishLinkedSetting(
Dictionary<int, float> values,
SplitDetailSettings source,
int group,
float value,
Action<SplitDetailSettings, float> apply)
{
group = ClampGroup(group);
if (source == null || group == 0 || apply == null)
return;
value = Math.Max(0f, value);
List<SplitDetailSettings> linkedSettings = new List<SplitDetailSettings>();
lock (Sync)
{
values[group] = value;
CleanupSettingsLocked();
for (int i = 0; i < Settings.Count; i++)
{
SplitDetailSettings settings = Settings[i].Target as SplitDetailSettings;
if (settings == null ||
ReferenceEquals(settings, source) ||
settings.MiddleColumnLinkGroup != group)
{
continue;
}
linkedSettings.Add(settings);
}
}
for (int i = 0; i < linkedSettings.Count; i++)
apply(linkedSettings[i], value);
}
public static float ResolveMiddleEnd(int group, int instanceId, float localMidEnd)
{
return ResolveLinkedMinimum(GroupReports, group, instanceId, localMidEnd);
}
public static float ResolveLabelLeft(int group, int instanceId, float localLabelLeft)
{
return ResolveLinkedMinimum(GroupLabelLeftReports, group, instanceId, localLabelLeft);
}
private static float ResolveLinkedMinimum(
Dictionary<int, Dictionary<int, MiddleEndReport>> reportGroups,
int group,
int instanceId,
float localValue)
{
group = ClampGroup(group);
if (group == 0 || instanceId <= 0)
return localValue;
lock (Sync)
{
Dictionary<int, MiddleEndReport> reports;
if (!reportGroups.TryGetValue(group, out reports))
{
reports = new Dictionary<int, MiddleEndReport>();
reportGroups[group] = reports;
}
int now = Environment.TickCount;
reports[instanceId] = new MiddleEndReport(localValue, now);
float linkedValue = localValue;
List<int> stale = null;
foreach (KeyValuePair<int, MiddleEndReport> report in reports)
{
if (TickAge(now, report.Value.Tick) > ReportLifetimeMs)
{
if (stale == null)
stale = new List<int>();
stale.Add(report.Key);
continue;
}
linkedValue = Math.Min(linkedValue, report.Value.Value);
}
if (stale != null)
{
for (int i = 0; i < stale.Count; i++)
reports.Remove(stale[i]);
}
return linkedValue;
}
}
private static int ClampGroup(int group)
{
if (group < 0) return 0;
if (group > MaxGroup) return MaxGroup;
return group;
}
private static int TickAge(int now, int then)
{
unchecked
{
return now - then;
}
}
private static void CleanupSettingsLocked()
{
for (int i = Settings.Count - 1; i >= 0; i--)
{
if (!Settings[i].IsAlive)
Settings.RemoveAt(i);
}
}
}
public class SplitDetailComponent : IComponent
{
// ── Subsplit prefix ───────────────────────────────────────────────────
// ⚠ Change if your splits use a different prefix (e.g. "{-}").
private const string SubsplitPrefix = "-";
// ── Layout constants ──────────────────────────────────────────────────
private const float MinLabelColumnWidth = 20f;
private const float OuterPad = 5f;
private const float RightColumnWidth = 78f;
private const float MinMiddleColumnWidth= 28f;
private const float LabelComparisonPad = 1f;
private const float MiddleTextGap = 3f;
private const float MiddleRightSafeGap = 5f;
private const float SmallFontScale = 0.50f;
private const float MinSmallFontPt = 5f;
// ── Settings ──────────────────────────────────────────────────────────
private static int _nextLayoutLinkId;
private readonly SplitDetailSettings _settings;
private readonly int _layoutLinkId;
// ── Cached display data ────────────────────────────────────────────────
// Shared
private string _labelText = string.Empty;
private string _rightText = string.Empty;
private Color _rightTextColor = Color.White; // may become gold
// Current Split mode — two small stacked comparison lines
private string _cs_cmp1Label = string.Empty;
private string _cs_cmp1Time = string.Empty;
private string _cs_cmp2Label = string.Empty;
private string _cs_cmp2Time = string.Empty;
// Prior modes — compact delta block
private string _pr_delta1 = string.Empty;
private Color _pr_delta1Color = Color.White;
private string _pr_delta2 = string.Empty;
private Color _pr_delta2Color = Color.White;
private Color _backgroundDeltaColor = Color.Transparent;
private readonly LiveSplitState _state;
private int _highlightScrollOffset;
private struct MiddleLayout
{
public float ValueRight;
public float LabelX;
public float LabelW;
public float LeftBound;
public float LabelValueGap;
public MiddleLayout(float valueRight, float labelX, float labelW,
float leftBound)
: this(valueRight, labelX, labelW, leftBound, MiddleTextGap)
{
}
public MiddleLayout(float valueRight, float labelX, float labelW,
float leftBound, float labelValueGap)
{
ValueRight = valueRight;
LabelX = labelX;
LabelW = labelW;
LeftBound = leftBound;
LabelValueGap = Math.Max(0f, labelValueGap);
}
}
// ── Constructor ───────────────────────────────────────────────────────
public SplitDetailComponent(LiveSplitState state)
{
_state = state;
_layoutLinkId = System.Threading.Interlocked.Increment(ref _nextLayoutLinkId);
_settings = new SplitDetailSettings(state);
if (_state != null)
{
_state.OnStart += state_OnResetHighlightScroll;
_state.OnSplit += state_OnResetHighlightScroll;
_state.OnUndoSplit += state_OnResetHighlightScroll;
_state.OnSkipSplit += state_OnResetHighlightScroll;
_state.OnReset += state_OnResetHighlightScroll;
_state.OnScrollUp += state_OnScrollUp;
_state.OnScrollDown += state_OnScrollDown;
}
}
// ── IComponent identity ───────────────────────────────────────────────
// ComponentName is shown in the Layout Editor component list.
// We include the active mode label so multiple instances are easy to tell apart:
// "Split Detail - Current Split"
// "Split Detail - Current Seg."
// "Split Detail - Prev Split"
// "Split Detail - Prev Seg."
// (or whatever custom labels the user has chosen in Settings)
// NOTE: ComponentName reflects the configured mode, not temporary live state.
public string ComponentName
{
get
{
return "Split Detail - " + _settings.ComponentLabel;
}
}
// ── IComponent sizing ─────────────────────────────────────────────────
private float _rowHeight = 30f;
private float RowHeight => _rowHeight;
public float HorizontalWidth => 300f;
public float MinimumHeight => RowHeight;
public float VerticalHeight => RowHeight;
public float MinimumWidth => 120f;
public float PaddingTop => 0f;
public float PaddingBottom => 0f;
public float PaddingLeft => 0f;
public float PaddingRight => 0f;
public IDictionary<string, Action> ContextMenuControls => null;
// ── IComponent settings ───────────────────────────────────────────────
public Control GetSettingsControl(LayoutMode mode)
{
_settings.RefreshComparisons();
return _settings;
}
public XmlNode GetSettings(XmlDocument document) => _settings.GetSettings(document);
public void SetSettings(XmlNode settings) => _settings.SetSettings(settings);
// ── IComponent update/draw ────────────────────────────────────────────
public void Update(IInvalidator invalidator, LiveSplitState state,
float width, float height, LayoutMode mode)
{
CalculateDisplayValues(state);
invalidator?.Invalidate(0, 0, width, height);
}
public void DrawHorizontal(Graphics g, LiveSplitState state,
float height, Region clipRegion)
=> DrawRow(g, state, HorizontalWidth, height);
public void DrawVertical(Graphics g, LiveSplitState state,
float width, Region clipRegion)
=> DrawRow(g, state, width, RowHeight);
public void Dispose()
{
if (_state != null)
{
_state.OnStart -= state_OnResetHighlightScroll;
_state.OnSplit -= state_OnResetHighlightScroll;
_state.OnUndoSplit -= state_OnResetHighlightScroll;
_state.OnSkipSplit -= state_OnResetHighlightScroll;
_state.OnReset -= state_OnResetHighlightScroll;
_state.OnScrollUp -= state_OnScrollUp;
_state.OnScrollDown -= state_OnScrollDown;
}
}
private void state_OnResetHighlightScroll(object sender, EventArgs e)
{
_highlightScrollOffset = 0;
}
private void state_OnResetHighlightScroll(object sender, TimerPhase e)
{
_highlightScrollOffset = 0;
}
private void state_OnScrollUp(object sender, EventArgs e)
{
if (_state == null) return;
_highlightScrollOffset--;
ClampHighlightScrollOffset();
}
private void state_OnScrollDown(object sender, EventArgs e)
{
if (_state == null) return;
_highlightScrollOffset++;
ClampHighlightScrollOffset();
}
private void ClampHighlightScrollOffset()
{
IRun run = _state?.Run;
if (run == null || run.Count == 0)
{
_highlightScrollOffset = 0;
return;
}
int baseIndex = GetBaseHighlightSplitIndex(_state);
_highlightScrollOffset = Math.Min(
Math.Max(_highlightScrollOffset, -baseIndex),
run.Count - baseIndex - 1);
}
// =====================================================================
// GROUP / SUBSPLIT DETECTION — do not modify unless changing subsplit logic
// =====================================================================
/// <summary>
/// Given any segment index, returns the inclusive [Start, End] range
/// of the parent split GROUP that contains it.
///
/// Step 1 — Walk FORWARD until reaching a segment whose name does NOT
/// start with SubsplitPrefix → that is the group parent (end).
/// Step 2 — Walk BACKWARD from end while the preceding segment's name
/// starts with SubsplitPrefix → that is the first child (start).
///
/// If subsplits are not used, every segment is its own group (start==end).
/// </summary>
private SegmentRange GetGroupRange(IRun run, int segmentIndex)
{
if (segmentIndex < 0 || segmentIndex >= run.Count)
return SegmentRange.Invalid;
int end = segmentIndex;
while (end < run.Count - 1 && run[end].Name.StartsWith(SubsplitPrefix))
end++;
int start = end;
while (start > 0 && run[start - 1].Name.StartsWith(SubsplitPrefix))
start--;
return new SegmentRange(start, end);
}
private SegmentRange GetCurrentGroupRange(LiveSplitState state)
{
if (state.CurrentPhase == TimerPhase.NotRunning ||
state.CurrentPhase == TimerPhase.Ended)
return SegmentRange.Invalid;
int idx = state.CurrentSplitIndex;
if (idx < 0 || idx >= state.Run.Count)
return SegmentRange.Invalid;
return GetGroupRange(state.Run, idx);
}
private bool UsesHighlightedSplit(LiveSplitState state)
{
return state != null &&
(state.CurrentPhase == TimerPhase.Ended ||
_highlightScrollOffset != 0);
}
private int GetBaseHighlightSplitIndex(LiveSplitState state)
{
if (state?.Run == null || state.Run.Count == 0) return -1;
return Math.Min(Math.Max(state.CurrentSplitIndex, 0), state.Run.Count - 1);
}
private int GetHighlightedSplitIndex(LiveSplitState state)
{
if (state?.Run == null || state.Run.Count == 0) return -1;
ClampHighlightScrollOffset();
return GetBaseHighlightSplitIndex(state) + _highlightScrollOffset;
}
private SegmentRange GetPriorGroupRange(LiveSplitState state)
{
if (state.CurrentPhase == TimerPhase.NotRunning &&
!UsesHighlightedSplit(state))
return SegmentRange.Invalid;
IRun run = state.Run;
if (UsesHighlightedSplit(state))
return GetGroupRange(run, GetHighlightedSplitIndex(state));
SegmentRange currentGroup = GetCurrentGroupRange(state);
if (!currentGroup.IsValid || currentGroup.Start <= 0)
return SegmentRange.Invalid;
return GetGroupRange(run, currentGroup.Start - 1);
}
private int GetPriorSubsplitIndex(LiveSplitState state, TimingMethod method)
{
if (state.CurrentPhase == TimerPhase.NotRunning &&
!UsesHighlightedSplit(state))
{
return -1;
}
if (UsesHighlightedSplit(state))
return GetHighlightedSplitIndex(state);
int prev = state.CurrentSplitIndex - 1;
if (prev < 0) return -1;
return GetPriorSubsplitIndexAfterShortFilter(state.Run, prev, method);
}
private int GetPriorSubsplitIndexAfterShortFilter(IRun run, int startIndex,
TimingMethod method)
{
if (!_settings.IgnoreShortSubsplits ||
_settings.IgnoreShortSubsplitSeconds <= 0d ||
run == null)
{
return startIndex;
}
TimeSpan threshold = TimeSpan.FromSeconds(_settings.IgnoreShortSubsplitSeconds);
for (int idx = startIndex; idx >= 0; idx--)
{
if (!IsChildSubsplit(run, idx))
return idx;
TimeSpan? actual = GetCompletedRangeTime(run, idx, idx, method);
if (!actual.HasValue || actual.Value >= threshold)
return idx;
}
return -1;
}
private static bool IsChildSubsplit(IRun run, int index)
{
return run != null &&
index >= 0 &&
index < run.Count &&
run[index].Name.StartsWith(SubsplitPrefix);
}
private void ApplyItemNameLabel(IRun run, int segmentIndex)
{
if (!_settings.UseItemName) return;
if (run == null || segmentIndex < 0 || segmentIndex >= run.Count) return;
_labelText = FormatItemNameForDisplay(run[segmentIndex].Name);
}
private string FormatItemNameForDisplay(string name)
{
if (string.IsNullOrEmpty(name)) return string.Empty;
string displayName;
if (_settings.Mode == SplitDetailMode.CurrentSegment ||
_settings.Mode == SplitDetailMode.PriorSubsplit)
{
displayName = ExtractSegmentName(name);
}
else
{
displayName = ExtractBraceName(name);
}
return _settings.AlwaysRemoveLeadingNumbers
? RemoveLeadingNumberParts(displayName)
: displayName;
}
private static string ExtractSegmentName(string name)
{
if (string.IsNullOrEmpty(name)) return string.Empty;
string segmentName = RemoveLeadingBracePrefix(name);
segmentName = RemoveLeadingSubsplitPrefix(segmentName);
return string.IsNullOrEmpty(segmentName) ? ExtractBraceName(name) : segmentName;
}
private static string RemoveLeadingBracePrefix(string name)
{
if (string.IsNullOrEmpty(name)) return string.Empty;
if (name[0] != '{') return name;
int close = name.IndexOf('}');
if (close <= 0 || close >= name.Length - 1) return name;
return name.Substring(close + 1).TrimStart();
}
private static string RemoveLeadingSubsplitPrefix(string name)
{
if (string.IsNullOrEmpty(name)) return string.Empty;
if (name[0] == '-')
return name.Substring(1).TrimStart();
return name;
}
private static string ExtractBraceName(string name)
{
if (string.IsNullOrEmpty(name)) return string.Empty;
if (name[0] != '{') return name;
int close = name.IndexOf('}');
if (close <= 1) return name;
return name.Substring(1, close - 1);
}
private static string RemoveLeadingNumberParts(string name)
{
if (string.IsNullOrWhiteSpace(name)) return string.Empty;
string result = name.TrimStart();
bool removedAny = false;
while (!string.IsNullOrEmpty(result))
{
int tokenEnd = FirstWhitespaceIndex(result);
if (tokenEnd <= 0)
break;
string token = result.Substring(0, tokenEnd);
if (!ContainsDigit(token))
break;
result = result.Substring(tokenEnd).TrimStart();
removedAny = true;
}
if (removedAny)
result = TrimLeadingNameSeparators(result);
return string.IsNullOrEmpty(result) ? name.Trim() : result;
}
private static int FirstWhitespaceIndex(string text)
{
for (int i = 0; i < text.Length; i++)
{
if (char.IsWhiteSpace(text[i]))
return i;
}
return -1;
}
private static bool ContainsDigit(string text)
{
for (int i = 0; i < text.Length; i++)
{
if (char.IsDigit(text[i]))
return true;
}
return false;
}
private static string TrimLeadingNameSeparators(string text)
{
string result = text.TrimStart();
while (result.Length > 0 &&
(result[0] == '-' || result[0] == ':' || result[0] == '/' ||
result[0] == '\\' || result[0] == '|' || result[0] == '.'))
{
result = result.Substring(1).TrimStart();
}
return result;
}
// =====================================================================
// TIMING CALCULATIONS — do not modify unless changing timing logic
// =====================================================================
private TimeSpan? GetCompletedRangeTime(IRun run, int start, int end,
TimingMethod method)
{
TimeSpan? endTime = run[end].SplitTime[method];
if (endTime == null) return null;
if (start == 0) return endTime;
TimeSpan? startTime = run[start - 1].SplitTime[method];
if (startTime == null) return null;
return endTime - startTime;
}
private TimeSpan? GetActiveRangeTime(IRun run, LiveSplitState state,
int start, int end,
TimingMethod method)
{
TimeSpan? currentTime = state.CurrentTime[method];
if (currentTime == null) return null;
if (start == 0) return currentTime;
TimeSpan? startTime = run[start - 1].SplitTime[method];
if (startTime == null) return null;
return currentTime - startTime;
}
/// <summary>
/// Gets the active elapsed time for the current segment (not yet split).
/// </summary>
private TimeSpan? GetActiveSegmentTime(IRun run, LiveSplitState state,
int segmentIndex, TimingMethod method)
{
TimeSpan? currentTime = state.CurrentTime[method];
if (currentTime == null) return null;
if (segmentIndex == 0) return currentTime;
TimeSpan? prevSplitTime = run[segmentIndex - 1].SplitTime[method];
if (prevSplitTime == null) return null;
return currentTime - prevSplitTime;
}
private TimeSpan? GetComparisonRangeTime(IRun run, int start, int end,
string comparison,
TimingMethod method)
{
if (!HasComparison(run, comparison) ||
start < 0 || end < start || end >= run.Count)
return null;
TimeSpan? endTime = run[end].Comparisons[comparison][method];
if (endTime == null) return null;
if (start == 0) return endTime;
TimeSpan? startTime = run[start - 1].Comparisons[comparison][method];
if (startTime == null) return null;
return endTime - startTime;
}
// =====================================================================
// GOLD DETECTION
// =====================================================================
/// <summary>
/// Returns true if 'actual' is faster than the sum of best segment times
/// for the given range — i.e. the runner just set a new best for this group.
/// Uses BestSegmentTime per-segment and sums them, matching how LiveSplit
/// tracks golds at the segment level.
/// </summary>
private static bool IsNewBest(IRun run, int start, int end,
TimeSpan? actual, TimingMethod method)
{
if (!actual.HasValue) return false;
TimeSpan bestSum = TimeSpan.Zero;
for (int i = start; i <= end; i++)
{
TimeSpan? best = run[i].BestSegmentTime[method];
if (!best.HasValue) return false; // no reference → can't confirm gold
bestSum += best.Value;
}
return actual.Value < bestSum;
}
/// <summary>
/// Returns the gold/best-segment color from layout settings.
/// Tries several property names via reflection for version compatibility,
/// then falls back to a standard gold color.
/// </summary>
private static Color GetGoldColor(LiveSplitState state)
{
var ls = state.LayoutSettings;
Color c = GetLayoutSetting(ls, "GoldColor", Color.Transparent);
if (c == Color.Transparent)
c = GetLayoutSetting(ls, "BestSegmentColor", Color.Transparent);
if (c == Color.Transparent)
c = Color.FromArgb(255, 215, 0); // standard gold fallback
return c;
}
// =====================================================================
// LIVE MODE DETECTION — determine when to show current (live) vs prior
// =====================================================================
/// <summary>
/// Determines if the current active split group is losing time compared to
/// the selected comparison(s).
/// Returns true if the priority delta is positive (losing time).
///
/// Use ComparisonCount to decide which comparison to check:
/// - if ComparisonCount == 1: use Comparison 1 (ignore PriorityDelta)
/// - if ComparisonCount == 2: use the priority comparison
/// </summary>
private bool IsCurrentSplitLosingTime(LiveSplitState state, IRun run,
TimingMethod method, string cmp1, string cmp2)
{
SegmentRange group = GetCurrentGroupRange(state);
if (!group.IsValid) return false;
TimeSpan? activeTime = GetActiveRangeTime(run, state, group.Start, group.End, method);
if (!activeTime.HasValue) return false;
// Determine which comparison to use for live detection
string comparisonToCheck;
if (_settings.ComparisonCount == 1)
{
// Only one comparison shown: use Comparison 1
comparisonToCheck = cmp1;
}
else
{
// Two comparisons shown: use priority delta setting
comparisonToCheck = (_settings.PriorityDelta == 1) ? cmp1 : cmp2;
}
TimeSpan? comparisonTime = GetComparisonRangeTime(run, group.Start, group.End,
comparisonToCheck, method);
if (!comparisonTime.HasValue) return false;
TimeSpan delta = activeTime.Value - comparisonTime.Value;
return delta.Ticks > 0; // Positive delta = losing time
}
/// <summary>
/// Determines if the current active segment is losing time compared to
/// the selected comparison(s).
/// Returns true if the priority delta is positive (losing time).
///
/// Use ComparisonCount to decide which comparison to check:
/// - if ComparisonCount == 1: use Comparison 1 (ignore PriorityDelta)
/// - if ComparisonCount == 2: use the priority comparison
/// </summary>
private bool IsCurrentSegmentLosingTime(LiveSplitState state, IRun run,
TimingMethod method, string cmp1, string cmp2)
{
int currentIdx = state.CurrentSplitIndex;
if (currentIdx < 0 || currentIdx >= run.Count) return false;
// Get the active elapsed time for the current segment
TimeSpan? activeTime = GetActiveSegmentTime(run, state, currentIdx, method);
if (!activeTime.HasValue) return false;
// Determine which comparison to use for live detection
string comparisonToCheck;
if (_settings.ComparisonCount == 1)
{
// Only one comparison shown: use Comparison 1
comparisonToCheck = cmp1;
}
else
{
// Two comparisons shown: use priority delta setting
comparisonToCheck = (_settings.PriorityDelta == 1) ? cmp1 : cmp2;
}
// Get the segment-only comparison time (not cumulative)
TimeSpan? comparisonTime = GetComparisonRangeTime(run, currentIdx, currentIdx,
comparisonToCheck, method);
if (!comparisonTime.HasValue) return false;
TimeSpan delta = activeTime.Value - comparisonTime.Value;
return delta.Ticks > 0; // Positive delta = losing time
}
// =====================================================================
// DISPLAY VALUE CALCULATION
// =====================================================================
private void CalculateDisplayValues(LiveSplitState state)
{
_labelText = string.Empty;
_rightText = Dash;
_rightTextColor = _settings.TimeColor;
_cs_cmp1Label = string.Empty;
_cs_cmp1Time = Dash;
_cs_cmp2Label = string.Empty;
_cs_cmp2Time = Dash;
_pr_delta1 = Dash;
_pr_delta2 = Dash;
_pr_delta1Color = _settings.TextColor;
_pr_delta2Color = _settings.TextColor;
_backgroundDeltaColor = Color.Transparent;
IRun run = state.Run;
TimingMethod meth = state.CurrentTimingMethod;
string cmp1 = ResolveComparisonChoice(state, run, _settings.Comparison1, "Personal Best");
string cmp2 = ResolveComparisonChoice(state, run, _settings.Comparison2, "Best Segments");
switch (_settings.Mode)
{
case SplitDetailMode.CurrentSplit:
CalcCurrentSplit(state, run, meth, cmp1, cmp2, isCurrentSubsplit: false);
break;
case SplitDetailMode.CurrentSegment:
CalcCurrentSplit(state, run, meth, cmp1, cmp2, isCurrentSubsplit: true);
break;
case SplitDetailMode.PriorSplit:
CalcPriorRange(state, run, meth, cmp1, cmp2, isPriorSubsplit: false);
break;
case SplitDetailMode.PriorSubsplit:
CalcPriorRange(state, run, meth, cmp1, cmp2, isPriorSubsplit: true);
break;
}
}
// ── Current Split / Current Seg. ──────────────────────────────────────
//
// Left │ Middle │ Right
// ───────────────│─────────────────────────│────────────
// Current Split │ PB: 1:36.55 │
// │ Best: 1:21.35 │ 17:15.84
//
private void SetBackgroundDeltaColor(LiveSplitState state,
IRun run,
int start,
int end,