Merge branch 'j.lechner/schedule-view' into 'main'

feat: add schedule and now-playing page

Closes #10

See merge request julian/blockwoche3.1-radiosender!10
This commit is contained in:
Julian Lechner committed 2026-11-23 10:02:09 +00:00
commit ce0bc03ef7
6 files changed
+533

No files matched your search

+11
View File
@@ -1,4 +1,5 @@
using System.Windows;
using Radiosender.Controllers;
using Radiosender.Services;
namespace Radiosender;
@@ -7,10 +8,20 @@ public partial class App : Application
{
public static SongRepository Songs { get; private set; } = null!;
/// <summary>App-wide, so a running broadcast keeps going while the user switches pages.</summary>
public static ScheduleController Schedule { get; private set; } = null!;
protected override void OnStartup(StartupEventArgs e)
{
// Creates the database file and table on first start.
Songs = new SongRepository(SongRepository.DefaultDatabasePath);
Schedule = new ScheduleController(Songs, new ScheduleGenerator(), new PlaybackEngine(), () => DateTime.Now);
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
Schedule.Stop();
base.OnExit(e);
}
}
@@ -0,0 +1,84 @@
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Controllers;
/// <summary>
/// Creates the broadcast plan and drives its playback. One instance lives for the whole app
/// (<see cref="App.Schedule"/>), so the plan survives page navigation.
/// </summary>
/// <remarks>Events come from the playback engine's thread pool; views marshal with <c>Dispatcher.BeginInvoke</c>.</remarks>
public class ScheduleController
{
public const int MaxHours = 24;
private readonly SongRepository _songs;
private readonly ScheduleGenerator _generator;
private readonly PlaybackEngine _engine;
private readonly Func<DateTime> _now;
private DateTime _itemStartedAt;
public ScheduleController(SongRepository songs, ScheduleGenerator generator, PlaybackEngine engine, Func<DateTime> now)
{
_songs = songs;
_generator = generator;
_engine = engine;
_now = now;
_engine.ItemStarted += (_, e) =>
{
_itemStartedAt = _now();
ItemStarted?.Invoke(this, e.Index);
};
_engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"Skipped \"{e.Item.Title}\": {e.Error.Message}");
_engine.Finished += (_, _) => Finished?.Invoke(this, EventArgs.Empty);
}
public event EventHandler<int>? ItemStarted;
public event EventHandler<string>? ItemFailed;
public event EventHandler? Finished;
public IReadOnlyList<ScheduleItem> Plan { get; private set; } = [];
public bool IsPlaying => _engine.IsRunning;
public int CurrentIndex => _engine.CurrentIndex;
/// <summary>The item on air, or <c>null</c> when nothing plays.</summary>
public ScheduleItem? CurrentItem => CurrentIndex is var i && i >= 0 && i < _engine.Items.Count ? _engine.Items[i] : null;
/// <summary>Time since the current item started, capped at its duration.</summary>
public TimeSpan CurrentElapsed => CurrentItem is { } item
? TimeSpan.FromTicks(Math.Clamp((_now() - _itemStartedAt).Ticks, 0, item.Duration.Ticks))
: TimeSpan.Zero;
/// <summary>Playback volume from 0 to 1.</summary>
public float Volume
{
get => MusicPlayer.Instance.Volume;
set => MusicPlayer.Instance.Volume = value;
}
/// <summary>Plans <paramref name="hours"/> full hours from the next full hour with the songs in the library.</summary>
/// <exception cref="ScheduleException">The library cannot fill the plan.</exception>
public IReadOnlyList<ScheduleItem> CreatePlan(int hours)
{
ArgumentOutOfRangeException.ThrowIfLessThan(hours, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(hours, MaxHours);
var now = _now();
var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1);
Stop();
Plan = _generator.Generate(nextHour, hours, _songs.GetAll());
return Plan;
}
/// <summary>Plays the plan from its first item; the planned times are the on-air clock, playback starts right away.</summary>
public void Start()
{
if (Plan.Count == 0)
throw new InvalidOperationException("Create a schedule first.");
_engine.Start(Plan);
}
public void Stop() => _engine.Stop();
}
+3
View File
@@ -22,6 +22,9 @@
<ui:NavigationViewItem Content="Home"
Icon="{ui:SymbolIcon Home24}"
TargetPageType="{x:Type pages:HomePage}" />
<ui:NavigationViewItem Content="Schedule"
Icon="{ui:SymbolIcon CalendarLtr24}"
TargetPageType="{x:Type pages:SchedulePage}" />
<ui:NavigationViewItem Content="Library"
Icon="{ui:SymbolIcon MusicNote224}"
TargetPageType="{x:Type pages:LibraryPage}" />
@@ -0,0 +1,169 @@
<Page x:Class="Radiosender.Views.Pages.SchedulePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="Schedule"
Loaded="OnLoaded"
Unloaded="OnUnloaded">
<Page.Resources>
<!-- Type label for the timeline: text names the type, the border color repeats it.
Songs stay neutral; the accent color can match the news red. -->
<DataTemplate x:Key="KindChip">
<Border x:Name="Chip"
Padding="8,1"
HorizontalAlignment="Left"
BorderThickness="1"
CornerRadius="4"
BorderBrush="{DynamicResource TextFillColorTertiaryBrush}">
<TextBlock x:Name="ChipText" Text="{Binding Kind}" FontSize="12" />
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Kind}" Value="News">
<Setter TargetName="Chip" Property="BorderBrush" Value="{DynamicResource SystemFillColorCriticalBrush}" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Ad">
<Setter TargetName="Chip" Property="BorderBrush" Value="{DynamicResource SystemFillColorCautionBrush}" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Moderator">
<Setter TargetName="Chip" Property="BorderBrush" Value="{DynamicResource SystemFillColorSuccessBrush}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Page.Resources>
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Schedule" />
<StackPanel Grid.Row="1" Margin="0,16,0,0" Orientation="Horizontal">
<ui:TextBlock VerticalAlignment="Center" Text="Hours" />
<ui:NumberBox x:Name="HoursBox"
Width="140"
Margin="12,0,0,0"
AutomationProperties.Name="Hours to plan"
Minimum="1"
Maximum="24"
Value="1"
SmallChange="1"
MaxDecimalPlaces="0"
ClearButtonEnabled="False" />
<ui:Button Margin="12,0,0,0"
Appearance="Primary"
Content="Create schedule"
Icon="{ui:SymbolIcon CalendarLtr24}"
Click="OnCreate" />
</StackPanel>
<ui:InfoBar x:Name="Message"
Grid.Row="2"
Margin="0,12,0,0"
IsClosable="True"
IsOpen="False" />
<!-- Now playing -->
<Border Grid.Row="3"
Margin="0,16,0,16"
Padding="16"
CornerRadius="8"
Background="{DynamicResource CardBackgroundFillColorDefaultBrush}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<ui:TextBlock FontTypography="Caption"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Now playing" />
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
<ContentPresenter x:Name="NowKind"
VerticalAlignment="Center"
ContentTemplate="{StaticResource KindChip}"
Visibility="Collapsed" />
<ui:TextBlock x:Name="NowTitle"
Margin="8,0,0,0"
FontTypography="Subtitle"
TextTrimming="CharacterEllipsis"
Text="Nothing on air" />
</StackPanel>
<ProgressBar x:Name="NowProgress"
Margin="0,12,0,0"
AutomationProperties.Name="Progress of the current item"
Maximum="1" />
<ui:TextBlock x:Name="NowTime"
Margin="0,6,0,0"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text=" " />
</StackPanel>
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<ui:Button x:Name="StartButton"
Content="Start"
Icon="{ui:SymbolIcon Play24}"
IsEnabled="False"
Click="OnStart" />
<ui:Button x:Name="StopButton"
Margin="8,0,0,0"
Content="Stop"
Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False"
Click="OnStop" />
</StackPanel>
<StackPanel Margin="0,12,0,0" Orientation="Horizontal">
<ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" />
<Slider x:Name="VolumeSlider"
Width="140"
Margin="8,0,0,0"
VerticalAlignment="Center"
AutomationProperties.Name="Volume"
Minimum="0"
Maximum="1"
SmallChange="0.05"
LargeChange="0.1"
ValueChanged="OnVolumeChanged" />
</StackPanel>
</StackPanel>
</Grid>
</Border>
<ui:ListView x:Name="Timeline"
Grid.Row="4"
SelectionMode="Single"
IsHitTestVisible="True"
AutomationProperties.Name="Schedule timeline">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="90" Header="Start">
<ui:GridViewColumn.DisplayMemberBinding>
<Binding Path="Start" StringFormat="HH:mm:ss" />
</ui:GridViewColumn.DisplayMemberBinding>
</ui:GridViewColumn>
<ui:GridViewColumn Width="120" Header="Type" CellTemplate="{StaticResource KindChip}" />
<ui:GridViewColumn Width="420" Header="Title" DisplayMemberBinding="{Binding Title}" />
<ui:GridViewColumn Width="90" Header="Duration">
<ui:GridViewColumn.DisplayMemberBinding>
<Binding Path="Duration" StringFormat="m\:ss" />
</ui:GridViewColumn.DisplayMemberBinding>
</ui:GridViewColumn>
</ui:GridView>
</ui:ListView.View>
</ui:ListView>
<ui:TextBlock x:Name="EmptyText"
Grid.Row="4"
Margin="0,48,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Text="No schedule yet. Choose the hours and create one."
Visibility="Visible" />
</Grid>
</Page>
@@ -0,0 +1,149 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Radiosender.Controllers;
using Radiosender.Services;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
public partial class SchedulePage : Page
{
private readonly ScheduleController _controller = App.Schedule;
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
private bool _loading;
public SchedulePage()
{
InitializeComponent();
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
_progressTimer.Tick += (_, _) =>
{
UpdateButtons();
UpdateProgress();
};
}
// The page can be shown again while a broadcast runs, so it always rebuilds from the controller.
private void OnLoaded(object sender, RoutedEventArgs e)
{
_controller.ItemStarted += OnItemStarted;
_controller.ItemFailed += OnItemFailed;
_controller.Finished += OnFinished;
_loading = true;
VolumeSlider.Value = _controller.Volume;
_loading = false;
ShowPlan();
ShowCurrent();
_progressTimer.Start();
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
_controller.ItemStarted -= OnItemStarted;
_controller.ItemFailed -= OnItemFailed;
_controller.Finished -= OnFinished;
_progressTimer.Stop();
}
private void OnCreate(object sender, RoutedEventArgs e)
{
var hours = (int)(HoursBox.Value ?? 1);
try
{
_controller.CreatePlan(hours);
var plan = _controller.Plan;
ShowMessage(InfoBarSeverity.Success, "Schedule created",
$"{hours} h from {plan[0].Start:HH:mm} to {plan[^1].End:HH:mm}, {plan.Count} items.");
}
catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException)
{
ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message);
}
ShowPlan();
ShowCurrent();
}
private void OnStart(object sender, RoutedEventArgs e)
{
Message.IsOpen = false;
_controller.Start();
ShowCurrent();
}
private void OnStop(object sender, RoutedEventArgs e)
{
_controller.Stop();
ShowCurrent();
}
private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (!_loading) _controller.Volume = (float)e.NewValue;
}
// Engine events arrive on a pool thread. BeginInvoke, not Invoke: Stop waits for that thread.
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
private void OnItemFailed(object? sender, string message) =>
Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Item skipped", message));
private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
{
ShowMessage(InfoBarSeverity.Informational, "Broadcast finished", "The whole schedule has been played.");
ShowCurrent();
});
private void ShowPlan()
{
Timeline.ItemsSource = _controller.Plan;
EmptyText.Visibility = _controller.Plan.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
}
private void ShowCurrent()
{
var item = _controller.CurrentItem;
UpdateButtons();
NowKind.Content = item;
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
NowTitle.Text = item?.Title ?? "Nothing on air";
Timeline.SelectedIndex = _controller.CurrentIndex;
if (Timeline.SelectedItem is { } selected)
Timeline.ScrollIntoView(selected);
UpdateProgress();
}
private void UpdateButtons()
{
var playing = _controller.IsPlaying;
StartButton.IsEnabled = !playing && _controller.Plan.Count > 0;
StopButton.IsEnabled = playing;
}
private void UpdateProgress()
{
if (_controller.CurrentItem is not { } item)
{
NowProgress.Value = 0;
NowTime.Text = " ";
return;
}
var elapsed = _controller.CurrentElapsed;
NowProgress.Value = item.Duration.Ticks == 0 ? 0 : (double)elapsed.Ticks / item.Duration.Ticks;
NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss} · planned {item.Start:HH:mm:ss}";
}
private void ShowMessage(InfoBarSeverity severity, string title, string text)
{
Message.Severity = severity;
Message.Title = title;
Message.Message = text;
Message.IsOpen = true;
}
}
@@ -0,0 +1,117 @@
using Microsoft.Data.Sqlite;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Tests;
public sealed class ScheduleControllerTests : IDisposable
{
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
private readonly SongRepository _songs;
private DateTime _now = new(2026, 11, 23, 14, 37, 12);
public ScheduleControllerTests() => _songs = new SongRepository(Path.Combine(_directory, "test.db"));
public void Dispose()
{
SqliteConnection.ClearAllPools();
Directory.Delete(_directory, recursive: true);
}
private sealed class InstantPlayer : IAudioPlayer
{
public event EventHandler? TrackFinished;
public void Play(string filePath) => TrackFinished?.Invoke(this, EventArgs.Empty);
public void Stop() { }
}
private ScheduleController Create(Func<TimeSpan, CancellationToken, Task>? delay = null) =>
new(_songs,
new ScheduleGenerator(new ScheduleOptions(), new Random(7)),
new PlaybackEngine(new InstantPlayer(), delay ?? ((_, _) => Task.CompletedTask)),
() => _now);
private void AddSongs()
{
int[] seconds = [192, 245, 167, 331, 238, 183, 369, 141];
for (var i = 0; i < seconds.Length; i++)
_songs.Add(new Song { Title = $"Song {i}", Artist = "Artist", Duration = TimeSpan.FromSeconds(seconds[i]), FilePath = $"{i}.mp3" });
}
[Fact]
public void CreatePlan_StartsAtNextFullHourAndCoversTheHours()
{
AddSongs();
var controller = Create();
var plan = controller.CreatePlan(2);
Assert.Equal(new DateTime(2026, 11, 23, 15, 0, 0), plan[0].Start);
Assert.Equal(new DateTime(2026, 11, 23, 17, 0, 0), plan[^1].End);
Assert.Same(plan, controller.Plan);
}
[Fact]
public void CreatePlan_ThrowsScheduleExceptionForEmptyLibrary()
{
Assert.Throws<ScheduleException>(() => Create().CreatePlan(1));
}
[Theory]
[InlineData(0)]
[InlineData(25)]
public void CreatePlan_RejectsHoursOutOfRange(int hours)
{
AddSongs();
Assert.Throws<ArgumentOutOfRangeException>(() => Create().CreatePlan(hours));
}
[Fact]
public void Start_WithoutPlanThrows()
{
Assert.Throws<InvalidOperationException>(() => Create().Start());
}
[Fact]
public async Task Start_PlaysThePlanAndRaisesFinished()
{
AddSongs();
var controller = Create();
controller.CreatePlan(1);
var started = 0;
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
controller.ItemStarted += (_, _) => Interlocked.Increment(ref started);
controller.Finished += (_, _) => finished.TrySetResult();
controller.Start();
await finished.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(controller.Plan.Count, started);
Assert.Null(controller.CurrentItem);
}
[Fact]
public async Task CurrentItemAndElapsed_FollowThePlayingItem()
{
AddSongs();
var hold = new TaskCompletionSource();
var controller = Create((_, token) => hold.Task.WaitAsync(token));
controller.CreatePlan(1);
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
controller.ItemStarted += (_, _) => first.TrySetResult();
controller.Start();
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
_now = _now.AddMinutes(2);
Assert.Equal(ScheduleItemKind.News, controller.CurrentItem!.Kind);
Assert.Equal(TimeSpan.FromMinutes(2), controller.CurrentElapsed);
_now = _now.AddHours(1);
Assert.Equal(controller.CurrentItem.Duration, controller.CurrentElapsed);
controller.Stop();
Assert.False(controller.IsPlaying);
Assert.Null(controller.CurrentItem);
}
}