Compare commits
24
Commits
e92ce4bb63
...
7829610cad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7829610cad | ||
|
|
c03acd0aa0 | ||
|
|
28525c90aa | ||
|
|
460b36204d | ||
|
|
882b8551d9 | ||
|
|
e27e79962c | ||
|
|
8caee21b9a | ||
|
|
9405c54750 | ||
|
|
e6abc13461 | ||
|
|
ea1017776d | ||
|
|
38c2ad6555 | ||
|
|
85a4a8a7d3 | ||
|
|
96d528b3ac | ||
|
|
d4a4b1c80e | ||
|
|
b205ce9ba9 | ||
|
|
9a6099af7c | ||
|
|
7048bd8bff | ||
|
|
534f56a7c4 | ||
|
|
deb74529a6 | ||
|
|
41b0cd6e98 | ||
|
|
fbcccea0f7 | ||
|
|
359e58a4c2 | ||
|
|
6b6ccd7b0a | ||
|
|
3ed8386303 |
@@ -208,6 +208,9 @@
|
||||
<Path Data="M4,5 H20 V19 H4 Z M10,9 L15,12 L10,15 Z" Stroke="{StaticResource Brush.Tertiary}" StrokeThickness="1.6" StrokeLineJoin="Round" Stretch="Uniform">
|
||||
<Path.Style><Style TargetType="Path"><Setter Property="Visibility" Value="Collapsed"/><Style.Triggers><DataTrigger Binding="{Binding IsMediaSource}" Value="True"><Setter Property="Visibility" Value="Visible"/></DataTrigger></Style.Triggers></Style></Path.Style>
|
||||
</Path>
|
||||
<Path Data="M3,9 H21 V15 H3 Z M6,12 H12 M15,12 H18" Stroke="{StaticResource Brush.Tertiary}" StrokeThickness="1.6" StrokeLineJoin="Round" Stretch="Uniform">
|
||||
<Path.Style><Style TargetType="Path"><Setter Property="Visibility" Value="Collapsed"/><Style.Triggers><DataTrigger Binding="{Binding IsScoreboard}" Value="True"><Setter Property="Visibility" Value="Visible"/></DataTrigger></Style.Triggers></Style></Path.Style>
|
||||
</Path>
|
||||
<Path Data="M6,16 V11 A6,6 0 0 1 18,11 V16 L20,18 H4 Z M10,20 H14" Stroke="{StaticResource Brush.Tertiary}" StrokeThickness="1.6" StrokeLineJoin="Round" Stretch="Uniform">
|
||||
<Path.Style><Style TargetType="Path"><Setter Property="Visibility" Value="Collapsed"/><Style.Triggers><DataTrigger Binding="{Binding IsAlertBox}" Value="True"><Setter Property="Visibility" Value="Visible"/></DataTrigger></Style.Triggers></Style></Path.Style>
|
||||
</Path>
|
||||
@@ -447,6 +450,96 @@
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Scoreboard config (creator 2026-10-30): the ego wall's billboard —
|
||||
which eight facts show, and how the strip is painted. -->
|
||||
<!-- The scoreboard is fed by the signed-in channel, so its controls are
|
||||
inert until there is an account; signing in re-enables them through
|
||||
the ordinary IsConnected notification. -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsScoreboard, Converter={StaticResource BoolToVis}}"
|
||||
IsEnabled="{Binding CanUseScoreboard}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Sign in to YouTube to use the scoreboard."
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="0,0,0,4"
|
||||
Visibility="{Binding CanUseScoreboard, Converter={StaticResource InverseBoolToVis}}"/>
|
||||
<!-- DEBUG builds only: prove the strip in the preview before a real
|
||||
stream. Absent from Release, not merely hidden by a flag. -->
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Margin="0,0,0,4"
|
||||
IsChecked="{Binding ScoreboardSimulate, Mode=TwoWay}"
|
||||
ToolTip="Push sample events so the strip appears in the preview."
|
||||
Visibility="{Binding IsDevelopmentBuild, Converter={StaticResource BoolToVis}}">
|
||||
<!-- Dev-only affordances wear orange so a development control can never
|
||||
be mistaken for product. -->
|
||||
<TextBlock Text="Simulate (dev)" Foreground="{StaticResource Brush.Attention}" FontSize="12"/>
|
||||
</CheckBox>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Margin="0,0,0,4"
|
||||
Content="Show the scoreboard" IsChecked="{Binding ScoreboardEnabled, Mode=TwoWay}"
|
||||
ToolTip="Off hides the strip in every scene AND stops the channel polling."/>
|
||||
<TextBlock Text="Edge (socials take the other)" Foreground="{StaticResource Brush.OnSurfaceVariant}"
|
||||
FontSize="11" Margin="10,0,0,2"/>
|
||||
<ComboBox Style="{StaticResource YtComboBox}" Height="24" FontSize="11" Margin="10,0,0,6"
|
||||
ItemsSource="{Binding ScoreboardEdgeOptions}"
|
||||
SelectedItem="{Binding ScoreboardEdge, Mode=TwoWay}"/>
|
||||
|
||||
<DockPanel Margin="10,0,0,6">
|
||||
<TextBlock DockPanel.Dock="Left" Text="Scroll speed" Foreground="{StaticResource Brush.OnSurfaceVariant}"
|
||||
FontSize="11" Width="76" VerticalAlignment="Center"/>
|
||||
<TextBlock DockPanel.Dock="Right" Width="56" TextAlignment="Right" FontSize="11"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" VerticalAlignment="Center"
|
||||
Text="{Binding ScoreboardScrollSpeed, StringFormat={}{0:0} px/s}"/>
|
||||
<Slider Minimum="20" Maximum="200" SmallChange="10" LargeChange="40"
|
||||
Value="{Binding ScoreboardScrollSpeed, Mode=TwoWay}" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
|
||||
<TextBlock Text="Facts" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" FontWeight="SemiBold" Margin="0,0,0,4"/>
|
||||
<WrapPanel Margin="10,0,0,0">
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Subscribers" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowSubscribers, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Watch hours" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowWatchHours, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Super Chats" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowSuperChats, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="New members" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowNewMembers, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Milestones" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowMilestones, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Last member" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowLastMember, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Last Super Chat" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowLastSuperChat, Mode=TwoWay}"/>
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Last gift" Margin="0,0,10,4"
|
||||
IsChecked="{Binding ScoreboardShowLastGift, Mode=TwoWay}"/>
|
||||
</WrapPanel>
|
||||
|
||||
<TextBlock Text="Text colour" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="10,6,0,2"/>
|
||||
<ComboBox Style="{StaticResource YtComboBox}" Height="24" FontSize="11" Margin="10,0,0,6"
|
||||
ItemsSource="{Binding ScoreboardColorOptions}" DisplayMemberPath="Name"
|
||||
SelectedValuePath="Hex" SelectedValue="{Binding ScoreboardTextColor, Mode=TwoWay}"/>
|
||||
|
||||
<CheckBox Style="{StaticResource YtCheckBox}" Content="Background" Margin="10,0,0,4"
|
||||
IsChecked="{Binding ScoreboardBackgroundEnabled, Mode=TwoWay}"/>
|
||||
<ComboBox Style="{StaticResource YtComboBox}" Height="24" FontSize="11" Margin="10,0,0,6"
|
||||
ItemsSource="{Binding ScoreboardColorOptions}" DisplayMemberPath="Name"
|
||||
SelectedValuePath="Hex" SelectedValue="{Binding ScoreboardBackgroundColor, Mode=TwoWay}"/>
|
||||
<DockPanel Margin="10,0,0,6">
|
||||
<TextBlock DockPanel.Dock="Left" Text="Opacity" Foreground="{StaticResource Brush.OnSurfaceVariant}"
|
||||
FontSize="11" Width="60" VerticalAlignment="Center"/>
|
||||
<TextBlock DockPanel.Dock="Right" Width="42" TextAlignment="Right" FontSize="11"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" VerticalAlignment="Center"
|
||||
Text="{Binding ScoreboardBackgroundOpacity, StringFormat={}{0:P0}}"/>
|
||||
<Slider Minimum="0" Maximum="1" SmallChange="0.05" LargeChange="0.1"
|
||||
Value="{Binding ScoreboardBackgroundOpacity, Mode=TwoWay}" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
|
||||
<DockPanel Margin="10,0,0,0">
|
||||
<TextBlock DockPanel.Dock="Left" Text="Text size" Foreground="{StaticResource Brush.OnSurfaceVariant}"
|
||||
FontSize="11" Width="60" VerticalAlignment="Center"/>
|
||||
<TextBlock DockPanel.Dock="Right" Width="56" TextAlignment="Right" FontSize="11"
|
||||
Foreground="{StaticResource Brush.OnSurfaceVariant}" VerticalAlignment="Center"
|
||||
Text="{Binding ScoreboardFontSizeLabel}"/>
|
||||
<Slider Minimum="14" Maximum="24" SmallChange="1" LargeChange="2" TickFrequency="1" IsSnapToTickEnabled="True"
|
||||
Value="{Binding ScoreboardFontSize, Mode=TwoWay}" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Countdown config -->
|
||||
<StackPanel Visibility="{Binding SelectedElement.IsCountdown, Converter={StaticResource BoolToVis}}" Margin="0,0,0,8">
|
||||
<TextBlock Text="Timer (minutes)" Foreground="{StaticResource Brush.OnSurfaceVariant}" FontSize="11" Margin="0,0,0,2"/>
|
||||
|
||||
@@ -138,6 +138,11 @@
|
||||
<DataTrigger Binding="{Binding IsAlertBox}" Value="True">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
<!-- The scoreboard strip is a frame-source too: without this trigger its
|
||||
Image stays collapsed and every property change looks inert. -->
|
||||
<DataTrigger Binding="{Binding IsScoreboard}" Value="True">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsWebSource}" Value="True">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
<Setter Property="Stretch" Value="Fill"/>
|
||||
|
||||
+20
-17
@@ -1,26 +1,29 @@
|
||||
# HANDOFF — 2026-10-30 (audio dock shipped; needs an eyes/hands pass)
|
||||
# HANDOFF — 2026-10-30 (scoreboard built to the polling policy; two wiring items left)
|
||||
|
||||
## State
|
||||
|
||||
- Branch `main`, worktree clean. Ten dock units landed on top of the design conversion; nothing
|
||||
pushed since `1724922` — this batch is local.
|
||||
- **The sound bars exist**: `Controls/AudioDock` — master strip on top (nearest the preview), four
|
||||
bays below (MIC / GAME / TRAX / LIP-SYNC), 148px, auto-collapsing to 36px below a 900px window
|
||||
height. The dock is now the ONLY audio surface; the preview's mic row, game chip, TRAX button and
|
||||
sync slider are deleted.
|
||||
- Faders speak dB (`Helpers/GainDb`, 0 dB = unity). Ladders are measured (`SegmentMeter` +
|
||||
`MeterScale`), never decorative. The duck badge prints the gain the mixer applied.
|
||||
- **MONO output** (creator ruling): folds the finished mix to both channels, persisted as
|
||||
`Audio.MonoOutput`, one click in the master strip. Exists because single-sided audio is inaudible
|
||||
with profound right-side deafness, not merely unbalanced.
|
||||
- Deliberately absent: L/R ladders (one ladder + an imbalance flag instead), TRAX scrub/prev-next
|
||||
(OBS territory), CPU/GPU/NVENC readouts, acrylic.
|
||||
- Branch `main`. The audio dock is shipped and pushed. **The scoreboard is built** in ten units,
|
||||
local commits only: tallies (`Models/ScoreboardState`, session-scoped), lifecycle
|
||||
(`ScoreboardRecorder`: start clears, End freezes), layout (`Models/ScoreboardLayout`: coupled
|
||||
edges resolved at render time, shrink-then-wrap, never scroll), renderer
|
||||
(`Services/Compositor/ScoreboardRenderer`: plate + text colour + opacity + 14–24px, cached),
|
||||
tile selection (`Models/ScoreboardTiles`, opt-in, money per currency), the cached presenter, the
|
||||
layer itself (`SourceType.Scoreboard`, strip geometry, resolver case), the properties panel
|
||||
(eight fact switches + colours + plate + size, theme widgets only), the Analytics scope
|
||||
(`yt-analytics.readonly`, incremental, `HasAnalyticsScope`), and the polling policy
|
||||
(`Models/ScoreboardCadence`).
|
||||
- Fixed on the way: the chat feed now reaches the tallies (the recorder had no caller).
|
||||
|
||||
## Next action
|
||||
|
||||
Nothing queued. **Needs the creator's hands**: launch and judge the dock at the real window size —
|
||||
bay proportions at 148px, the master strip's ladder/label density, and whether the MONO fold sounds
|
||||
right through their own ears/headphones (the one thing no test can answer).
|
||||
1. **HTTP providers** behind the cadence policy: watch hours (`reports.query`,
|
||||
`metrics=estimatedMinutesWatched`) and subscriber count (`channels.list?mine=true&part=statistics`),
|
||||
both behind an interface with a fake for tests, plus the timer that calls
|
||||
`ScoreboardCadence.Due(...)` and writes the values into `ScoreboardTiles`.
|
||||
2. **Goal-target inputs** in the properties panel (the tiles read `SubscriberGoal`/`WatchHourGoal`
|
||||
but nothing sets them yet).
|
||||
3. **On-screen check** of the strip: one line at 24px, plate/opacity, and the edge swap against the
|
||||
social bar.
|
||||
|
||||
## Landmines
|
||||
|
||||
|
||||
@@ -85,6 +85,9 @@ public abstract class SceneElement : INotifyPropertyChanged
|
||||
/// <summary>True only for AlertBox-type sources. Gates stream alerts properties panel.</summary>
|
||||
public virtual bool IsAlertBox => false;
|
||||
public virtual bool IsTextOverlay => false;
|
||||
|
||||
/// <summary>The scoreboard strip: a per-scene, full-width bar.</summary>
|
||||
public virtual bool IsScoreboard => false;
|
||||
public virtual bool IsMediaSource => false;
|
||||
public virtual bool IsLiveCapture => false;
|
||||
public virtual bool IsBackground { get; set; }
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>What kind of session the app is in, for polling decisions.</summary>
|
||||
public enum SessionPhase
|
||||
{
|
||||
Idle,
|
||||
Live,
|
||||
Test,
|
||||
Recording,
|
||||
}
|
||||
|
||||
/// <summary>Which channel figures a poll should fetch.</summary>
|
||||
public enum ScoreboardPoll
|
||||
{
|
||||
None,
|
||||
SubscribersOnly,
|
||||
Both,
|
||||
}
|
||||
|
||||
/// <summary>Polling policy for the scoreboard's two channel figures (creator ruling 2026-10-30).
|
||||
///
|
||||
/// <para>Analytics answers in DAYS, and test/record sessions have no public audience — so querying
|
||||
/// watch hours then is pure waste. Subscriber count is cheap (one quota unit) and moves during any
|
||||
/// session, so it polls whenever the app is working. Idle means silent.</para></summary>
|
||||
public static class ScoreboardCadence
|
||||
{
|
||||
public static readonly TimeSpan AnalyticsInterval = TimeSpan.FromMinutes(30);
|
||||
public static readonly TimeSpan SubscriberInterval = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary><paramref name="enabled"/> is the layer's master switch. Off means NOTHING is
|
||||
/// polled, whatever the session is doing — a hidden scoreboard has no reason to spend quota
|
||||
/// (creator ruling 2026-10-30).</summary>
|
||||
public static ScoreboardPoll Due(SessionPhase phase, DateTime lastAnalyticsUtc, DateTime lastSubscriberUtc,
|
||||
DateTime nowUtc, bool enabled = true)
|
||||
{
|
||||
if (!enabled) return ScoreboardPoll.None;
|
||||
if (phase == SessionPhase.Idle) return ScoreboardPoll.None;
|
||||
|
||||
var analyticsDue = phase == SessionPhase.Live && nowUtc - lastAnalyticsUtc >= AnalyticsInterval;
|
||||
var subscribersDue = nowUtc - lastSubscriberUtc >= SubscriberInterval;
|
||||
|
||||
return (analyticsDue, subscribersDue) switch
|
||||
{
|
||||
(true, true) => ScoreboardPoll.Both,
|
||||
(true, false) => ScoreboardPoll.None, // analytics alone is not a poll kind
|
||||
(false, true) => ScoreboardPoll.SubscribersOnly,
|
||||
_ => ScoreboardPoll.None,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>Keeps exactly one Scoreboard layer in EVERY scene.
|
||||
///
|
||||
/// <para>Creator ruling (2026-10-30): "YT_ACTIVITY_TICKER … is available to all scenes." The
|
||||
/// scoreboard is not something to add five times — it exists once per scene like the Background and
|
||||
/// the Brand logo, and a creator turns it off per scene with the ordinary eye toggle. Removing it is
|
||||
/// therefore not a delete: it heals on the next load.</para>
|
||||
///
|
||||
/// <para>Pure over a scene collection, so the rule is testable without a view-model.</para></summary>
|
||||
public static class ScoreboardHealer
|
||||
{
|
||||
public const string LayerName = "Scoreboard";
|
||||
|
||||
/// <summary>The strip's default box: full width, a strip's height, and its Y for the bottom
|
||||
/// edge. Geometry only — the EDGE itself is resolved against the social bar at render time.</summary>
|
||||
public const double StripHeight = 56;
|
||||
public const double BottomY = 1080 - StripHeight;
|
||||
|
||||
/// <summary>Ensures one scoreboard per scene, appended as the TOPMOST layer: it is a full-width
|
||||
/// strip drawn over the scene, and inserting it above the background would break the Brand
|
||||
/// logo's documented invariant ("directly above the background"). Returns true when anything
|
||||
/// changed, so the caller can save.</summary>
|
||||
public static bool Ensure(IEnumerable<Scene> scenes)
|
||||
{
|
||||
var changed = false;
|
||||
foreach (var scene in scenes)
|
||||
{
|
||||
var existing = scene.Elements.OfType<Source>().Where(s => s.IsScoreboard).ToList();
|
||||
|
||||
// More than one: keep the first, drop the rest.
|
||||
foreach (var extra in existing.Skip(1))
|
||||
{
|
||||
scene.Elements.Remove(extra);
|
||||
changed = true;
|
||||
}
|
||||
if (existing.Count > 0) continue;
|
||||
|
||||
scene.Elements.Add(new Source
|
||||
{
|
||||
Name = LayerName,
|
||||
Type = SourceType.Scoreboard,
|
||||
IsEnabled = true,
|
||||
X = 0,
|
||||
Y = BottomY,
|
||||
Width = 1920,
|
||||
Height = StripHeight,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>Which edge a full-width bar occupies.</summary>
|
||||
public enum BarEdge
|
||||
{
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
/// <summary>The scoreboard's placement and line-fitting arithmetic, kept pure so both are testable
|
||||
/// without a renderer.
|
||||
///
|
||||
/// <para>Two rules from the creator (2026-10-30):
|
||||
/// the strip and the social bar are a COUPLED pair that own opposite edges, resolved at render time
|
||||
/// from what is actually visible; and a strip that does not fit SHRINKS to a floor and then wraps to
|
||||
/// a second line — it never scrolls, because a creator reading the screen cannot wait for the fact
|
||||
/// to come round.</para></summary>
|
||||
public static class ScoreboardLayout
|
||||
{
|
||||
public const double FloorFontSize = 14;
|
||||
public const double MaxFontSize = 24;
|
||||
|
||||
/// <summary>Result of fitting the enabled tiles into one strip.</summary>
|
||||
public readonly record struct Fit(double FontSize, int LineCount, bool Shrunk)
|
||||
{
|
||||
public bool Wrapped => LineCount > 1;
|
||||
}
|
||||
|
||||
/// <summary>Resolves the edge pair. When both bars are visible they take opposite edges; the
|
||||
/// social bar keeps its own choice and the scoreboard is pushed to the other one. When either is
|
||||
/// hidden the survivor keeps its preferred edge — so hiding the scoreboard frees the social bar
|
||||
/// to sit anywhere, exactly as the creator asked.</summary>
|
||||
public static (BarEdge Social, BarEdge Scoreboard) ResolveEdges(
|
||||
bool socialVisible, BarEdge socialPreferred,
|
||||
bool scoreboardVisible, BarEdge scoreboardPreferred)
|
||||
{
|
||||
if (socialVisible && scoreboardVisible)
|
||||
return (socialPreferred, Opposite(socialPreferred));
|
||||
|
||||
return (socialPreferred, scoreboardPreferred);
|
||||
}
|
||||
|
||||
public static BarEdge Opposite(BarEdge edge) => edge == BarEdge.Top ? BarEdge.Bottom : BarEdge.Top;
|
||||
|
||||
/// <summary>Fits measured tile widths (at <paramref name="requestedSize"/>) into the available
|
||||
/// width: full size if they fit, otherwise shrink, and only if the shrink would drop below the
|
||||
/// legibility floor does it wrap. Widths are passed in because the renderer MEASURES them —
|
||||
/// guessing a character width would make the fit lie for a wide glyph or a long handle.</summary>
|
||||
public static Fit FitLine(IReadOnlyList<double> tileWidths, double separatorWidth,
|
||||
double availableWidth, double requestedSize = MaxFontSize, double floorSize = FloorFontSize)
|
||||
{
|
||||
var widths = tileWidths ?? System.Array.Empty<double>();
|
||||
var count = widths.Count;
|
||||
if (count == 0 || availableWidth <= 0)
|
||||
return new Fit(requestedSize, 1, false);
|
||||
|
||||
var total = widths.Sum() + separatorWidth * (count - 1);
|
||||
if (total <= availableWidth)
|
||||
return new Fit(requestedSize, 1, false);
|
||||
|
||||
var scaled = requestedSize * (availableWidth / total);
|
||||
if (scaled >= floorSize)
|
||||
return new Fit(scaled, 1, true);
|
||||
|
||||
// Below the floor: keep the floor and wrap. Greedy packing, measured widths scaled to the
|
||||
// floor size so the line breaks match what is actually drawn.
|
||||
var factor = floorSize / requestedSize;
|
||||
var lines = 1;
|
||||
var lineWidth = 0.0;
|
||||
foreach (var width in widths)
|
||||
{
|
||||
var w = width * factor;
|
||||
var needed = lineWidth == 0 ? w : lineWidth + separatorWidth + w;
|
||||
if (needed > availableWidth && lineWidth > 0)
|
||||
{
|
||||
lines++;
|
||||
lineWidth = w;
|
||||
}
|
||||
else
|
||||
{
|
||||
lineWidth = needed;
|
||||
}
|
||||
}
|
||||
return new Fit(floorSize, lines, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>Owns the session's <see cref="ScoreboardState"/> and the one lifecycle rule that
|
||||
/// matters: a new session starts from zero.
|
||||
///
|
||||
/// <para>Kept separate from the view-model so the rule is testable without a window, and so the
|
||||
/// scoreboard layer has exactly one place that decides when counting begins.</para></summary>
|
||||
public sealed class ScoreboardRecorder
|
||||
{
|
||||
public ScoreboardState State { get; private set; } = new();
|
||||
|
||||
/// <summary>Called when a session starts (go-live, test, or a local recording). Every start
|
||||
/// clears the tallies — "session" is the only scope the numbers promise.</summary>
|
||||
public void StartSession()
|
||||
{
|
||||
State = new ScoreboardState();
|
||||
IsRunning = true;
|
||||
RaiseChanged();
|
||||
}
|
||||
|
||||
/// <summary>Folds a chat event in. Outside a session nothing is counted: a stale tally left over
|
||||
/// from the last stream would be the "today" lie this design exists to avoid.</summary>
|
||||
public void Record(ChatMessage message)
|
||||
{
|
||||
if (!IsRunning) return;
|
||||
var before = Fingerprint(State);
|
||||
State.Apply(message);
|
||||
if (Fingerprint(State) != before) RaiseChanged();
|
||||
}
|
||||
|
||||
/// <summary>True while the tallies are live.</summary>
|
||||
public bool IsRunning { get; private set; }
|
||||
|
||||
/// <summary>Marks the session finished. The tallies stay visible (the End screen may show
|
||||
/// them) but stop moving.</summary>
|
||||
public void EndSession()
|
||||
{
|
||||
IsRunning = false;
|
||||
RaiseChanged();
|
||||
}
|
||||
|
||||
public event System.Action? Changed;
|
||||
|
||||
private void RaiseChanged() => Changed?.Invoke();
|
||||
|
||||
/// <summary>Cheap change detector: only re-render the strip when a displayed value moved.</summary>
|
||||
private static string Fingerprint(ScoreboardState state) =>
|
||||
$"{state.NewMembers}|{state.MilestoneCount}|{state.LastMemberName}|{state.LastGifterName}|" +
|
||||
$"{state.LastGiftCount}|{state.LastSuperChatAuthor}|{state.LastSuperChatDisplay}|" +
|
||||
$"{state.SessionTotal.Currency}|{state.SessionTotal.Total:0.######}";
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>Development-only sample data for the scoreboard.
|
||||
///
|
||||
/// <para>Creator (2026-10-30): the strip must be provable in the PREVIEW before a real stream —
|
||||
/// "simulate the ticker so we can see it and ensure it's getting composited". Synthetic events go
|
||||
/// through the same <see cref="ScoreboardRecorder"/> a live stream uses, so what the preview shows
|
||||
/// is exactly what real events would produce; nothing here fakes the renderer.</para>
|
||||
///
|
||||
/// <para>Kept in the model (not the view-model) so the sample is testable without a window.</para></summary>
|
||||
public static class ScoreboardSample
|
||||
{
|
||||
public static void Inject(ScoreboardRecorder recorder)
|
||||
{
|
||||
if (!recorder.IsRunning) recorder.StartSession();
|
||||
|
||||
recorder.Record(new ChatMessage { Kind = ChatEventKind.NewMember, AuthorName = "newviewer" });
|
||||
recorder.Record(new ChatMessage
|
||||
{
|
||||
Kind = ChatEventKind.MemberGift, AuthorName = "giftgiver", GiftNewMembersCount = 3,
|
||||
});
|
||||
recorder.Record(new ChatMessage { Kind = ChatEventKind.MemberMilestone, AuthorName = "longtimer" });
|
||||
recorder.Record(new ChatMessage
|
||||
{
|
||||
Kind = ChatEventKind.SuperChat, AuthorName = "tipper",
|
||||
SuperChatAmount = 12.34, SuperChatCurrency = "USD", SuperChatDisplayString = "$12.34",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>The session's scoreboard tallies — the facts a creator puts on screen to prove the
|
||||
/// channel is moving.
|
||||
///
|
||||
/// <para>Scope is the RUNNING SESSION (creator ruling 2026-10-30): the counts start at zero when a
|
||||
/// session starts and die with it. No persistence, nothing to reconcile, and every number is true
|
||||
/// for exactly what this session saw — a stored "today" that survives a Windows restart would be
|
||||
/// right only for the hours the app happened to be running, which is a lie the creator cannot
|
||||
/// check.</para>
|
||||
///
|
||||
/// <para>The two polled tiles (subscribers, watch hours) are NOT here: they are channel state, not
|
||||
/// session events, and live on the polled side of the scoreboard.</para></summary>
|
||||
public sealed class ScoreboardState
|
||||
{
|
||||
/// <summary>Super Chat + Super Sticker money, per currency. Adding across currencies would be
|
||||
/// the one arithmetic nobody forgives, so totals are keyed and only the dominant one is shown.</summary>
|
||||
private readonly Dictionary<string, double> _moneyByCurrency = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public string? LastMemberName { get; private set; }
|
||||
public string? LastSuperChatAuthor { get; private set; }
|
||||
public string? LastSuperChatDisplay { get; private set; }
|
||||
public double LastSuperChatAmount { get; private set; }
|
||||
public string? LastSuperChatCurrency { get; private set; }
|
||||
public string? LastGifterName { get; private set; }
|
||||
public int LastGiftCount { get; private set; }
|
||||
|
||||
/// <summary>Members gained this session: paid memberships plus gifted ones (counted once, from
|
||||
/// the GIFT PURCHASE — see <see cref="Apply"/>).</summary>
|
||||
public int NewMembers { get; private set; }
|
||||
|
||||
public int MilestoneCount { get; private set; }
|
||||
|
||||
public IReadOnlyDictionary<string, double> MoneyByCurrency => _moneyByCurrency;
|
||||
|
||||
/// <summary>The session's dominant currency (most money) and its total, or ("", 0) when nothing
|
||||
/// has come in. Chosen by VALUE so a single EUR tip beside ten USD cents cannot flip the display
|
||||
/// to the smaller currency.</summary>
|
||||
public (string Currency, double Total) SessionTotal =>
|
||||
_moneyByCurrency.Count == 0
|
||||
? (string.Empty, 0)
|
||||
: _moneyByCurrency.OrderByDescending(pair => pair.Value).First() is var top
|
||||
? (top.Key, top.Value)
|
||||
: (string.Empty, 0);
|
||||
|
||||
public bool HasMixedCurrencies => _moneyByCurrency.Count > 1;
|
||||
|
||||
/// <summary>Folds one chat message into the tallies. Every event kind the poll decodes is
|
||||
/// handled; plain chat is ignored.
|
||||
///
|
||||
/// <para><b>giftMembershipReceivedEvent deliberately does nothing.</b> It is the RECIPIENT's view
|
||||
/// of a purchase already counted by membershipGiftingEvent, so counting it would double both the
|
||||
/// members and the money (creator ruling 2026-10-30: "come on").</para></summary>
|
||||
public void Apply(ChatMessage message)
|
||||
{
|
||||
switch (message.Kind)
|
||||
{
|
||||
case ChatEventKind.NewMember:
|
||||
NewMembers++;
|
||||
LastMemberName = message.AuthorName;
|
||||
break;
|
||||
|
||||
case ChatEventKind.MemberGift:
|
||||
// The purchase: one event carrying how many memberships were bought.
|
||||
var count = Math.Max(1, message.GiftNewMembersCount);
|
||||
NewMembers += count;
|
||||
LastGiftCount = count;
|
||||
LastGifterName = message.AuthorName;
|
||||
break;
|
||||
|
||||
case ChatEventKind.GiftReceived:
|
||||
break; // recipient side of the event above — never counted
|
||||
|
||||
case ChatEventKind.MemberMilestone:
|
||||
MilestoneCount++;
|
||||
break;
|
||||
|
||||
case ChatEventKind.SuperChat:
|
||||
case ChatEventKind.SuperSticker:
|
||||
LastSuperChatAuthor = message.AuthorName;
|
||||
LastSuperChatAmount = message.SuperChatAmount;
|
||||
LastSuperChatCurrency = string.IsNullOrWhiteSpace(message.SuperChatCurrency)
|
||||
? "USD"
|
||||
: message.SuperChatCurrency!;
|
||||
LastSuperChatDisplay = message.SuperChatDisplayString
|
||||
?? FormatMoney(LastSuperChatAmount, LastSuperChatCurrency);
|
||||
if (message.SuperChatAmount > 0)
|
||||
{
|
||||
_moneyByCurrency.TryGetValue(LastSuperChatCurrency!, out var running);
|
||||
_moneyByCurrency[LastSuperChatCurrency!] = running + message.SuperChatAmount;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new session starts from zero.</summary>
|
||||
public void Reset() => CopyFrom(new ScoreboardState());
|
||||
|
||||
private void CopyFrom(ScoreboardState other)
|
||||
{
|
||||
_moneyByCurrency.Clear();
|
||||
foreach (var pair in other._moneyByCurrency) _moneyByCurrency[pair.Key] = pair.Value;
|
||||
LastMemberName = other.LastMemberName;
|
||||
LastSuperChatAuthor = other.LastSuperChatAuthor;
|
||||
LastSuperChatDisplay = other.LastSuperChatDisplay;
|
||||
LastSuperChatAmount = other.LastSuperChatAmount;
|
||||
LastSuperChatCurrency = other.LastSuperChatCurrency;
|
||||
LastGifterName = other.LastGifterName;
|
||||
LastGiftCount = other.LastGiftCount;
|
||||
NewMembers = other.NewMembers;
|
||||
MilestoneCount = other.MilestoneCount;
|
||||
}
|
||||
|
||||
private static string FormatMoney(double amount, string? currency) =>
|
||||
string.IsNullOrEmpty(currency) ? amount.ToString("0.00") : $"{currency} {amount:0.00}";
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace ytLive.Models;
|
||||
|
||||
/// <summary>Which of the eight facts the creator put on screen, and how each renders.
|
||||
///
|
||||
/// <para>Every tile is optional because the strip is an ego wall — the creator chooses the
|
||||
/// billboard. Goal tiles carry their targets here so the rendering stays a pure function of the
|
||||
/// state plus this selection.</para></summary>
|
||||
public sealed class ScoreboardTiles
|
||||
{
|
||||
/// <summary>Nothing enabled — the layer draws nothing.</summary>
|
||||
public static ScoreboardTiles None => new();
|
||||
|
||||
/// <summary>The selection a new layer starts with: the six session facts, no channel polls
|
||||
/// (those need the Analytics scope).</summary>
|
||||
public static ScoreboardTiles Default => new()
|
||||
{
|
||||
SuperChats = true, NewMembers = true, Milestones = true,
|
||||
LastMember = true, LastSuperChat = true, LastGift = true,
|
||||
};
|
||||
|
||||
public bool Subscribers { get; set; }
|
||||
public bool WatchHours { get; set; }
|
||||
public bool SuperChats { get; set; }
|
||||
public bool NewMembers { get; set; }
|
||||
public bool Milestones { get; set; }
|
||||
public bool LastMember { get; set; }
|
||||
public bool LastSuperChat { get; set; }
|
||||
public bool LastGift { get; set; }
|
||||
|
||||
/// <summary>Goal targets for the two polled tiles; 0 means "no goal, show the raw number".</summary>
|
||||
public int SubscriberGoal { get; set; }
|
||||
public int WatchHourGoal { get; set; }
|
||||
|
||||
/// <summary>Channel state fed by the polled side (subscribers, watch hours). Kept here so the
|
||||
/// strip is built from ONE source of truth: tallies + channel values + this selection.</summary>
|
||||
public int SubscriberCount { get; set; }
|
||||
public int WatchHoursValue { get; set; }
|
||||
|
||||
/// <summary>Cache key: the selection alone. Values are folded in by the presenter's fingerprint,
|
||||
/// so this only needs to change when the ENABLED SET changes.</summary>
|
||||
public string CacheKey =>
|
||||
$"{Subscribers}{WatchHours}{SuperChats}{NewMembers}{Milestones}{LastMember}{LastSuperChat}{LastGift}" +
|
||||
$"{SubscriberGoal}{WatchHourGoal}";
|
||||
|
||||
/// <summary>The strip's text, in reading order. Empty strings are dropped by the renderer.</summary>
|
||||
public IReadOnlyList<string> Build(ScoreboardState state)
|
||||
{
|
||||
var tiles = new List<string>(8);
|
||||
|
||||
if (Subscribers)
|
||||
tiles.Add(SubscriberGoal > 0
|
||||
? $"Subs {SubscriberCount:N0}/{SubscriberGoal:N0}"
|
||||
: $"Subs {SubscriberCount:N0}");
|
||||
|
||||
if (WatchHours)
|
||||
// Analytics is a DAILY aggregate, so the tile must not imply live data.
|
||||
tiles.Add(WatchHourGoal > 0
|
||||
? $"Hours {WatchHoursValue:N0}/{WatchHourGoal:N0} (as of {DateTime.Now:MMM d})"
|
||||
: $"Hours {WatchHoursValue:N0} (as of {DateTime.Now:MMM d})");
|
||||
|
||||
if (SuperChats && state.SessionTotal.Total > 0)
|
||||
tiles.Add(state.HasMixedCurrencies
|
||||
? $"SC {state.SessionTotal.Currency} {state.SessionTotal.Total:0.00} +{state.MoneyByCurrency.Count - 1}"
|
||||
: $"SC {state.SessionTotal.Currency} {state.SessionTotal.Total:0.00}");
|
||||
|
||||
if (NewMembers && state.NewMembers > 0)
|
||||
tiles.Add($"Members +{state.NewMembers}");
|
||||
|
||||
if (Milestones && state.MilestoneCount > 0)
|
||||
tiles.Add($"Milestones {state.MilestoneCount}");
|
||||
|
||||
if (LastMember && !string.IsNullOrWhiteSpace(state.LastMemberName))
|
||||
tiles.Add($"Last member {state.LastMemberName}");
|
||||
|
||||
if (LastSuperChat && !string.IsNullOrWhiteSpace(state.LastSuperChatDisplay))
|
||||
tiles.Add($"Last SC {state.LastSuperChatDisplay}");
|
||||
|
||||
if (LastGift && !string.IsNullOrWhiteSpace(state.LastGifterName))
|
||||
tiles.Add($"Last gift {state.LastGifterName} ×{Math.Max(1, state.LastGiftCount)}");
|
||||
|
||||
return tiles;
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -13,6 +13,8 @@ public enum SourceType
|
||||
Countdown,
|
||||
WebSource,
|
||||
ChatBox,
|
||||
/// <summary>The session scoreboard strip: full-width, state not events.</summary>
|
||||
Scoreboard,
|
||||
MediaSource,
|
||||
/// <summary>The designated alert zone: the six monetization events play their
|
||||
/// unique celebration animations here (OBS alert-box equivalent, native).</summary>
|
||||
@@ -74,6 +76,7 @@ public class Source : SceneElement
|
||||
Raise(nameof(DisplaySource));
|
||||
Raise(nameof(IsWebSource));
|
||||
Raise(nameof(IsTextOverlay));
|
||||
Raise(nameof(IsScoreboard));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +91,8 @@ public class Source : SceneElement
|
||||
public override bool IsWebSource => Type == SourceType.WebSource;
|
||||
public override bool IsTextOverlay => Type == SourceType.TextOverlay;
|
||||
|
||||
public override bool IsScoreboard => Type == SourceType.Scoreboard;
|
||||
|
||||
/// <summary>The permanent brand logo layer (one per scene, directly above the background).
|
||||
/// Locked against removal; its image comes from the App Settings brand logo.</summary>
|
||||
public bool IsBrandLogo { get; set; }
|
||||
@@ -138,9 +143,16 @@ public class Source : SceneElement
|
||||
|
||||
public ImageSource? ImageSource => _imageSource;
|
||||
|
||||
/// <summary>Types whose frame is produced at runtime rather than stored as an asset. The
|
||||
/// scoreboard joined this list 2026-10-30 — without it the strip was rendered, published to
|
||||
/// VideoImageSource, and never displayed (the same shape as the invisible-alert defect).</summary>
|
||||
private bool IsFrameSource =>
|
||||
Type is SourceType.ChatBox or SourceType.WebSource or SourceType.MediaSource
|
||||
or SourceType.AlertBox or SourceType.Scoreboard;
|
||||
|
||||
public override ImageSource? DisplaySource => IsLiveCapture
|
||||
? (VideoImageSource ?? _imageSource)
|
||||
: (Type is SourceType.ChatBox or SourceType.WebSource or SourceType.MediaSource or SourceType.AlertBox ? VideoImageSource : _imageSource);
|
||||
: (IsFrameSource ? VideoImageSource : _imageSource);
|
||||
|
||||
public override bool IsImageSource => Type == SourceType.Image;
|
||||
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
|
||||
## 2026-10-30 — C# record struct: `new T()` ignores the parameter defaults
|
||||
|
||||
**Symptom:** two property controls "had no code behind them" — the Background checkbox and the
|
||||
opacity slider changed nothing visible.
|
||||
|
||||
**Cause:** `public readonly record struct ScoreboardStyle(string TextColor = "#FFFFFF", bool BackgroundEnabled = true, …)`.
|
||||
`new ScoreboardStyle()` binds to the implicit **parameterless constructor**, which zero-initialises —
|
||||
the defaults in the parameter list are only used when the constructor is called with those arguments
|
||||
omitted *at a call site that supplies some of them*. Result: null colour, `BackgroundEnabled = false`,
|
||||
`FontOpacity = 0`, `FontSize = 0`. The renderer drew the zeros faithfully, so the UI looked dead
|
||||
while every unit test of the renderer passed (they constructed the style explicitly).
|
||||
|
||||
**Rule:** a record struct with meaningful defaults needs an explicit parameterless constructor
|
||||
(`public T() : this(<defaults>) { }`). And a "defaults" test must construct the type the same way
|
||||
production does — with `new()` — never with explicit arguments, or it proves nothing.
|
||||
|
||||
**Guard:** `ScoreboardRendererTests` asserts `new ScoreboardStyle()` yields white / on / black / 0.20 /
|
||||
max 200.
|
||||
|
||||
# MyMistakes.md
|
||||
|
||||
> **Two jobs**, distinguished by heading:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Collections.Generic;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Services.Compositor;
|
||||
|
||||
/// <summary>Turns the session's tallies into the strip frame, and keeps the raster until a displayed
|
||||
/// value actually moves.
|
||||
///
|
||||
/// <para>The cache is the point: a strip re-rasterised every tick would be the most expensive layer
|
||||
/// the compositor carries, for pixels that did not change. `ScoreboardRecorder.Changed` only fires
|
||||
/// on a visible change, so the presenter rebuilds only then.</para></summary>
|
||||
public sealed class ScoreboardPresenter
|
||||
{
|
||||
private readonly ScoreboardRecorder _recorder;
|
||||
private VideoFrame? _frame;
|
||||
private VideoFrame? _run; // the wide scrollable run (dev preview only)
|
||||
private double _offsetPx;
|
||||
private string? _tilesFingerprint;
|
||||
private ScoreboardStyle _style;
|
||||
private ScoreboardTiles _tiles = ScoreboardTiles.None;
|
||||
|
||||
public ScoreboardPresenter(ScoreboardRecorder recorder, ScoreboardStyle style)
|
||||
{
|
||||
_recorder = recorder;
|
||||
_style = style;
|
||||
_recorder.Changed += Invalidate;
|
||||
}
|
||||
|
||||
/// <summary>The strip TICKS (creator ruling 2026-10-30: "the point is, it's a ticker… so,
|
||||
/// tick"). True for the product, and the dev simulation uses the same path — so what the
|
||||
/// creator previews is what ships.</summary>
|
||||
public bool Scroll { get; set; } = true;
|
||||
|
||||
/// <summary>Marquee speed in pixels per second — the creator's dial (a read-speed choice, not a
|
||||
/// styling one).</summary>
|
||||
public double PixelsPerSecond { get; set; } = DefaultPixelsPerSecond;
|
||||
|
||||
public const double DefaultPixelsPerSecond = 120;
|
||||
public const double MinPixelsPerSecond = 20;
|
||||
public const double MaxPixelsPerSecond = 200; // creator cap: faster than this is unreadable
|
||||
|
||||
/// <summary>Advances the scroll by <paramref name="seconds"/>. The strip is a marquee: one
|
||||
/// measured run, cropped to a moving window, so a tick is a row-wise byte copy rather than a
|
||||
/// re-rasterisation.</summary>
|
||||
public void Advance(double seconds, double? pixelsPerSecond = null)
|
||||
{
|
||||
if (!Scroll) return;
|
||||
_offsetPx += seconds * (pixelsPerSecond ?? PixelsPerSecond);
|
||||
}
|
||||
|
||||
/// <summary>The strip frame for the current tallies, or null when nothing is enabled/shown.</summary>
|
||||
public VideoFrame? Frame
|
||||
{
|
||||
get
|
||||
{
|
||||
var tiles = _tiles.Build(_recorder.State);
|
||||
var fingerprint = $"{_tiles.CacheKey}|{string.Join('|', tiles)}|{_style}";
|
||||
|
||||
if (Scroll)
|
||||
{
|
||||
if (_run is null || fingerprint != _tilesFingerprint)
|
||||
{
|
||||
_tilesFingerprint = fingerprint;
|
||||
_run = ScoreboardRenderer.RenderRun(tiles, _style);
|
||||
}
|
||||
return _run is null ? null : ScoreboardRenderer.Crop(_run, (int)_offsetPx, ScoreboardRenderer.Width);
|
||||
}
|
||||
|
||||
if (_frame != null && fingerprint == _tilesFingerprint) return _frame;
|
||||
_tilesFingerprint = fingerprint;
|
||||
_frame = ScoreboardRenderer.Render(tiles, _style);
|
||||
return _frame;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetTiles(ScoreboardTiles tiles)
|
||||
{
|
||||
_tiles = tiles;
|
||||
Invalidate();
|
||||
}
|
||||
|
||||
public void SetStyle(ScoreboardStyle style)
|
||||
{
|
||||
_style = style;
|
||||
Invalidate();
|
||||
}
|
||||
|
||||
/// <summary>Drops the cached raster so the next read rebuilds it.</summary>
|
||||
public void Invalidate()
|
||||
{
|
||||
_frame = null;
|
||||
_run = null;
|
||||
_tilesFingerprint = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Services.Compositor;
|
||||
|
||||
/// <summary>How the scoreboard strip is painted. Same knobs as the social bar, because the creator
|
||||
/// asked for the same controls in the same place (2026-10-30).</summary>
|
||||
public readonly record struct ScoreboardStyle(
|
||||
string TextColor = "#FFFFFF",
|
||||
bool BackgroundEnabled = true,
|
||||
string BackgroundColor = "#000000",
|
||||
double BackgroundOpacity = 0.20,
|
||||
double FontSize = ScoreboardLayout.MaxFontSize,
|
||||
double SeparatorOpacity = 0.45)
|
||||
{
|
||||
/// <summary>A record STRUCT's implicit parameterless constructor zero-initialises — it does NOT
|
||||
/// run the parameter defaults. Without this, `new ScoreboardStyle()` produced null text colour,
|
||||
/// no background and zero opacity: every "default" in this file was a lie, and the plate/opacity
|
||||
/// controls looked dead because the renderer was faithfully drawing what it was given.</summary>
|
||||
public ScoreboardStyle() : this("#FFFFFF", true, "#000000", 0.20, ScoreboardLayout.MaxFontSize, 0.45)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rasterises the scoreboard strip (one line, shrinking/wrapping via
|
||||
/// <see cref="ScoreboardLayout.FitLine"/>) into a straight-alpha BGRA frame the compositor blits.
|
||||
///
|
||||
/// <para>Static by design: the strip holds state, not events — everything enabled is always
|
||||
/// visible, nothing waits its turn. It therefore rasterises only when a value changes, which is why
|
||||
/// the renderer takes plain strings and the caller keeps the cache.</para></summary>
|
||||
public static class ScoreboardRenderer
|
||||
{
|
||||
public const int Width = 1920;
|
||||
private const double PaddingX = 24;
|
||||
private const double PaddingY = 8;
|
||||
private const double SeparatorGap = 26;
|
||||
|
||||
/// <summary>Builds the SCROLLING run: the strip's line plus a gap, at its natural width, so the
|
||||
/// publisher can crop a 1920-wide window that moves. One raster per value change, never per
|
||||
/// tick — the tick is a row-wise byte copy.</summary>
|
||||
public static VideoFrame? RenderRun(IReadOnlyList<string>? tiles, ScoreboardStyle style, double gapPx = 240)
|
||||
{
|
||||
var texts = tiles?.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim()).ToList();
|
||||
if (texts is not { Count: > 0 }) return null;
|
||||
|
||||
var typeface = new Typeface(OutputPalette.Sans, FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal);
|
||||
var size = Math.Clamp(style.FontSize, ScoreboardLayout.FloorFontSize, ScoreboardLayout.MaxFontSize);
|
||||
var textBrush = Brush(style.TextColor, 1.0, Colors.White);
|
||||
var separator = Brush(style.TextColor, Math.Clamp(style.SeparatorOpacity, 0, 1), Colors.Gray);
|
||||
|
||||
var measured = texts.Select(t => Text(t, typeface, size, textBrush)).ToList();
|
||||
var lineWidth = measured.Sum(t => t.WidthIncludingTrailingWhitespace) + SeparatorGap * (texts.Count - 1);
|
||||
var height = (int)Math.Ceiling(size * 1.45 + PaddingY * 2);
|
||||
var width = (int)Math.Ceiling(lineWidth + gapPx);
|
||||
|
||||
var plate = Brush(style.BackgroundColor, Math.Clamp(style.BackgroundOpacity, 0, 1), Colors.Black);
|
||||
var visual = new DrawingVisual();
|
||||
using (var dc = visual.RenderOpen())
|
||||
{
|
||||
if (style.BackgroundEnabled)
|
||||
dc.DrawRectangle(plate, null, new Rect(0, 0, width, height));
|
||||
|
||||
var x = 0.0;
|
||||
for (var i = 0; i < measured.Count; i++)
|
||||
{
|
||||
dc.DrawText(measured[i], new Point(x, (height - size) / 2));
|
||||
x += measured[i].WidthIncludingTrailingWhitespace;
|
||||
if (i == measured.Count - 1) continue;
|
||||
var dot = Text("·", typeface, size, separator);
|
||||
dc.DrawText(dot, new Point(x + (SeparatorGap - dot.WidthIncludingTrailingWhitespace) / 2, (height - size) / 2));
|
||||
x += SeparatorGap;
|
||||
}
|
||||
}
|
||||
|
||||
return Rasterise(visual, width, height);
|
||||
}
|
||||
|
||||
/// <summary>Crops a <paramref name="width"/>-wide window out of the run at
|
||||
/// <paramref name="offsetPx"/>, wrapping. Straight-alpha rows, no scaling.</summary>
|
||||
public static VideoFrame Crop(VideoFrame run, int offsetPx, int width)
|
||||
{
|
||||
var height = run.Height;
|
||||
var pixels = new byte[width * height * 4];
|
||||
var runStride = run.Width * 4;
|
||||
var start = ((offsetPx % run.Width) + run.Width) % run.Width;
|
||||
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var srcRow = y * runStride;
|
||||
var dstRow = y * width * 4;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var sx = (start + x) % run.Width;
|
||||
var src = srcRow + sx * 4;
|
||||
var dst = dstRow + x * 4;
|
||||
pixels[dst] = run.BgraPixels[src];
|
||||
pixels[dst + 1] = run.BgraPixels[src + 1];
|
||||
pixels[dst + 2] = run.BgraPixels[src + 2];
|
||||
pixels[dst + 3] = run.BgraPixels[src + 3];
|
||||
}
|
||||
}
|
||||
return new VideoFrame(width, height, pixels);
|
||||
}
|
||||
|
||||
public static VideoFrame? Render(IReadOnlyList<string>? tiles, ScoreboardStyle style)
|
||||
{
|
||||
var texts = tiles?.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim()).ToList();
|
||||
if (texts is not { Count: > 0 }) return null;
|
||||
|
||||
var typeface = new Typeface(OutputPalette.Sans, FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal);
|
||||
var requested = Math.Clamp(style.FontSize, ScoreboardLayout.FloorFontSize, ScoreboardLayout.MaxFontSize);
|
||||
|
||||
double Measure(string text, double size) =>
|
||||
new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
|
||||
typeface, size, Brushes.White, pixelsPerDip: 1.0).WidthIncludingTrailingWhitespace;
|
||||
|
||||
var widths = texts.Select(t => Measure(t, requested)).ToList();
|
||||
var fit = ScoreboardLayout.FitLine(widths, SeparatorGap, Width - PaddingX * 2, requested);
|
||||
|
||||
// Re-measure at the fitted size so line breaking and drawing use the same numbers.
|
||||
var size = fit.FontSize;
|
||||
var lines = BuildLines(texts, texts.Select(t => Measure(t, size)).ToList(), Width - PaddingX * 2);
|
||||
var lineHeight = size * 1.45;
|
||||
var height = (int)Math.Ceiling(lines.Count * lineHeight + PaddingY * 2);
|
||||
|
||||
var textBrush = Brush(style.TextColor, 1.0, Colors.White);
|
||||
var plate = Brush(style.BackgroundColor, Math.Clamp(style.BackgroundOpacity, 0, 1), Colors.Black);
|
||||
var separator = Brush(style.TextColor, Math.Clamp(style.SeparatorOpacity, 0, 1), Colors.Gray);
|
||||
|
||||
var visual = new DrawingVisual();
|
||||
using (var dc = visual.RenderOpen())
|
||||
{
|
||||
if (style.BackgroundEnabled)
|
||||
dc.DrawRoundedRectangle(plate, null, new Rect(0, 0, Width, height), height / 2.0, height / 2.0);
|
||||
|
||||
for (var line = 0; line < lines.Count; line++)
|
||||
{
|
||||
var lineTiles = lines[line];
|
||||
var totalWidth = lineTiles.Sum(t => Measure(t, size)) + SeparatorGap * (lineTiles.Count - 1);
|
||||
var x = (Width - totalWidth) / 2;
|
||||
var y = PaddingY + line * lineHeight + (lineHeight - size) / 2;
|
||||
|
||||
for (var i = 0; i < lineTiles.Count; i++)
|
||||
{
|
||||
var text = Text(lineTiles[i], typeface, size, textBrush);
|
||||
dc.DrawText(text, new Point(x, y));
|
||||
x += text.WidthIncludingTrailingWhitespace;
|
||||
|
||||
if (i == lineTiles.Count - 1) continue;
|
||||
var dot = Text("·", typeface, size, separator);
|
||||
dc.DrawText(dot, new Point(x + (SeparatorGap - dot.WidthIncludingTrailingWhitespace) / 2, y));
|
||||
x += SeparatorGap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Rasterise(visual, Width, height);
|
||||
}
|
||||
|
||||
/// <summary>Draws the visual into a straight-alpha BGRA frame (unpremultiplied, because the
|
||||
/// compositor blends straight alpha).</summary>
|
||||
private static VideoFrame Rasterise(DrawingVisual visual, int width, int height)
|
||||
{
|
||||
var bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
|
||||
bitmap.Render(visual);
|
||||
|
||||
var pixels = new byte[width * height * 4];
|
||||
bitmap.CopyPixels(pixels, width * 4, 0);
|
||||
for (var i = 0; i < pixels.Length; i += 4)
|
||||
{
|
||||
var a = pixels[i + 3];
|
||||
if (a == 0 || a == 255) continue;
|
||||
pixels[i] = (byte)(pixels[i] * 255 / a);
|
||||
pixels[i + 1] = (byte)(pixels[i + 1] * 255 / a);
|
||||
pixels[i + 2] = (byte)(pixels[i + 2] * 255 / a);
|
||||
}
|
||||
return new VideoFrame(width, height, pixels);
|
||||
}
|
||||
|
||||
/// <summary>Greedy line packing at the fitted size — mirrors <see cref="ScoreboardLayout.FitLine"/>
|
||||
/// so the break points agree with the fit the caller was told about.</summary>
|
||||
private static List<List<string>> BuildLines(IReadOnlyList<string> tiles, IReadOnlyList<double> widths, double available)
|
||||
{
|
||||
var lines = new List<List<string>> { new() };
|
||||
var lineWidth = 0.0;
|
||||
for (var i = 0; i < tiles.Count; i++)
|
||||
{
|
||||
var w = widths[i];
|
||||
var needed = lineWidth == 0 ? w : lineWidth + SeparatorGap + w;
|
||||
if (needed > available && lineWidth > 0)
|
||||
{
|
||||
lines.Add(new List<string>());
|
||||
lineWidth = w;
|
||||
}
|
||||
else
|
||||
{
|
||||
lineWidth = needed;
|
||||
}
|
||||
lines[^1].Add(tiles[i]);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static FormattedText Text(string text, Typeface face, double size, Brush brush) =>
|
||||
new(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, face, size, brush, pixelsPerDip: 1.0);
|
||||
|
||||
private static SolidColorBrush Brush(string hex, double opacity, Color fallback)
|
||||
{
|
||||
Color colour;
|
||||
try { colour = (Color)ColorConverter.ConvertFromString(hex); }
|
||||
catch (Exception) { colour = fallback; }
|
||||
var brush = new SolidColorBrush(Color.FromArgb((byte)Math.Round(opacity * 255), colour.R, colour.G, colour.B));
|
||||
brush.Freeze();
|
||||
return brush;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using ytLive.Services.Compositor;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Services;
|
||||
@@ -51,6 +52,21 @@ public partial class LayoutStore : IDisposable
|
||||
|
||||
public void SaveMonoOutput(bool enabled) => UpsertSetting("Audio.MonoOutput", enabled ? "1" : "0");
|
||||
|
||||
/// <summary>Scoreboard master switch (creator 2026-10-30). Persisted because "off" also means
|
||||
/// "stop polling" — a switch that resets would quietly resume spending quota.</summary>
|
||||
public bool LoadScoreboardEnabled() => GetSetting("Scoreboard.Enabled") != "0";
|
||||
|
||||
public void SaveScoreboardEnabled(bool enabled) => UpsertSetting("Scoreboard.Enabled", enabled ? "1" : "0");
|
||||
|
||||
/// <summary>Scoreboard marquee speed (px/s), restored at startup.</summary>
|
||||
public int LoadScoreboardScrollSpeed()
|
||||
=> int.TryParse(GetSetting("Scoreboard.ScrollSpeed"), out var px)
|
||||
? Math.Clamp(px, (int)ScoreboardPresenter.MinPixelsPerSecond, (int)ScoreboardPresenter.MaxPixelsPerSecond)
|
||||
: (int)ScoreboardPresenter.DefaultPixelsPerSecond;
|
||||
|
||||
public void SaveScoreboardScrollSpeed(int pixelsPerSecond)
|
||||
=> UpsertSetting("Scoreboard.ScrollSpeed", pixelsPerSecond.ToString());
|
||||
|
||||
/// <summary>The user's chosen record output folder (TASK 18), or null to use the
|
||||
/// default <c>%APPDATA%\ytLlive\recordings</c>. Restored at startup.</summary>
|
||||
public string? LoadRecordFolder()
|
||||
|
||||
@@ -33,7 +33,37 @@ public class YouTubeAuthService
|
||||
/// No forced re-consent: a refresh token keeps the scopes it was originally granted, so an
|
||||
/// existing session is unaffected; the reduced set applies from the next fresh sign-in.</para>
|
||||
/// </summary>
|
||||
private const string Scope = "https://www.googleapis.com/auth/youtube";
|
||||
private const string Scope =
|
||||
"https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/yt-analytics.readonly";
|
||||
|
||||
/// <summary>Just the Analytics half, so callers can ask "did this session grant it?" without
|
||||
/// string-splitting the whole scope list.</summary>
|
||||
internal const string AnalyticsScope = "https://www.googleapis.com/auth/yt-analytics.readonly";
|
||||
|
||||
/// <summary>True when the stored session carries the Analytics grant. Tokens saved before the
|
||||
/// scope was added report false, which is what drives the one-click re-consent rather than a
|
||||
/// silent 403 in the middle of a stream.</summary>
|
||||
public bool HasAnalyticsScope => GrantedScopes.Contains(AnalyticsScope, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Scopes granted by the CURRENT session, as reported by Google on the token response.
|
||||
/// Empty for a session saved before scopes were recorded — treated as "unknown, assume missing".</summary>
|
||||
public IReadOnlyCollection<string> GrantedScopes => _grantedScopes;
|
||||
|
||||
private readonly List<string> _grantedScopes = new();
|
||||
|
||||
/// <summary>Records what Google says this token may do. A refresh response carries the granted
|
||||
/// scopes, so a session saved before Analytics was requested reports "not granted" until the
|
||||
/// user re-consents — which is precisely the signal the scoreboard needs.</summary>
|
||||
private void CaptureScopes(System.Text.Json.JsonElement tokenData)
|
||||
{
|
||||
_grantedScopes.Clear();
|
||||
if (!tokenData.TryGetProperty("scope", out var scope) || scope.ValueKind != System.Text.Json.JsonValueKind.String)
|
||||
return;
|
||||
var raw = scope.GetString();
|
||||
if (string.IsNullOrWhiteSpace(raw)) return;
|
||||
foreach (var part in raw.Split(' ', System.StringSplitOptions.RemoveEmptyEntries))
|
||||
_grantedScopes.Add(part);
|
||||
}
|
||||
|
||||
private readonly string _clientId;
|
||||
private readonly string _clientSecret;
|
||||
@@ -91,6 +121,7 @@ public class YouTubeAuthService
|
||||
("redirect_uri", redirectUri),
|
||||
("response_type", "code"),
|
||||
("scope", Scope),
|
||||
("include_granted_scopes", "true"),
|
||||
("access_type", "offline"),
|
||||
("prompt", "consent"),
|
||||
};
|
||||
@@ -193,6 +224,7 @@ public class YouTubeAuthService
|
||||
var tokenData = JsonSerializer.Deserialize<JsonElement>(json);
|
||||
|
||||
var accessToken = tokenData.GetProperty("access_token").GetString()!;
|
||||
CaptureScopes(tokenData);
|
||||
var refreshToken = tokenData.GetProperty("refresh_token").GetString()!;
|
||||
var expiresIn = tokenData.GetProperty("expires_in").GetInt32();
|
||||
|
||||
@@ -218,6 +250,7 @@ public class YouTubeAuthService
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var tokenData = JsonSerializer.Deserialize<JsonElement>(json);
|
||||
|
||||
CaptureScopes(tokenData);
|
||||
CurrentChannel.AccessToken = tokenData.GetProperty("access_token").GetString()!;
|
||||
CurrentChannel.TokenExpiry = DateTime.UtcNow.AddSeconds(tokenData.GetProperty("expires_in").GetInt32());
|
||||
_sessionChanged?.Invoke(CurrentChannel);
|
||||
|
||||
@@ -17,6 +17,7 @@ public partial class MainViewModel
|
||||
{
|
||||
if (SetProperty(ref _isConnected, value))
|
||||
{
|
||||
OnPropertyChanged(nameof(CanUseScoreboard));
|
||||
// ON-AIR requires a sign-in; dropping the session turns the pill
|
||||
// off so the state can never offer a stream without an account.
|
||||
if (!value) OnAirPillOn = false;
|
||||
|
||||
@@ -31,6 +31,7 @@ public partial class MainViewModel
|
||||
RaiseMasterReadouts();
|
||||
UpdateDuckState();
|
||||
CheckTraxSilence();
|
||||
TickScoreboard();
|
||||
}
|
||||
|
||||
/// <summary>One honest diagnostic: "playing" with a flat player meter means the samples never
|
||||
|
||||
@@ -439,6 +439,7 @@ public partial class MainViewModel
|
||||
}
|
||||
SeedOnAirImage();
|
||||
EnsureBrandLogos();
|
||||
EnsureScoreboards();
|
||||
OnPropertyChanged(nameof(ShowSourcesEmptyHint));
|
||||
OnPropertyChanged(nameof(LayerCount));
|
||||
}
|
||||
|
||||
@@ -50,6 +50,9 @@ public partial class MainViewModel : ViewModelBase
|
||||
{
|
||||
_chatLayer.OnMessageReceived(message, Scenes);
|
||||
_alertLayer.OnMessageReceived(message, Scenes);
|
||||
// Feed the session tallies LAST: the scoreboard counts what the poll decoded, and it only
|
||||
// counts while a session is running (ScoreboardRecorder ignores everything else).
|
||||
_scoreboard.Record(message);
|
||||
}
|
||||
|
||||
private void UpdateChatBoxPreview(Source chatBox, IReadOnlyList<ChatMessage>? messages = null)
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using ytLive.Helpers;
|
||||
using ytLive.Models;
|
||||
using ytLive.Services;
|
||||
using ytLive.Services.Compositor;
|
||||
|
||||
namespace ytLive.ViewModels;
|
||||
|
||||
/// <summary>The scoreboard strip: session tallies rendered as a full-width bar, per scene.
|
||||
///
|
||||
/// <para>It is a <see cref="SourceType.Scoreboard"/> layer, so a creator gets the same eye toggle,
|
||||
/// drag and per-scene presence as every other element — "prominent on BRB, dialled back on Live" is
|
||||
/// geometry, not a second mechanism.</para></summary>
|
||||
public partial class MainViewModel
|
||||
{
|
||||
private readonly ScoreboardRecorder _scoreboard = new();
|
||||
private ScoreboardTiles _scoreboardTiles = ScoreboardTiles.Default;
|
||||
private ScoreboardStyle _scoreboardStyle = new();
|
||||
private ScoreboardPresenter? _scoreboardPresenter;
|
||||
private WriteableBitmap? _scoreboardPreview;
|
||||
|
||||
/// <summary>Gap between the strip and the frame edge.</summary>
|
||||
private const double ScoreboardEdgeMargin = 8;
|
||||
|
||||
private BarEdge _scoreboardPreferredEdge = BarEdge.Bottom;
|
||||
|
||||
/// <summary>The edge the creator asked for. It is only a PREFERENCE: the resolver gives the
|
||||
/// scoreboard the edge the social bar does not hold (creator ruling, resolved at render time).</summary>
|
||||
public BarEdge ScoreboardEdge
|
||||
{
|
||||
get => _scoreboardPreferredEdge;
|
||||
set
|
||||
{
|
||||
if (!SetProperty(ref _scoreboardPreferredEdge, value)) return;
|
||||
RefreshScoreboardPreviews();
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<BarEdge> ScoreboardEdgeOptions { get; } = new[] { BarEdge.Top, BarEdge.Bottom };
|
||||
|
||||
/// <summary>How fast the ticker travels, in pixels per second. Persisted like the rest of the
|
||||
/// strip's look: it is a readability choice, and re-dialling it every launch would be a tax.</summary>
|
||||
public double ScoreboardScrollSpeed
|
||||
{
|
||||
get => _scoreboardPresenter?.PixelsPerSecond ?? ScoreboardPresenter.DefaultPixelsPerSecond;
|
||||
set
|
||||
{
|
||||
var clamped = Math.Clamp(value, ScoreboardPresenter.MinPixelsPerSecond, ScoreboardPresenter.MaxPixelsPerSecond);
|
||||
if (_scoreboardPresenter != null) _scoreboardPresenter.PixelsPerSecond = clamped;
|
||||
_layoutStore.SaveScoreboardScrollSpeed((int)Math.Round(clamped));
|
||||
OnPropertyChanged(nameof(ScoreboardScrollSpeed));
|
||||
}
|
||||
}
|
||||
private Source? _scoreboardPreviewSource;
|
||||
|
||||
internal ScoreboardRecorder ScoreboardRecorder => _scoreboard;
|
||||
|
||||
private bool _scoreboardEnabled = true;
|
||||
|
||||
/// <summary>The scoreboard's master switch. Off hides the strip in EVERY scene (the per-scene
|
||||
/// eye stays independent) and — the point of the switch — stops all polling: a scoreboard nobody
|
||||
/// can see must not spend quota.</summary>
|
||||
public bool ScoreboardEnabled
|
||||
{
|
||||
get => _scoreboardEnabled;
|
||||
set
|
||||
{
|
||||
if (!SetProperty(ref _scoreboardEnabled, value)) return;
|
||||
_layoutStore.SaveScoreboardEnabled(value);
|
||||
RefreshScoreboardPreviews();
|
||||
OnPropertyChanged(nameof(ScoreboardPollsEnabled));
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
private const bool DevelopmentBuild = true;
|
||||
#else
|
||||
private const bool DevelopmentBuild = false;
|
||||
#endif
|
||||
|
||||
/// <summary>Can the scoreboard be configured at all? Signed-in creators yes; in a DEBUG build
|
||||
/// always, so the strip can be previewed and judged before there is an account (creator,
|
||||
/// 2026-10-30).</summary>
|
||||
public bool CanUseScoreboard => IsConnected || IsDevelopmentBuild;
|
||||
|
||||
/// <summary>True in a DEBUG build. Used only to expose development-only controls, never to
|
||||
/// change behaviour — the shipped binary differs by their absence, not by a code path.</summary>
|
||||
public bool IsDevelopmentBuild => DevelopmentBuild;
|
||||
|
||||
private bool _scoreboardSimulate;
|
||||
|
||||
/// <summary>DEBUG-only: push a representative set of events so the strip is visible in the
|
||||
/// preview before any real stream. Off clears back to an empty session.</summary>
|
||||
public bool ScoreboardSimulate
|
||||
{
|
||||
get => _scoreboardSimulate;
|
||||
set
|
||||
{
|
||||
if (!SetProperty(ref _scoreboardSimulate, value)) return;
|
||||
if (value)
|
||||
{
|
||||
ScoreboardSample.Inject(_scoreboard);
|
||||
}
|
||||
else
|
||||
{
|
||||
_scoreboard.StartSession(); // empty session: "nothing yet"
|
||||
}
|
||||
RefreshScoreboardPreviews();
|
||||
OnPropertyChanged(nameof(ScoreboardFrame));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the cadence policy asks: the master switch AND at least one scene showing it.</summary>
|
||||
internal bool ScoreboardPollsEnabled =>
|
||||
!_scoreboardSimulate // dev data is made up: never poll for it
|
||||
&& _scoreboardEnabled && Scenes.Any(scene =>
|
||||
scene.Elements.OfType<Source>().Any(s => s.IsScoreboard && s.IsVisible && s.IsEnabled));
|
||||
|
||||
internal ScoreboardTiles ScoreboardTilesState => _scoreboardTiles;
|
||||
|
||||
/// <summary>Composited strip frame for the output path (cached by the presenter).</summary>
|
||||
internal VideoFrame? ScoreboardFrame => _scoreboardPresenter?.Frame;
|
||||
|
||||
internal void StartScoreboardSession()
|
||||
{
|
||||
_scoreboard.StartSession();
|
||||
RefreshScoreboardPreviews();
|
||||
}
|
||||
|
||||
internal void EndScoreboardSession()
|
||||
{
|
||||
_scoreboard.EndSession();
|
||||
RefreshScoreboardPreviews();
|
||||
}
|
||||
|
||||
/// <summary>One Scoreboard layer in every scene, healed on load — "available to all scenes"
|
||||
/// (creator ruling 2026-10-30). Per-scene visibility is the ordinary eye toggle.</summary>
|
||||
internal void EnsureScoreboards()
|
||||
{
|
||||
if (ScoreboardHealer.Ensure(Scenes))
|
||||
{
|
||||
foreach (var scene in Scenes) _sceneGraph.InvalidateBake(scene);
|
||||
RefreshScoreboardPreviews();
|
||||
OnPropertyChanged(nameof(LayerCount));
|
||||
}
|
||||
}
|
||||
|
||||
private void InitScoreboard()
|
||||
{
|
||||
_scoreboardPresenter = new ScoreboardPresenter(_scoreboard, _scoreboardStyle)
|
||||
{
|
||||
// placeholder so SetTiles below drives the first render
|
||||
};
|
||||
_scoreboardPresenter.SetTiles(_scoreboardTiles);
|
||||
_scoreboardPresenter.SetStyle(_scoreboardStyle);
|
||||
_scoreboard.Changed += RefreshScoreboardPreviews;
|
||||
}
|
||||
|
||||
/// <summary>Snapshot of the strip presenters as themed properties, for the properties panel
|
||||
/// (unit 7) — kept here so the panel binds one object instead of six primitives.</summary>
|
||||
internal ScoreboardStyle ScoreboardStyleState => _scoreboardStyle;
|
||||
|
||||
// ─── Properties panel surface (per layout: one scoreboard look) ────────────
|
||||
|
||||
public string ScoreboardTextColor
|
||||
{
|
||||
get => _scoreboardStyle.TextColor;
|
||||
set { _scoreboardStyle = _scoreboardStyle with { TextColor = value }; PushStyle(); }
|
||||
}
|
||||
|
||||
public bool ScoreboardBackgroundEnabled
|
||||
{
|
||||
get => _scoreboardStyle.BackgroundEnabled;
|
||||
set { _scoreboardStyle = _scoreboardStyle with { BackgroundEnabled = value }; PushStyle(); }
|
||||
}
|
||||
|
||||
public string ScoreboardBackgroundColor
|
||||
{
|
||||
get => _scoreboardStyle.BackgroundColor;
|
||||
set { _scoreboardStyle = _scoreboardStyle with { BackgroundColor = value }; PushStyle(); }
|
||||
}
|
||||
|
||||
public double ScoreboardBackgroundOpacity
|
||||
{
|
||||
get => _scoreboardStyle.BackgroundOpacity;
|
||||
set
|
||||
{
|
||||
_scoreboardStyle = _scoreboardStyle with { BackgroundOpacity = Math.Clamp(value, 0, 1) };
|
||||
PushStyle();
|
||||
// The readout binds THIS property: without its own raise the number never moves even
|
||||
// though the render does (creator: "bzzzt!").
|
||||
OnPropertyChanged(nameof(ScoreboardBackgroundOpacity));
|
||||
}
|
||||
}
|
||||
|
||||
public double ScoreboardFontSize
|
||||
{
|
||||
get => _scoreboardStyle.FontSize;
|
||||
set
|
||||
{
|
||||
_scoreboardStyle = _scoreboardStyle with
|
||||
{
|
||||
FontSize = Math.Clamp(value, ScoreboardLayout.FloorFontSize, ScoreboardLayout.MaxFontSize),
|
||||
};
|
||||
PushStyle();
|
||||
OnPropertyChanged(nameof(ScoreboardFontSize)); // same bug as the opacity readout
|
||||
OnPropertyChanged(nameof(ScoreboardFontSizeLabel));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"24 px" — the panel shows real pixels, not a bare slider number.</summary>
|
||||
public string ScoreboardFontSizeLabel => $"{_scoreboardStyle.FontSize:0} px";
|
||||
|
||||
/// <summary>The colours offered for text and plate: the app's one palette.</summary>
|
||||
public IReadOnlyList<NamedColor> ScoreboardColorOptions => BorderColorPalette.All;
|
||||
|
||||
public bool ScoreboardShowSubscribers { get => _scoreboardTiles.Subscribers; set => SetTile(t => t.Subscribers = value); }
|
||||
public bool ScoreboardShowWatchHours { get => _scoreboardTiles.WatchHours; set => SetTile(t => t.WatchHours = value); }
|
||||
public bool ScoreboardShowSuperChats { get => _scoreboardTiles.SuperChats; set => SetTile(t => t.SuperChats = value); }
|
||||
public bool ScoreboardShowNewMembers { get => _scoreboardTiles.NewMembers; set => SetTile(t => t.NewMembers = value); }
|
||||
public bool ScoreboardShowMilestones { get => _scoreboardTiles.Milestones; set => SetTile(t => t.Milestones = value); }
|
||||
public bool ScoreboardShowLastMember { get => _scoreboardTiles.LastMember; set => SetTile(t => t.LastMember = value); }
|
||||
public bool ScoreboardShowLastSuperChat { get => _scoreboardTiles.LastSuperChat; set => SetTile(t => t.LastSuperChat = value); }
|
||||
public bool ScoreboardShowLastGift { get => _scoreboardTiles.LastGift; set => SetTile(t => t.LastGift = value); }
|
||||
|
||||
private void SetTile(Action<ScoreboardTiles> change)
|
||||
{
|
||||
change(_scoreboardTiles);
|
||||
_scoreboardPresenter?.SetTiles(_scoreboardTiles);
|
||||
RefreshScoreboardPreviews();
|
||||
OnPropertyChanged(nameof(ScoreboardTilesState));
|
||||
}
|
||||
|
||||
private void PushStyle()
|
||||
{
|
||||
_scoreboardPresenter?.SetStyle(_scoreboardStyle);
|
||||
RefreshScoreboardPreviews();
|
||||
OnPropertyChanged(nameof(ScoreboardStyleState));
|
||||
}
|
||||
|
||||
/// <summary>One tick of the marquee: advance the window and republish. Runs only while the strip
|
||||
/// is actually shown, so an idle/hidden scoreboard costs nothing.</summary>
|
||||
private void TickScoreboard()
|
||||
{
|
||||
if (_scoreboardPresenter is null) return;
|
||||
if (!_scoreboardEnabled && !_scoreboardSimulate) return;
|
||||
_scoreboardPresenter.Advance(0.033);
|
||||
RefreshScoreboardPreviews();
|
||||
}
|
||||
|
||||
/// <summary>Publishes the strip to every scoreboard layer's preview element. The pump thread
|
||||
/// must never touch a WriteableBitmap, so this runs on the UI thread only.</summary>
|
||||
private void RefreshScoreboardPreviews()
|
||||
{
|
||||
// Dev simulation OVERRIDES the master switch (creator ruling): the whole point of the dev
|
||||
// toggle is to prove the strip without touching product settings.
|
||||
var frame = (_scoreboardEnabled || _scoreboardSimulate) ? _scoreboardPresenter?.Frame : null;
|
||||
foreach (var scene in Scenes)
|
||||
foreach (var source in scene.Elements.OfType<Source>().Where(s => s.IsScoreboard))
|
||||
{
|
||||
if (frame is null) { source.VideoImageSource = null; continue; }
|
||||
if (_scoreboardPreview is null || _scoreboardPreview.PixelWidth != frame.Width ||
|
||||
_scoreboardPreview.PixelHeight != frame.Height)
|
||||
{
|
||||
_scoreboardPreview = new WriteableBitmap(frame.Width, frame.Height, 96, 96, PixelFormats.Bgra32, null);
|
||||
}
|
||||
_scoreboardPreview.WritePixels(new System.Windows.Int32Rect(0, 0, frame.Width, frame.Height),
|
||||
frame.BgraPixels, frame.Width * 4, 0);
|
||||
source.VideoImageSource = _scoreboardPreview;
|
||||
|
||||
// The strip's box follows what was RENDERED (one or two lines), and its edge comes
|
||||
// from the SHARED rule: the social bar keeps its side, the scoreboard takes the other.
|
||||
var socialEdge = _socials?.BarPosition == SocialBarPosition.Top ? BarEdge.Top : BarEdge.Bottom;
|
||||
var (_, resolved) = ScoreboardLayout.ResolveEdges(
|
||||
socialVisible: SocialBarVisible, socialPreferred: socialEdge,
|
||||
scoreboardVisible: true, scoreboardPreferred: _scoreboardPreferredEdge);
|
||||
|
||||
source.Width = frame.Width;
|
||||
source.Height = frame.Height;
|
||||
source.Y = resolved == BarEdge.Top
|
||||
? ScoreboardEdgeMargin
|
||||
: 1080 - frame.Height - ScoreboardEdgeMargin;
|
||||
_scoreboardPreviewSource = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,6 +224,7 @@ public partial class MainViewModel
|
||||
private void NotifySocialsChanged()
|
||||
{
|
||||
RenderSocialBarFrame();
|
||||
RefreshScoreboardPreviews(); // the pair re-sorts when the social bar shows/hides
|
||||
OnPropertyChanged(nameof(SocialBarTextBrush));
|
||||
OnPropertyChanged(nameof(SocialBarBackgroundBrush));
|
||||
OnPropertyChanged(nameof(HasSocials));
|
||||
@@ -238,6 +239,8 @@ public partial class MainViewModel
|
||||
if (_socials == null || _socials.BarPosition == position) return;
|
||||
_socials.BarPosition = position;
|
||||
OnPropertyChanged(nameof(SocialBarTop));
|
||||
// Coupled pair: moving the social bar moves the scoreboard to the other edge.
|
||||
RefreshScoreboardPreviews();
|
||||
ScheduleSave();
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ public partial class MainViewModel
|
||||
SourceType.WebSource => "Web Resource",
|
||||
SourceType.ChatBox => "YouTube Chat",
|
||||
SourceType.AlertBox => "Stream Alerts",
|
||||
SourceType.Scoreboard => "Scoreboard",
|
||||
_ => "Layer",
|
||||
};
|
||||
|
||||
@@ -52,9 +53,12 @@ public partial class MainViewModel
|
||||
: NextSourceName(scene, baseName),
|
||||
Type = sourceType,
|
||||
X = sourceType == SourceType.ChatBox ? 1400 : sourceType == SourceType.AlertBox ? 620 : 0,
|
||||
Y = sourceType == SourceType.ChatBox ? 20 : sourceType == SourceType.AlertBox ? 430 : 0,
|
||||
Width = sourceType == SourceType.WebSource ? 640 : sourceType == SourceType.ChatBox ? 500 : sourceType == SourceType.AlertBox ? 680 : 0,
|
||||
Height = sourceType == SourceType.WebSource ? 480 : sourceType == SourceType.ChatBox ? 648 : sourceType == SourceType.AlertBox ? 200 : 0,
|
||||
// The scoreboard is a full-width bar: its Y comes from the edge it owns (resolved
|
||||
// against the social bar at render time), never from a drag.
|
||||
Y = sourceType == SourceType.Scoreboard ? 1024
|
||||
: sourceType == SourceType.ChatBox ? 20 : sourceType == SourceType.AlertBox ? 430 : 0,
|
||||
Width = sourceType == SourceType.WebSource ? 640 : sourceType == SourceType.ChatBox ? 500 : sourceType == SourceType.AlertBox ? 680 : sourceType == SourceType.Scoreboard ? 1920 : 0,
|
||||
Height = sourceType == SourceType.WebSource ? 480 : sourceType == SourceType.ChatBox ? 648 : sourceType == SourceType.AlertBox ? 200 : sourceType == SourceType.Scoreboard ? 56 : 0,
|
||||
};
|
||||
_sceneGraph.AddElement(scene, source);
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ public partial class MainViewModel : ViewModelBase
|
||||
if (IsLive || IsRecording) return;
|
||||
var streaming = OnAirPillOn;
|
||||
var recording = RecordPillOn;
|
||||
// The scoreboard's scope is the session: every start clears it (creator ruling 2026-10-30).
|
||||
StartScoreboardSession();
|
||||
|
||||
if (!streaming && !recording)
|
||||
{
|
||||
// Nothing armed = "record something" (local recording needs no account,
|
||||
|
||||
@@ -278,6 +278,9 @@ public partial class MainViewModel : ViewModelBase
|
||||
AudioSyncOffsetMs = _layoutStore.LoadAudioSyncOffsetMs();
|
||||
MonoOutput = _layoutStore.LoadMonoOutput(); // applied to the mixer by the setter
|
||||
_musicPlayer.UserGain = (float)Helpers.GainDb.FromDb(TraxDefaultDb); // background by default
|
||||
InitScoreboard();
|
||||
ScoreboardEnabled = _layoutStore.LoadScoreboardEnabled();
|
||||
ScoreboardScrollSpeed = _layoutStore.LoadScoreboardScrollSpeed();
|
||||
try
|
||||
{
|
||||
var s = _layoutStore.GetSetting("ZoomShape");
|
||||
@@ -595,6 +598,7 @@ public partial class MainViewModel : ViewModelBase
|
||||
WebcamSceneConfig webcam => _cameraManager.GetLatestFrame(DeviceKeyForWebcam(webcam.WebcamId), EffectKeyFor(webcam)),
|
||||
Source { IsLiveCapture: true, CaptureKey: not null } live => _screenCaptureManager.GetLatestFrame(live.CaptureKey),
|
||||
Source { Type: SourceType.ChatBox } chatBox => RenderChatBox(chatBox),
|
||||
Source { Type: SourceType.Scoreboard } => _scoreboardPresenter?.Frame,
|
||||
Source { Type: SourceType.AlertBox } alertBox => RenderAlertBox(alertBox),
|
||||
Source { Type: SourceType.WebSource } web => _webView2Manager?.GetLatestFrame(web.Id),
|
||||
Source { IsMediaSource: true, MediaPath: not null } media => _mediaManager.GetLatestFrame(media.MediaPath),
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using Xunit;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>Adding the Analytics scope means existing sessions lack it. The app must be able to TELL
|
||||
/// — an anonymous 403 mid-stream is the failure this guards against.</summary>
|
||||
public class AnalyticsScopeTests
|
||||
{
|
||||
[Fact]
|
||||
public void The_app_asks_for_analytics_and_can_tell_when_a_session_lacks_it()
|
||||
{
|
||||
var source = SourceAssert.Text("Services", "YouTubeAuthService.cs");
|
||||
|
||||
// Requested, incrementally (so an existing user sees only the new prompt).
|
||||
Assert.Contains("yt-analytics.readonly", source);
|
||||
Assert.Contains("include_granted_scopes", source);
|
||||
|
||||
// And the grant is inspected from the token response, not assumed.
|
||||
Assert.Contains("CaptureScopes", source);
|
||||
Assert.Contains("HasAnalyticsScope", source);
|
||||
|
||||
// A connection type that exposes the flag, so the scoreboard can offer the one-click path.
|
||||
Assert.NotNull(typeof(ytLive.Services.YouTubeAuthService).GetProperty("HasAnalyticsScope"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>The quiet-by-default rule: watch hours only during a live stream (Analytics is a daily
|
||||
/// figure and test/record sessions have no public audience), subscribers whenever the app is
|
||||
/// working, and silence when idle.</summary>
|
||||
public class ScoreboardCadenceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Analytics_polls_only_when_live_and_subscribers_poll_during_any_session()
|
||||
{
|
||||
var now = new DateTime(2026, 10, 30, 12, 0, 0, DateTimeKind.Utc);
|
||||
var old = now.AddHours(-2);
|
||||
|
||||
// Idle: silent, even if everything is stale.
|
||||
Assert.Equal(ScoreboardPoll.None, ScoreboardCadence.Due(SessionPhase.Idle, old, old, now));
|
||||
|
||||
// Live with stale figures: both.
|
||||
Assert.Equal(ScoreboardPoll.Both, ScoreboardCadence.Due(SessionPhase.Live, old, old, now));
|
||||
|
||||
// Test / recording: subscribers only — no public audience, so no analytics.
|
||||
Assert.Equal(ScoreboardPoll.SubscribersOnly, ScoreboardCadence.Due(SessionPhase.Test, old, old, now));
|
||||
Assert.Equal(ScoreboardPoll.SubscribersOnly, ScoreboardCadence.Due(SessionPhase.Recording, old, old, now));
|
||||
|
||||
// Fresh figures: nothing is due.
|
||||
Assert.Equal(ScoreboardPoll.None, ScoreboardCadence.Due(SessionPhase.Live, now, now, now));
|
||||
|
||||
// Analytics alone never polls (it is not a kind the poller knows).
|
||||
Assert.Equal(ScoreboardPoll.None,
|
||||
ScoreboardCadence.Due(SessionPhase.Live, old, now.AddSeconds(-10), now));
|
||||
|
||||
// The master switch beats every other rule: off means silent, whatever the session is.
|
||||
Assert.Equal(ScoreboardPoll.None, ScoreboardCadence.Due(SessionPhase.Live, old, old, now, enabled: false));
|
||||
Assert.Equal(ScoreboardPoll.None, ScoreboardCadence.Due(SessionPhase.Test, old, old, now, enabled: false));
|
||||
Assert.Equal(ScoreboardPoll.None, ScoreboardCadence.Due(SessionPhase.Recording, old, old, now, enabled: false));
|
||||
|
||||
// Subscribers alone mid-window.
|
||||
Assert.Equal(ScoreboardPoll.SubscribersOnly,
|
||||
ScoreboardCadence.Due(SessionPhase.Live, now, old, now));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>Creator ruling (2026-10-30): the Scoreboard layer — YT_ACTIVITY_TICKER — is AVAILABLE TO
|
||||
/// ALL SCENES. It therefore heals into every scene like the Background and Brand logo, and a scene
|
||||
/// can never end up with two of them.</summary>
|
||||
public class ScoreboardHealerTests
|
||||
{
|
||||
private static Scene SceneWith(string name)
|
||||
{
|
||||
var scene = new Scene { Name = name };
|
||||
scene.Elements.Add(new Source { Name = "Background", Type = SourceType.Background, IsBackground = true });
|
||||
scene.Elements.Add(new Source { Name = "Brand logo", Type = SourceType.Image, IsBrandLogo = true });
|
||||
return scene;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_scene_gets_exactly_one_scoreboard_below_the_background()
|
||||
{
|
||||
var scenes = new List<Scene>
|
||||
{
|
||||
SceneWith(SceneCatalog.Starting), SceneWith(SceneCatalog.Live), SceneWith(SceneCatalog.Brb),
|
||||
};
|
||||
|
||||
Assert.True(ScoreboardHealer.Ensure(scenes));
|
||||
foreach (var scene in scenes)
|
||||
{
|
||||
var boards = scene.Elements.OfType<Source>().Where(s => s.IsScoreboard).ToList();
|
||||
Assert.Single(boards);
|
||||
Assert.Equal("Scoreboard", boards[0].Name);
|
||||
Assert.Equal(0, boards[0].X);
|
||||
Assert.Equal(1920, boards[0].Width);
|
||||
Assert.Equal(ScoreboardHealer.StripHeight, boards[0].Height);
|
||||
// Topmost: a full-width strip over the scene, and the Brand logo keeps its documented
|
||||
// place directly above the background.
|
||||
Assert.Equal(scene.Elements.Count - 1, scene.Elements.IndexOf(boards[0]));
|
||||
Assert.Equal("Brand logo", scene.Elements[1].Name);
|
||||
}
|
||||
|
||||
// Idempotent: a second pass changes nothing (no duplicate strips, no churn).
|
||||
Assert.False(ScoreboardHealer.Ensure(scenes));
|
||||
foreach (var scene in scenes) Assert.Single(scene.Elements.OfType<Source>().Where(s => s.IsScoreboard));
|
||||
|
||||
// A scene that somehow has two is healed back to one.
|
||||
scenes[0].Elements.Add(new Source { Name = "Scoreboard2", Type = SourceType.Scoreboard });
|
||||
Assert.True(ScoreboardHealer.Ensure(scenes));
|
||||
Assert.Single(scenes[0].Elements.OfType<Source>().Where(s => s.IsScoreboard));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Linq;
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>The scoreboard is a LAYER, not a special widget: it must appear as a source type, carry
|
||||
/// the full-width strip geometry, be resolvable on the output path like a chat box, and hook the
|
||||
/// session lifecycle so its numbers are session-scoped.</summary>
|
||||
public class ScoreboardLayerTests
|
||||
{
|
||||
[Fact]
|
||||
public void The_scoreboard_is_a_real_source_with_strip_geometry_and_a_resolver()
|
||||
{
|
||||
Assert.Contains("Scoreboard", System.Enum.GetNames<SourceType>());
|
||||
|
||||
// Geometry: full width, a strip's height, bottom by default.
|
||||
var sources = SourceAssert.Text("ViewModels", "MainViewModel.Sources.cs");
|
||||
Assert.Contains("SourceType.Scoreboard ? 1920", sources);
|
||||
Assert.Contains("SourceType.Scoreboard ? 56", sources);
|
||||
Assert.Contains("SourceType.Scoreboard ? 1024", sources);
|
||||
|
||||
// The output resolver knows how to produce its frame (same shape as the chat box/alert box).
|
||||
var resolver = SourceAssert.Text("ViewModels", "MainViewModel.cs");
|
||||
Assert.Contains("Source { Type: SourceType.Scoreboard } => _scoreboardPresenter?.Frame", resolver);
|
||||
|
||||
// The PREVIEW must show the strip: its frame is a runtime frame-source and its Image needs
|
||||
// the visibility trigger. Missing either made every property change look inert (2026-10-30).
|
||||
var source = SourceAssert.Text("Models", "Source.cs");
|
||||
Assert.Contains("or SourceType.AlertBox or SourceType.Scoreboard", source);
|
||||
Assert.Contains("IsScoreboard", SourceAssert.Text("Controls", "PreviewPane.xaml"));
|
||||
|
||||
// Session lifecycle: every start clears the tallies.
|
||||
var ops = SourceAssert.Text("ViewModels", "MainViewModel.Streaming.Operations.cs");
|
||||
Assert.Contains("StartScoreboardSession();", ops);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>Two creator rulings live here: the strip and the social bar own OPPOSITE edges (coupled,
|
||||
/// resolved from what is visible), and a strip that does not fit shrinks to a legibility floor and
|
||||
/// then wraps — it never scrolls.</summary>
|
||||
public class ScoreboardLayoutTests
|
||||
{
|
||||
[Fact]
|
||||
public void Bars_never_share_an_edge_and_an_overlong_strip_shrinks_then_wraps()
|
||||
{
|
||||
// Both visible: opposite edges, whatever the scoreboard asked for.
|
||||
Assert.Equal((BarEdge.Top, BarEdge.Bottom),
|
||||
ScoreboardLayout.ResolveEdges(true, BarEdge.Top, true, BarEdge.Top));
|
||||
Assert.Equal((BarEdge.Bottom, BarEdge.Top),
|
||||
ScoreboardLayout.ResolveEdges(true, BarEdge.Bottom, true, BarEdge.Bottom));
|
||||
|
||||
// Social bar hidden: the scoreboard keeps its own preference.
|
||||
Assert.Equal((BarEdge.Top, BarEdge.Bottom),
|
||||
ScoreboardLayout.ResolveEdges(false, BarEdge.Top, true, BarEdge.Bottom));
|
||||
|
||||
// Scoreboard hidden: the social bar is free.
|
||||
Assert.Equal((BarEdge.Bottom, BarEdge.Top),
|
||||
ScoreboardLayout.ResolveEdges(true, BarEdge.Bottom, false, BarEdge.Top));
|
||||
|
||||
// Fits at full size.
|
||||
var fit = ScoreboardLayout.FitLine(new[] { 200.0, 200.0, 200.0 }, 40, 1920);
|
||||
Assert.Equal(ScoreboardLayout.MaxFontSize, fit.FontSize);
|
||||
Assert.Equal(1, fit.LineCount);
|
||||
Assert.False(fit.Shrunk);
|
||||
|
||||
// Too wide for full size, but a shrink keeps it on one line.
|
||||
fit = ScoreboardLayout.FitLine(new[] { 400.0, 400.0, 400.0 }, 40, 900);
|
||||
Assert.True(fit.FontSize < ScoreboardLayout.MaxFontSize);
|
||||
Assert.True(fit.FontSize >= ScoreboardLayout.FloorFontSize);
|
||||
Assert.Equal(1, fit.LineCount);
|
||||
Assert.True(fit.Shrunk);
|
||||
|
||||
// Far too wide even at the floor: two lines, never a scroll.
|
||||
fit = ScoreboardLayout.FitLine(new[] { 600.0, 600.0, 600.0, 600.0 }, 40, 700);
|
||||
Assert.Equal(ScoreboardLayout.FloorFontSize, fit.FontSize);
|
||||
Assert.True(fit.LineCount > 1);
|
||||
Assert.True(fit.Wrapped);
|
||||
|
||||
// Nothing enabled: no crash, no lines invented.
|
||||
Assert.Equal(1, ScoreboardLayout.FitLine(System.Array.Empty<double>(), 40, 1920).LineCount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
using ytLive.Services.Compositor;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>The strip's cache is a performance rule with teeth: it must rebuild when a displayed
|
||||
/// value moves and must NOT rebuild otherwise, or the compositor pays for a raster per tick into
|
||||
/// pixels that did not change.</summary>
|
||||
public class ScoreboardPresenterTests
|
||||
{
|
||||
private static ChatMessage Member(string name) => new() { Kind = ChatEventKind.NewMember, AuthorName = name };
|
||||
|
||||
[Fact]
|
||||
public void The_strip_rebuilds_only_when_a_displayed_value_moves()
|
||||
{
|
||||
System.Exception? failure = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var recorder = new ScoreboardRecorder();
|
||||
var tiles = new ScoreboardTiles
|
||||
{
|
||||
SuperChats = false, WatchHours = false, Subscribers = false,
|
||||
NewMembers = true, Milestones = false, LastMember = true,
|
||||
LastSuperChat = false, LastGift = false,
|
||||
};
|
||||
var presenter = new ScoreboardPresenter(recorder, new ScoreboardStyle());
|
||||
presenter.SetTiles(tiles);
|
||||
|
||||
// Before a session: nothing counted, nothing to draw.
|
||||
Assert.Null(presenter.Frame);
|
||||
|
||||
recorder.StartSession();
|
||||
recorder.Record(Member("First"));
|
||||
var first = presenter.Frame;
|
||||
Assert.NotNull(first);
|
||||
|
||||
// No tick, no change: the same pixels come back (the run is cached).
|
||||
Assert.Equal(first!.BgraPixels, presenter.Frame!.BgraPixels);
|
||||
|
||||
// A TICK moves the window: the pixels must differ.
|
||||
presenter.Advance(0.5);
|
||||
var ticked = presenter.Frame;
|
||||
Assert.NotNull(ticked);
|
||||
Assert.NotEqual(first.BgraPixels, ticked!.BgraPixels);
|
||||
|
||||
// SPEED is a real dial: the same elapsed time at twice the speed moves twice as far,
|
||||
// so the window lands somewhere else.
|
||||
var slow = new ScoreboardPresenter(recorder, new ScoreboardStyle()) { PixelsPerSecond = 60 };
|
||||
var fast = new ScoreboardPresenter(recorder, new ScoreboardStyle()) { PixelsPerSecond = 120 };
|
||||
slow.SetTiles(tiles);
|
||||
fast.SetTiles(tiles);
|
||||
slow.Advance(1.0);
|
||||
fast.Advance(1.0);
|
||||
Assert.NotEqual(slow.Frame!.BgraPixels, fast.Frame!.BgraPixels);
|
||||
|
||||
// A visible change re-rasterises the run.
|
||||
recorder.Record(Member("Second"));
|
||||
var second = presenter.Frame;
|
||||
Assert.NotNull(second);
|
||||
Assert.NotEqual(ticked.BgraPixels, second!.BgraPixels);
|
||||
|
||||
// A gift-recipient event changes nothing displayed: same window, same pixels.
|
||||
var beforeGift = presenter.Frame!.BgraPixels.ToArray();
|
||||
recorder.Record(new ChatMessage { Kind = ChatEventKind.GiftReceived, AuthorName = "Recipient" });
|
||||
Assert.Equal(beforeGift, presenter.Frame!.BgraPixels);
|
||||
|
||||
// Disabling every tile returns no frame, and the layer draws nothing.
|
||||
presenter.SetTiles(ScoreboardTiles.None);
|
||||
Assert.Null(presenter.Frame);
|
||||
}
|
||||
catch (System.Exception ex) { failure = ex; }
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
Assert.Null(failure);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Reflection;
|
||||
using Xunit;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>The scoreboard's look and its eight fact switches live in the LAYER PROPERTIES, and the
|
||||
/// panel must use the app's widgets — a hand-painted control is the TASK 58/63 defect, and the
|
||||
/// guard that catches it is here because the type-based sweep cannot see a bespoke picker.</summary>
|
||||
public class ScoreboardPropertiesTests
|
||||
{
|
||||
[Fact]
|
||||
public void The_scoreboard_properties_are_themed_controls_bound_to_the_layer_surface()
|
||||
{
|
||||
var panel = SourceAssert.Text("Controls", "LeftPanel.xaml");
|
||||
|
||||
// Gated on the selected layer being a scoreboard.
|
||||
Assert.Contains("SelectedElement.IsScoreboard", panel);
|
||||
|
||||
// Signed out: the block is inert with a one-line explanation — EXCEPT in a DEBUG build, where
|
||||
// CanUseScoreboard is true so the strip can be previewed without an account.
|
||||
var block = panel[panel.IndexOf("Scoreboard config", System.StringComparison.Ordinal)..];
|
||||
block = block[..block.IndexOf("<!-- Countdown config -->", System.StringComparison.Ordinal)];
|
||||
Assert.Contains("IsEnabled=\"{Binding CanUseScoreboard}\"", block);
|
||||
Assert.Contains("Sign in to YouTube to use the scoreboard.", block);
|
||||
Assert.Contains("CanUseScoreboard, Converter={StaticResource InverseBoolToVis}", block);
|
||||
|
||||
// Defaults the creator asked for, and readouts that actually move.
|
||||
Assert.Contains("Background", block);
|
||||
Assert.DoesNotContain("Background plate", block);
|
||||
Assert.Contains("ScoreboardFontSizeLabel", block); // "24 px", not a bare number
|
||||
|
||||
var vm = SourceAssert.Text("ViewModels", "MainViewModel.Scoreboard.cs");
|
||||
Assert.Contains("OnPropertyChanged(nameof(ScoreboardBackgroundOpacity));", vm);
|
||||
Assert.Contains("OnPropertyChanged(nameof(ScoreboardFontSize));", vm);
|
||||
|
||||
// Dev-only labels are ORANGE, so a development affordance cannot pass for product.
|
||||
Assert.Contains("Simulate (dev)", block);
|
||||
Assert.Contains("Brush.Attention", block);
|
||||
|
||||
// Scroll speed: a real dial, persisted, with its range owned by the presenter.
|
||||
Assert.Contains("ScoreboardScrollSpeed", block);
|
||||
Assert.Contains("Minimum=\"20\" Maximum=\"200\"", block);
|
||||
Assert.Contains("Scoreboard.ScrollSpeed", SourceAssert.Text("Services", "LayoutStore.Settings.cs"));
|
||||
|
||||
// The master switch sits in the same panel: off hides the strip and stops the polling.
|
||||
Assert.Contains("ScoreboardEnabled", panel);
|
||||
|
||||
// The eight fact switches.
|
||||
foreach (var binding in new[]
|
||||
{
|
||||
"ScoreboardShowSubscribers", "ScoreboardShowWatchHours", "ScoreboardShowSuperChats",
|
||||
"ScoreboardShowNewMembers", "ScoreboardShowMilestones", "ScoreboardShowLastMember",
|
||||
"ScoreboardShowLastSuperChat", "ScoreboardShowLastGift",
|
||||
})
|
||||
Assert.Contains(binding, panel);
|
||||
|
||||
// Look controls: text colour, plate colour, plate opacity, text size.
|
||||
foreach (var binding in new[]
|
||||
{
|
||||
"ScoreboardTextColor", "ScoreboardBackgroundColor",
|
||||
"ScoreboardBackgroundOpacity", "ScoreboardFontSize",
|
||||
})
|
||||
Assert.Contains(binding, panel);
|
||||
|
||||
// Theme widgets only: the colour pickers are the app's drop-down (YtComboBox), never a
|
||||
// hand-built menu, and the toggles are YtCheckBox.
|
||||
Assert.Contains("Style=\"{StaticResource YtComboBox}\"", block);
|
||||
Assert.Contains("Style=\"{StaticResource YtCheckBox}\"", block);
|
||||
Assert.DoesNotContain("ContextMenu", block);
|
||||
|
||||
// The VM surface exists for every binding above (a typo would bind to nothing silently).
|
||||
var type = typeof(MainViewModel);
|
||||
foreach (var name in new[]
|
||||
{
|
||||
"ScoreboardTextColor", "ScoreboardBackgroundColor", "ScoreboardBackgroundOpacity",
|
||||
"ScoreboardFontSize", "ScoreboardColorOptions", "ScoreboardShowSubscribers",
|
||||
"ScoreboardEnabled", "CanUseScoreboard", "ScoreboardScrollSpeed",
|
||||
})
|
||||
Assert.NotNull(type.GetProperty(name));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>The session is the only scope the scoreboard promises, so the rules are: a start clears
|
||||
/// everything, events outside a session are ignored, and an ended session keeps its numbers but
|
||||
/// stops moving.</summary>
|
||||
public class ScoreboardRecorderTests
|
||||
{
|
||||
private static ChatMessage Member(string name) => new() { Kind = ChatEventKind.NewMember, AuthorName = name };
|
||||
|
||||
[Fact]
|
||||
public void Starting_a_session_clears_the_tallies_and_only_a_live_session_counts()
|
||||
{
|
||||
var recorder = new ScoreboardRecorder();
|
||||
var changes = 0;
|
||||
recorder.Changed += () => changes++;
|
||||
|
||||
// Outside a session: nothing is counted (no stale carry-over from the last stream).
|
||||
recorder.Record(Member("Ignored"));
|
||||
Assert.Equal(0, recorder.State.NewMembers);
|
||||
|
||||
recorder.StartSession();
|
||||
Assert.True(recorder.IsRunning);
|
||||
recorder.Record(Member("First"));
|
||||
recorder.Record(Member("Second"));
|
||||
Assert.Equal(2, recorder.State.NewMembers);
|
||||
Assert.True(changes >= 2, "each visible change must raise Changed so the strip re-renders");
|
||||
|
||||
// End freezes: numbers stay, movement stops.
|
||||
recorder.EndSession();
|
||||
Assert.False(recorder.IsRunning);
|
||||
recorder.Record(Member("AfterEnd"));
|
||||
Assert.Equal(2, recorder.State.NewMembers);
|
||||
|
||||
// The next session starts from zero.
|
||||
recorder.StartSession();
|
||||
Assert.Equal(0, recorder.State.NewMembers);
|
||||
Assert.Null(recorder.State.LastMemberName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Xunit;
|
||||
using ytLive.Services;
|
||||
using ytLive.Services.Compositor;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>The strip is state, not events: everything enabled is always on screen. These checks
|
||||
/// paint the real frame, because a renderer that silently draws nothing would still pass a
|
||||
/// structural test.</summary>
|
||||
public class ScoreboardRendererTests
|
||||
{
|
||||
private static readonly List<string> Tiles = new() { "Members 12", "Milestones 3", "SC $47.00" };
|
||||
|
||||
[Fact]
|
||||
public void The_strip_paints_the_plate_and_the_text_and_never_needs_a_scroll()
|
||||
{
|
||||
// The shipped defaults: white text, background ON, black, 20%.
|
||||
var defaults = new ScoreboardStyle();
|
||||
Assert.Equal("#FFFFFF", defaults.TextColor);
|
||||
Assert.True(defaults.BackgroundEnabled);
|
||||
Assert.Equal("#000000", defaults.BackgroundColor);
|
||||
Assert.Equal(0.20, defaults.BackgroundOpacity, 3);
|
||||
Assert.Equal(200, ytLive.Services.Compositor.ScoreboardPresenter.MaxPixelsPerSecond, 3);
|
||||
|
||||
Exception? failure = null;
|
||||
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// Plate on: half-transparent blue behind white text.
|
||||
var plated = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FFFFFF", true, "#0000FF", 0.5));
|
||||
Assert.NotNull(plated);
|
||||
Assert.Equal(ScoreboardRenderer.Width, plated!.Width);
|
||||
Assert.True(plated.Height > 0);
|
||||
|
||||
Assert.True(Count(plated, (r, g, b, a) => b > 150 && r < 60 && g < 60 && a is > 100 and < 170) > 500,
|
||||
"the plate must fill at the chosen colour and opacity");
|
||||
Assert.True(Count(plated, (r, g, b, a) => r > 200 && g > 200 && b > 200 && a > 200) > 20,
|
||||
"the text must be painted in the chosen colour");
|
||||
|
||||
// Plate off: the same area is transparent, the text survives.
|
||||
var bare = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FFFFFF", false, "#0000FF", 0.5));
|
||||
Assert.NotNull(bare);
|
||||
Assert.Equal(0, Count(bare!, (r, g, b, a) => b > 150 && r < 60 && g < 60 && a > 100));
|
||||
Assert.True(Count(bare!, (r, g, b, a) => r > 200 && g > 200 && b > 200 && a > 200) > 20);
|
||||
|
||||
// Text colour reaches the glyphs.
|
||||
var red = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FF0000", false, "#000000", 0.5));
|
||||
Assert.True(Count(red!, (r, g, b, a) => r > 180 && g < 80 && b < 80 && a > 200) > 20);
|
||||
|
||||
// The PLATE TOGGLE itself: same text, plate off vs on, different pixels. This is the
|
||||
// check that answers "the checkbox has no code behind it".
|
||||
var off = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FFFFFF", false, "#0000FF", 0.5));
|
||||
var on = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FFFFFF", true, "#0000FF", 0.5));
|
||||
Assert.True(Count(on!, (r, g, b, a) => b > 150 && r < 60 && g < 60 && a > 100)
|
||||
> Count(off!, (r, g, b, a) => b > 150 && r < 60 && g < 60 && a > 100) + 500,
|
||||
"turning the plate on must add plate pixels");
|
||||
|
||||
// Opacity: 20% and 80% must produce visibly different plate transparency.
|
||||
var faint = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FFFFFF", true, "#0000FF", 0.2));
|
||||
var solid = ScoreboardRenderer.Render(Tiles, new ScoreboardStyle("#FFFFFF", true, "#0000FF", 0.8));
|
||||
// Sample a plate-only pixel (5px in from the left edge, vertical middle): the text is
|
||||
// centred, so nothing anti-aliased can pollute the alpha reading.
|
||||
static int AlphaOf(VideoFrame f) => f.BgraPixels[((f.Height / 2) * f.Width + 5) * 4 + 3];
|
||||
Assert.InRange(AlphaOf(faint!), 35, 70); // ~20% of 255
|
||||
Assert.InRange(AlphaOf(solid!), 190, 220); // ~80% of 255
|
||||
Assert.True(AlphaOf(solid!) > AlphaOf(faint!) + 100, "the opacity slider must move the alpha");
|
||||
|
||||
// Nothing enabled: no frame at all (the layer draws nothing).
|
||||
Assert.Null(ScoreboardRenderer.Render(Array.Empty<string>(), new ScoreboardStyle()));
|
||||
}
|
||||
catch (Exception ex) { failure = ex; }
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
|
||||
Assert.Null(failure);
|
||||
}
|
||||
|
||||
private static int Count(VideoFrame frame, Func<int, int, int, int, bool> predicate)
|
||||
{
|
||||
var hits = 0;
|
||||
for (var i = 0; i < frame.BgraPixels.Length; i += 4)
|
||||
if (predicate(frame.BgraPixels[i + 2], frame.BgraPixels[i + 1], frame.BgraPixels[i], frame.BgraPixels[i + 3]))
|
||||
hits++;
|
||||
return hits;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
using ytLive.ViewModels;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>DEBUG-only affordance (creator 2026-10-30): push sample events so the strip is provable
|
||||
/// in the PREVIEW before a real stream. The sample must travel the real recorder, so what it paints
|
||||
/// is what live events paint — a fake renderer would prove nothing.</summary>
|
||||
public class ScoreboardSimulationTests
|
||||
{
|
||||
[Fact]
|
||||
public void The_dev_sample_feeds_the_real_recorder_and_the_toggle_is_debug_only()
|
||||
{
|
||||
// The sample goes through the recorder a stream uses, and lands all four tallies.
|
||||
var recorder = new ScoreboardRecorder();
|
||||
ScoreboardSample.Inject(recorder);
|
||||
|
||||
Assert.True(recorder.IsRunning);
|
||||
var state = recorder.State;
|
||||
Assert.Equal(4, state.NewMembers); // 1 paid + a gift of 3
|
||||
Assert.Equal(3, state.LastGiftCount);
|
||||
Assert.Equal("giftgiver", state.LastGifterName);
|
||||
Assert.Equal(1, state.MilestoneCount);
|
||||
Assert.Equal(12.34, state.SessionTotal.Total, 2);
|
||||
Assert.Equal("$12.34", state.LastSuperChatDisplay);
|
||||
|
||||
// A toggle OFF clears back to an empty session (so the empty state is visible too).
|
||||
recorder.StartSession();
|
||||
Assert.Equal(0, recorder.State.NewMembers);
|
||||
|
||||
// Simulate OVERRIDES the master "show" switch: the dev toggle must work even when the
|
||||
// product setting is off.
|
||||
var vmSource = SourceAssert.Text("ViewModels", "MainViewModel.Scoreboard.cs");
|
||||
Assert.Contains("_scoreboardEnabled || _scoreboardSimulate", vmSource);
|
||||
|
||||
// The control exists and is gated on the build, not on a runtime flag.
|
||||
var panel = SourceAssert.Text("Controls", "LeftPanel.xaml");
|
||||
Assert.Contains("ScoreboardSimulate", panel);
|
||||
Assert.Contains("IsDevelopmentBuild", panel);
|
||||
|
||||
var type = typeof(MainViewModel);
|
||||
Assert.NotNull(type.GetProperty("ScoreboardSimulate"));
|
||||
Assert.NotNull(type.GetProperty("IsDevelopmentBuild"));
|
||||
// DEBUG-gated at compile time, so a Release build has no dev control at all.
|
||||
Assert.Contains("#if DEBUG", vmSource);
|
||||
Assert.Contains("private const bool DevelopmentBuild = true;", vmSource);
|
||||
Assert.Contains("private const bool DevelopmentBuild = false;", vmSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Xunit;
|
||||
using ytLive.Models;
|
||||
|
||||
namespace ytLive.Tests;
|
||||
|
||||
/// <summary>Session-scoped scoreboard tallies. The rules that matter: money is never added across
|
||||
/// currencies, and a gifted membership is counted ONCE (from the purchase), never again from the
|
||||
/// recipient's event — that double-count is the easy mistake, and the creator called it out.</summary>
|
||||
public class ScoreboardStateTests
|
||||
{
|
||||
private static ChatMessage Message(ChatEventKind kind, string author = "viewer", double amount = 0,
|
||||
string? currency = "USD", int giftCount = 0, string? display = null) => new()
|
||||
{
|
||||
Kind = kind, AuthorName = author, SuperChatAmount = amount,
|
||||
SuperChatCurrency = currency, GiftNewMembersCount = giftCount, SuperChatDisplayString = display,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Tallies_follow_the_six_events_and_never_double_count_a_gift()
|
||||
{
|
||||
var state = new ScoreboardState();
|
||||
|
||||
state.Apply(Message(ChatEventKind.NewMember, "Paid"));
|
||||
Assert.Equal(1, state.NewMembers);
|
||||
Assert.Equal("Paid", state.LastMemberName);
|
||||
|
||||
// A gift purchase of 5 memberships counts 5...
|
||||
state.Apply(Message(ChatEventKind.MemberGift, "Gifter", giftCount: 5));
|
||||
Assert.Equal(6, state.NewMembers);
|
||||
Assert.Equal(5, state.LastGiftCount);
|
||||
Assert.Equal("Gifter", state.LastGifterName);
|
||||
|
||||
// ...and the recipients' own events add NOTHING (they are the same memberships).
|
||||
for (var i = 0; i < 5; i++) state.Apply(Message(ChatEventKind.GiftReceived, $"Recipient{i}", giftCount: 1));
|
||||
Assert.Equal(6, state.NewMembers);
|
||||
Assert.Equal(5, state.LastGiftCount);
|
||||
Assert.Equal("Gifter", state.LastGifterName);
|
||||
|
||||
state.Apply(Message(ChatEventKind.MemberMilestone, "Longtimer"));
|
||||
Assert.Equal(1, state.MilestoneCount);
|
||||
|
||||
// Super Chat and Super Sticker both carry money; the last one drives the "latest" tile.
|
||||
state.Apply(Message(ChatEventKind.SuperChat, "Tipper", 10, "USD", display: "$10.00"));
|
||||
state.Apply(Message(ChatEventKind.SuperSticker, "Sticker", 5, "USD"));
|
||||
Assert.Equal(15, state.SessionTotal.Total, 3);
|
||||
Assert.Equal("USD", state.SessionTotal.Currency);
|
||||
Assert.Equal("Sticker", state.LastSuperChatAuthor);
|
||||
Assert.False(state.HasMixedCurrencies);
|
||||
|
||||
// A second currency is tracked separately, never summed into the first.
|
||||
state.Apply(Message(ChatEventKind.SuperChat, "Euro", 3, "EUR"));
|
||||
Assert.Equal(15, state.MoneyByCurrency["USD"], 3);
|
||||
Assert.Equal(3, state.MoneyByCurrency["EUR"], 3);
|
||||
Assert.True(state.HasMixedCurrencies);
|
||||
Assert.Equal("USD", state.SessionTotal.Currency); // dominant by value, not by recency
|
||||
|
||||
// Plain chat is ignored entirely.
|
||||
state.Apply(Message(ChatEventKind.None, "Chatter"));
|
||||
Assert.Equal(6, state.NewMembers);
|
||||
Assert.Equal(1, state.MilestoneCount);
|
||||
|
||||
// A new session starts clean.
|
||||
state.Reset();
|
||||
Assert.Equal(0, state.NewMembers);
|
||||
Assert.Equal(0, state.SessionTotal.Total);
|
||||
Assert.Null(state.LastMemberName);
|
||||
}
|
||||
}
|
||||
@@ -138,10 +138,17 @@ public class YouTubeAuthServiceTests
|
||||
/// documenting the guarantee gets deleted instead of obeyed.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ExactlyOneScopeIsRequested_AndItIsTheBroadOne()
|
||||
public void TwoScopesAreRequested_TheBroadYouTubeOneAndReadOnlyAnalytics()
|
||||
{
|
||||
// Updated 2026-10-30: the scoreboard's two polled tiles need watch-time analytics, so the
|
||||
// app asks for exactly one more scope. The DECISION worth locking is still "no redundant
|
||||
// scopes": force-ssl stays gone, and analytics is read-only.
|
||||
Assert.Equal(
|
||||
new[] { "https://www.googleapis.com/auth/youtube" },
|
||||
new[]
|
||||
{
|
||||
"https://www.googleapis.com/auth/youtube",
|
||||
"https://www.googleapis.com/auth/yt-analytics.readonly",
|
||||
},
|
||||
SourceAssert.Scopes("Scope", "Services", "YouTubeAuthService.cs"));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user