feat(schedule): rework the schedule page

Adds the start time, unlimited mode, start from now, end now and the
buttons to move, edit and remove timeline items. Rows update in place and
slow controller calls run off the UI thread, with the buttons switching at
once.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Fable 5.2 committed 2026-11-23 14:22:52 +01:00
1 parent d6a45cafa6
commit 80292ac90b
4 files changed
+383 -102

No files matched your search

+110 -47
View File
@@ -2,7 +2,9 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="Schedule" Title="Sendeplan"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ScrollViewer.CanContentScroll="False"
Loaded="OnLoaded" Loaded="OnLoaded"
Unloaded="OnUnloaded"> Unloaded="OnUnloaded">
<Page.Resources> <Page.Resources>
@@ -14,8 +16,8 @@
HorizontalAlignment="Left" HorizontalAlignment="Left"
BorderThickness="1" BorderThickness="1"
CornerRadius="4" CornerRadius="4"
BorderBrush="{DynamicResource TextFillColorTertiaryBrush}"> BorderBrush="{DynamicResource ControlStrongStrokeColorDefaultBrush}">
<TextBlock x:Name="ChipText" Text="{Binding Kind}" FontSize="12" /> <TextBlock x:Name="ChipText" Text="{Binding KindName}" FontSize="12" />
</Border> </Border>
<DataTemplate.Triggers> <DataTemplate.Triggers>
<DataTrigger Binding="{Binding Kind}" Value="News"> <DataTrigger Binding="{Binding Kind}" Value="News">
@@ -41,26 +43,50 @@
<RowDefinition Height="*" /> <RowDefinition Height="*" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0" FontTypography="Title" Text="Schedule" /> <!-- Wraps on narrow windows instead of cutting off the buttons. -->
<WrapPanel Grid.Row="1" Margin="0,-8,0,0">
<StackPanel Grid.Row="1" Margin="0,16,0,0" Orientation="Horizontal"> <ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="Start" />
<ui:TextBlock VerticalAlignment="Center" Text="Hours" /> <ComboBox x:Name="StartBox"
Width="112"
Margin="0,8,12,0"
VerticalAlignment="Center"
AutomationProperties.Name="Startzeit"
DisplayMemberPath="Label"
DropDownOpened="OnStartDropDownOpened" />
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="Stunden" />
<ui:NumberBox x:Name="HoursBox" <ui:NumberBox x:Name="HoursBox"
Width="140" Width="112"
Margin="12,0,0,0" Margin="0,8,12,0"
AutomationProperties.Name="Hours to plan" VerticalAlignment="Center"
AutomationProperties.Name="Zu planende Stunden"
Minimum="1" Minimum="1"
Maximum="24" Maximum="24"
Value="1" Value="1"
SmallChange="1" SmallChange="1"
MaxDecimalPlaces="0" MaxDecimalPlaces="0"
ClearButtonEnabled="False" /> ClearButtonEnabled="False" />
<ui:Button Margin="12,0,0,0" <CheckBox x:Name="UnlimitedBox"
MinWidth="0"
Margin="0,8,0,0"
VerticalAlignment="Center"
Content="Unbegrenzt"
ToolTip="Ohne Ende: Die nächsten 5 Stunden sind geplant, jede Stunde kommt eine weitere dazu."
Checked="OnUnlimitedChanged"
Unchecked="OnUnlimitedChanged" />
<ui:Button x:Name="CreateButton"
Margin="0,8,8,0"
VerticalAlignment="Center"
Appearance="Primary" Appearance="Primary"
Content="Create schedule" Content="Plan erstellen"
Icon="{ui:SymbolIcon CalendarLtr24}"
Click="OnCreate" /> Click="OnCreate" />
</StackPanel> <ui:Button x:Name="StartNowButton"
Margin="0,8,0,0"
VerticalAlignment="Center"
Content="Jetzt starten"
Icon="{ui:SymbolIcon Play24}"
ToolTip="Plant ab diesem Moment und geht sofort auf Sendung. Die Startzeit wird ignoriert."
Click="OnStartNow" />
</WrapPanel>
<ui:InfoBar x:Name="Message" <ui:InfoBar x:Name="Message"
Grid.Row="2" Grid.Row="2"
@@ -73,6 +99,8 @@
Margin="0,16,0,16" Margin="0,16,0,16"
Padding="16" Padding="16"
CornerRadius="8" CornerRadius="8"
BorderThickness="1"
BorderBrush="{DynamicResource CardStrokeColorDefaultBrush}"
Background="{DynamicResource CardBackgroundFillColorDefaultBrush}"> Background="{DynamicResource CardBackgroundFillColorDefaultBrush}">
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@@ -83,7 +111,7 @@
<StackPanel Grid.Column="0"> <StackPanel Grid.Column="0">
<ui:TextBlock FontTypography="Caption" <ui:TextBlock FontTypography="Caption"
Foreground="{DynamicResource TextFillColorSecondaryBrush}" Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Now playing" /> Text="Läuft gerade" />
<StackPanel Margin="0,4,0,0" Orientation="Horizontal"> <StackPanel Margin="0,4,0,0" Orientation="Horizontal">
<ContentPresenter x:Name="NowKind" <ContentPresenter x:Name="NowKind"
VerticalAlignment="Center" VerticalAlignment="Center"
@@ -93,11 +121,11 @@
Margin="8,0,0,0" Margin="8,0,0,0"
FontTypography="Subtitle" FontTypography="Subtitle"
TextTrimming="CharacterEllipsis" TextTrimming="CharacterEllipsis"
Text="Nothing on air" /> Text="Nichts auf Sendung" />
</StackPanel> </StackPanel>
<ProgressBar x:Name="NowProgress" <ProgressBar x:Name="NowProgress"
Margin="0,12,0,0" Margin="0,12,0,0"
AutomationProperties.Name="Progress of the current item" AutomationProperties.Name="Fortschritt des aktuellen Elements"
Maximum="1" /> Maximum="1" />
<ui:TextBlock x:Name="NowTime" <ui:TextBlock x:Name="NowTime"
Margin="0,6,0,0" Margin="0,6,0,0"
@@ -106,18 +134,21 @@
</StackPanel> </StackPanel>
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center"> <StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal"> <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
<ui:Button x:Name="StartButton" <ui:Button x:Name="EndNowButton"
Content="Jetzt beenden"
Icon="{ui:SymbolIcon Next24}"
ToolTip="Beendet das laufende Element sofort; das nächste startet."
IsEnabled="False"
Click="OnEndNow" />
<!-- One button: Start while idle, Stop while on air. -->
<ui:Button x:Name="PlayButton"
MinWidth="110"
Margin="8,0,0,0"
Content="Start" Content="Start"
Icon="{ui:SymbolIcon Play24}" Icon="{ui:SymbolIcon Play24}"
IsEnabled="False" IsEnabled="False"
Click="OnStart" /> Click="OnPlayToggle" />
<ui:Button x:Name="StopButton"
Margin="8,0,0,0"
Content="Stop"
Icon="{ui:SymbolIcon Stop24}"
IsEnabled="False"
Click="OnStop" />
</StackPanel> </StackPanel>
<StackPanel Margin="0,12,0,0" Orientation="Horizontal"> <StackPanel Margin="0,12,0,0" Orientation="Horizontal">
<ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" /> <ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" />
@@ -125,7 +156,7 @@
Width="140" Width="140"
Margin="8,0,0,0" Margin="8,0,0,0"
VerticalAlignment="Center" VerticalAlignment="Center"
AutomationProperties.Name="Volume" AutomationProperties.Name="Lautstärke"
Minimum="0" Minimum="0"
Maximum="1" Maximum="1"
SmallChange="0.05" SmallChange="0.05"
@@ -136,19 +167,21 @@
</Grid> </Grid>
</Border> </Border>
<!-- Song request (hot swap) --> <!-- Song request (hot swap) on the left, actions for the selected timeline row on the right -->
<Grid Grid.Row="4" Margin="0,0,0,12"> <StackPanel Grid.Row="4" Margin="0,0,0,12">
<Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MaxWidth="420" /> <ColumnDefinition Width="4*" MaxWidth="320" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Song request" /> <ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Songwunsch" />
<ComboBox x:Name="RequestSong" <ComboBox x:Name="RequestSong"
Grid.Column="1" Grid.Column="1"
Margin="12,0,0,0" Margin="12,0,0,0"
AutomationProperties.Name="Requested song" AutomationProperties.Name="GewĂĽnschter Song"
DisplayMemberPath="Label" DisplayMemberPath="Label"
IsEditable="True" IsEditable="True"
IsTextSearchEnabled="True" IsTextSearchEnabled="True"
@@ -157,25 +190,54 @@
<ui:Button x:Name="SwapButton" <ui:Button x:Name="SwapButton"
Grid.Column="2" Grid.Column="2"
Margin="12,0,0,0" Margin="12,0,0,0"
Content="Play instead of selected" Content="Auswahl ersetzen"
Icon="{ui:SymbolIcon ArrowSwap24}" Icon="{ui:SymbolIcon ArrowSwap24}"
IsEnabled="False" IsEnabled="False"
Click="OnSwap" /> Click="OnSwap" />
<ui:TextBlock x:Name="SwapHint" <StackPanel Grid.Column="4" Margin="12,0,0,0" Orientation="Horizontal">
Grid.Column="3" <ui:Button x:Name="MoveUpButton"
Margin="12,0,0,0" Icon="{ui:SymbolIcon ArrowUp24}"
VerticalAlignment="Center" ToolTip="Nach oben"
Foreground="{DynamicResource TextFillColorSecondaryBrush}" AutomationProperties.Name="Ausgewähltes Element nach oben verschieben"
TextTrimming="CharacterEllipsis" IsEnabled="False"
Text="Select an upcoming item in the schedule." /> Click="OnMoveUp" />
<ui:Button x:Name="MoveDownButton"
Margin="4,0,0,0"
Icon="{ui:SymbolIcon ArrowDown24}"
ToolTip="Nach unten"
AutomationProperties.Name="Ausgewähltes Element nach unten verschieben"
IsEnabled="False"
Click="OnMoveDown" />
<ui:Button x:Name="EditItemButton"
Margin="4,0,0,0"
Icon="{ui:SymbolIcon Edit24}"
ToolTip="Titel und Länge bearbeiten"
AutomationProperties.Name="Ausgewähltes Element bearbeiten"
IsEnabled="False"
Click="OnEditItem" />
<ui:Button x:Name="RemoveButton"
Margin="4,0,0,0"
Icon="{ui:SymbolIcon Delete24}"
ToolTip="Aus dem Plan entfernen"
AutomationProperties.Name="Ausgewähltes Element entfernen"
IsEnabled="False"
Click="OnRemove" />
</StackPanel>
</Grid> </Grid>
<ui:TextBlock x:Name="SwapHint"
Margin="0,6,0,0"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
TextWrapping="Wrap"
Visibility="Collapsed" />
</StackPanel>
<ui:ListView x:Name="Timeline" <ui:ListView x:Name="Timeline"
Grid.Row="5" Grid.Row="5"
SelectionMode="Single" SelectionMode="Single"
IsHitTestVisible="True" IsHitTestVisible="True"
AutomationProperties.Name="Schedule timeline" AutomationProperties.Name="Sendeplan"
SelectionChanged="OnTimelineSelectionChanged"> SelectionChanged="OnTimelineSelectionChanged"
MouseDoubleClick="OnEditItem">
<ui:ListView.View> <ui:ListView.View>
<ui:GridView> <ui:GridView>
<ui:GridViewColumn Width="36"> <ui:GridViewColumn Width="36">
@@ -185,7 +247,7 @@
Symbol="Play24" Symbol="Play24"
Filled="True" Filled="True"
Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}" Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}"
AutomationProperties.Name="On air" AutomationProperties.Name="Auf Sendung"
Visibility="Collapsed" /> Visibility="Collapsed" />
<DataTemplate.Triggers> <DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsCurrent}" Value="True"> <DataTrigger Binding="{Binding IsCurrent}" Value="True">
@@ -200,15 +262,15 @@
<Binding Path="Item.Start" StringFormat="HH:mm:ss" /> <Binding Path="Item.Start" StringFormat="HH:mm:ss" />
</ui:GridViewColumn.DisplayMemberBinding> </ui:GridViewColumn.DisplayMemberBinding>
</ui:GridViewColumn> </ui:GridViewColumn>
<ui:GridViewColumn Width="120" Header="Type"> <ui:GridViewColumn Width="120" Header="Typ">
<ui:GridViewColumn.CellTemplate> <ui:GridViewColumn.CellTemplate>
<DataTemplate> <DataTemplate>
<ContentPresenter Content="{Binding Item}" ContentTemplate="{StaticResource KindChip}" /> <ContentPresenter Content="{Binding Item}" ContentTemplate="{StaticResource KindChip}" />
</DataTemplate> </DataTemplate>
</ui:GridViewColumn.CellTemplate> </ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn> </ui:GridViewColumn>
<ui:GridViewColumn Width="420" Header="Title" DisplayMemberBinding="{Binding Item.Title}" /> <ui:GridViewColumn Width="360" Header="Titel" DisplayMemberBinding="{Binding Item.Title}" />
<ui:GridViewColumn Width="90" Header="Duration"> <ui:GridViewColumn Width="90" Header="Dauer">
<ui:GridViewColumn.DisplayMemberBinding> <ui:GridViewColumn.DisplayMemberBinding>
<Binding Path="Item.Duration" StringFormat="m\:ss" /> <Binding Path="Item.Duration" StringFormat="m\:ss" />
</ui:GridViewColumn.DisplayMemberBinding> </ui:GridViewColumn.DisplayMemberBinding>
@@ -222,7 +284,8 @@
Margin="0,48,0,0" Margin="0,48,0,0"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Top" VerticalAlignment="Top"
Text="No schedule yet. Choose the hours and create one." Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Noch kein Plan. Stunden wählen und Plan erstellen."
Visibility="Visible" /> Visibility="Visible" />
</Grid> </Grid>
</Page> </Page>
+191 -55
View File
@@ -1,3 +1,4 @@
using System.Collections.ObjectModel;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Threading; using System.Windows.Threading;
@@ -14,10 +15,24 @@ public partial class SchedulePage : Page
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) }; private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
private bool _loading; private bool _loading;
private int _scrolledTo = -1; private int _scrolledTo = -1;
private bool _shownPlaying;
// Weekday names in the start list follow the interface language, not the Windows setting.
private static readonly System.Globalization.CultureInfo German = new("de-DE");
// Bound once and updated row by row, so a click never rebuilds the whole list.
private readonly ObservableCollection<TimelineRow> _rows = [];
// A controller call is running on a pool thread; the buttons that would collide with it are off.
private bool _working;
// Optimistic state: what the user just asked for, shown before the engine has caught up.
private bool? _expectPlaying;
public SchedulePage() public SchedulePage()
{ {
InitializeComponent(); InitializeComponent();
Timeline.ItemsSource = _rows;
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped. // Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
_progressTimer.Tick += (_, _) => _progressTimer.Tick += (_, _) =>
{ {
@@ -36,6 +51,9 @@ public partial class SchedulePage : Page
_loading = true; _loading = true;
VolumeSlider.Value = _controller.Volume; VolumeSlider.Value = _controller.Volume;
_loading = false; _loading = false;
FillStartTimes();
if (_controller.Plan.Count > 0)
UnlimitedBox.IsChecked = _controller.IsUnlimited;
// The library can change on other pages. // The library can change on other pages.
RequestSong.ItemsSource = _controller.LibrarySongs() RequestSong.ItemsSource = _controller.LibrarySongs()
@@ -55,65 +73,148 @@ public partial class SchedulePage : Page
_progressTimer.Stop(); _progressTimer.Stop();
} }
private void OnCreate(object sender, RoutedEventArgs e) // The next 12 full hours; rebuilt when the list opens, so it never offers a past hour.
private void FillStartTimes()
{ {
var hours = (int)(HoursBox.Value ?? 1); var selected = (StartBox.SelectedItem as StartOption)?.Time;
try var now = DateTime.Now;
{ var next = now.Date.AddHours(now.Hour + 1);
_controller.CreatePlan(hours); var options = Enumerable.Range(0, 12)
var plan = _controller.Plan; .Select(i => next.AddHours(i))
ShowMessage(InfoBarSeverity.Success, "Schedule created", .Select(t => new StartOption(t, t.Date == now.Date ? $"{t:HH:mm}" : t.ToString("ddd HH:mm", German)))
$"{hours} h from {plan[0].Start:HH:mm} to {plan[^1].End:HH:mm}, {plan.Count} items."); .ToList();
} StartBox.ItemsSource = options;
catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException) StartBox.SelectedItem = options.FirstOrDefault(o => o.Time == selected) ?? options[0];
{
ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message);
}
ShowCurrent();
} }
private void OnSwap(object sender, RoutedEventArgs e) private void OnStartDropDownOpened(object? sender, EventArgs e) => FillStartTimes();
private void OnUnlimitedChanged(object sender, RoutedEventArgs e) =>
HoursBox.IsEnabled = UnlimitedBox.IsChecked != true;
private void OnCreate(object sender, RoutedEventArgs e) => CreatePlan(startNow: false);
private void OnStartNow(object sender, RoutedEventArgs e) => CreatePlan(startNow: true);
private async void CreatePlan(bool startNow)
{
int? hours = UnlimitedBox.IsChecked == true ? null : (int)(HoursBox.Value ?? 1);
var start = (StartBox.SelectedItem as StartOption)?.Time;
if (startNow)
_expectPlaying = true;
await RunAsync("Der Plan konnte nicht erstellt werden", () =>
{
if (startNow)
_controller.StartNow(hours);
else
_controller.CreatePlan(hours, start);
});
}
/// <summary>
/// Runs a controller call that can take a moment (planning, waiting for the audio thread to stop)
/// off the UI thread, so the window stays responsive. Returns <c>false</c> after showing the error.
/// </summary>
private async Task<bool> RunAsync(string errorTitle, Action work)
{
_working = true;
UpdateButtons();
try
{
await Task.Run(work);
Message.IsOpen = false;
return true;
}
catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException or InvalidOperationException)
{
ShowMessage(InfoBarSeverity.Error, errorTitle, ex.Message);
return false;
}
finally
{
_working = false;
_expectPlaying = null;
ShowCurrent();
}
}
private async void OnSwap(object sender, RoutedEventArgs e)
{ {
if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song) if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song)
return; return;
try ScheduleItem? placed = null;
{ if (await RunAsync("Der Songwunsch konnte nicht eingeplant werden", () => placed = _controller.Swap(row.Index, song.Id)[row.Index]))
var plan = _controller.Swap(row.Index, song.Id); ShowMessage(InfoBarSeverity.Success, "Songwunsch eingeplant",
var placed = plan[row.Index]; $"\"{placed!.Title}\" läuft um {placed.Start:HH:mm:ss}.");
ShowMessage(InfoBarSeverity.Success, "Song request planned",
$"\"{placed.Title}\" plays at {placed.Start:HH:mm:ss} instead of \"{row.Item.Title}\". The rest of that half hour was replanned, the news stays on time.");
}
catch (ScheduleException ex)
{
ShowMessage(InfoBarSeverity.Error, "Could not play the request", ex.Message);
}
ShowCurrent();
} }
private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); private void OnMoveUp(object sender, RoutedEventArgs e) => MoveSelected(-1);
private void OnStart(object sender, RoutedEventArgs e) private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1);
// The selection follows the item, so it can be moved several steps in a row.
private void MoveSelected(int offset) => ChangeSelected(row =>
{
_controller.Move(row.Index, offset);
Timeline.SelectedIndex = row.Index + offset;
});
private void OnEndNow(object sender, RoutedEventArgs e)
{ {
Message.IsOpen = false;
try try
{ {
_controller.Start(); _controller.EndCurrentNow();
Message.IsOpen = false;
} }
catch (InvalidOperationException ex) catch (ScheduleException ex)
{ {
ShowMessage(InfoBarSeverity.Warning, "Could not start", ex.Message); ShowMessage(InfoBarSeverity.Error, "Das Element konnte nicht beendet werden", ex.Message);
} }
ShowCurrent(); ShowCurrent();
} }
private void OnStop(object sender, RoutedEventArgs e) private void OnRemove(object sender, RoutedEventArgs e) => ChangeSelected(row => _controller.Remove(row.Index));
private void OnEditItem(object sender, RoutedEventArgs e)
{ {
_controller.Stop(); if (!EditItemButton.IsEnabled || Timeline.SelectedItem is not TimelineRow row)
return;
var dialog = new ScheduleItemEditWindow(row.Item) { Owner = Window.GetWindow(this) };
if (dialog.ShowDialog() == true)
ChangeSelected(r => _controller.EditItem(r.Index, dialog.ItemTitle, dialog.Duration));
}
private void ChangeSelected(Action<TimelineRow> change)
{
if (Timeline.SelectedItem is not TimelineRow row)
return;
try
{
change(row);
Message.IsOpen = false;
}
catch (ScheduleException ex)
{
ShowMessage(InfoBarSeverity.Error, "Der Plan konnte nicht geändert werden", ex.Message);
}
ShowCurrent(); ShowCurrent();
} }
private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
private async void OnPlayToggle(object sender, RoutedEventArgs e)
{
var stop = _controller.IsPlaying;
// The button and the card switch at once; stopping waits for the audio thread in the background.
_expectPlaying = !stop;
if (stop)
NowKind.Visibility = Visibility.Collapsed;
UpdateProgress();
await RunAsync("Start nicht möglich", stop ? _controller.Stop : _controller.Start);
}
private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e) private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{ {
if (!_loading) _controller.Volume = (float)e.NewValue; if (!_loading) _controller.Volume = (float)e.NewValue;
@@ -123,15 +224,15 @@ public partial class SchedulePage : Page
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent); private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
private void OnItemFailed(object? sender, string message) => private void OnItemFailed(object? sender, string message) =>
Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Item skipped", message)); Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Element ĂĽbersprungen", message));
private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() => private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
{ {
ShowMessage(InfoBarSeverity.Informational, "Broadcast finished", "The whole schedule has been played."); ShowMessage(InfoBarSeverity.Informational, "Sendung beendet", "Der ganze Plan wurde gespielt.");
ShowCurrent(); ShowCurrent();
}); });
// Rebuilds the rows from the controller; the selection is the user's swap target and is kept. // Syncs the rows with the controller; the selection is the user's swap target and is kept.
private void ShowCurrent() private void ShowCurrent()
{ {
var item = _controller.CurrentItem; var item = _controller.CurrentItem;
@@ -139,8 +240,19 @@ public partial class SchedulePage : Page
var plan = _controller.Plan; var plan = _controller.Plan;
var selected = Timeline.SelectedIndex; var selected = Timeline.SelectedIndex;
var rows = plan.Select((p, i) => new TimelineRow(i, p, i == current)).ToList(); // Rows are records: only the ones whose content changed are replaced.
Timeline.ItemsSource = rows; for (var i = 0; i < plan.Count; i++)
{
var updated = new TimelineRow(i, plan[i], i == current);
if (i == _rows.Count)
_rows.Add(updated);
else if (_rows[i] != updated)
_rows[i] = updated;
}
while (_rows.Count > plan.Count)
_rows.RemoveAt(_rows.Count - 1);
var rows = _rows;
GridColumns.Fit(Timeline);
Timeline.SelectedIndex = selected < rows.Count ? selected : -1; Timeline.SelectedIndex = selected < rows.Count ? selected : -1;
// Follow the broadcast when it moves on; otherwise keep the user's row in view. // Follow the broadcast when it moves on; otherwise keep the user's row in view.
if (current != _scrolledTo && current >= 0 && current < rows.Count) if (current != _scrolledTo && current >= 0 && current < rows.Count)
@@ -152,7 +264,7 @@ public partial class SchedulePage : Page
NowKind.Content = item; NowKind.Content = item;
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible; NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
if (item is not null) NowTitle.Text = item.Title; if (item is not null) NowTitle.Text = item.Title.Length > 0 ? item.Title : item.KindName;
UpdateButtons(); UpdateButtons();
UpdateProgress(); UpdateProgress();
@@ -160,38 +272,60 @@ public partial class SchedulePage : Page
private void UpdateButtons() private void UpdateButtons()
{ {
var playing = _controller.IsPlaying; var playing = _expectPlaying ?? _controller.IsPlaying;
StartButton.IsEnabled = !playing && _controller.Plan.Count > 0; PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0);
StopButton.IsEnabled = playing; CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working;
// Called every timer tick, so the label and icon change only with the state.
if (playing != _shownPlaying)
{
_shownPlaying = playing;
PlayButton.Content = playing ? "Stopp" : "Start";
PlayButton.Icon = new SymbolIcon(playing ? SymbolRegular.Stop24 : SymbolRegular.Play24);
}
var row = Timeline.SelectedItem as TimelineRow; var row = Timeline.SelectedItem as TimelineRow;
// Only items that are not on air or over can be moved or removed; the one on air can still be edited.
var count = _controller.Plan.Count;
var current = _controller.CurrentIndex;
bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current);
var index = row?.Index ?? -1;
MoveUpButton.IsEnabled = Editable(index) && Editable(index - 1);
MoveDownButton.IsEnabled = Editable(index) && Editable(index + 1);
RemoveButton.IsEnabled = Editable(index);
var onAir = !_working && playing && index >= 0 && index == current;
EditItemButton.IsEnabled = (Editable(index) || onAir) && row!.Item.Kind != ScheduleItemKind.Song;
EndNowButton.IsEnabled = !_working && _expectPlaying != false && _controller.CurrentItem is not null;
var blocker = row switch var blocker = row switch
{ {
null => "Select an upcoming item in the schedule.", null => "Ein kommendes Element im Plan auswählen.",
{ Item.Kind: ScheduleItemKind.News } => "News cannot be replaced.", { Item.Kind: ScheduleItemKind.News } => "Nachrichten können nicht ersetzt werden.",
_ when playing && row.Index <= _controller.CurrentIndex => "This item is already on air or over.", _ when playing && row.Index <= _controller.CurrentIndex => "Dieses Element ist bereits auf Sendung oder vorbei.",
_ when RequestSong.SelectedItem is null => "Choose a song from the library.",
_ => null, _ => null,
}; };
SwapHint.Text = blocker ?? $"Replaces the item at {row!.Item.Start:HH:mm:ss}."; SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}.";
SwapButton.IsEnabled = blocker is null; // The hint only matters once a song is chosen.
var requested = RequestSong.SelectedItem is not null;
SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed;
SwapButton.IsEnabled = !_working && requested && blocker is null;
} }
private void UpdateProgress() private void UpdateProgress()
{ {
if (_controller.CurrentItem is not { } item) if (_expectPlaying == false || _controller.CurrentItem is not { } item)
{ {
NowProgress.Value = 0; NowProgress.Value = 0;
// Checked here, not in ShowCurrent: the engine starts waiting a moment after Start. // Checked here, not in ShowCurrent: the engine starts waiting a moment after Start.
var waiting = _controller.WaitingUntil; var waiting = _expectPlaying == false ? null : _controller.WaitingUntil;
NowTitle.Text = waiting is { } at ? $"On air at {at:HH:mm:ss}" : "Nothing on air"; NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung";
NowTime.Text = waiting is null ? " " : "Waiting for the planned start, so the news comes at :00 and :30."; NowTime.Text = " ";
return; return;
} }
var elapsed = _controller.CurrentElapsed; var elapsed = _controller.CurrentElapsed;
NowProgress.Value = item.Duration.Ticks == 0 ? 0 : (double)elapsed.Ticks / item.Duration.Ticks; 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}"; NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss}";
} }
private void ShowMessage(InfoBarSeverity severity, string title, string text) private void ShowMessage(InfoBarSeverity severity, string title, string text)
@@ -205,4 +339,6 @@ public partial class SchedulePage : Page
private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent); private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent);
private sealed record SongOption(long Id, string Label); private sealed record SongOption(long Id, string Label);
private sealed record StartOption(DateTime Time, string Label);
} }
@@ -0,0 +1,36 @@
<ui:FluentWindow x:Class="Radiosender.Views.ScheduleItemEditWindow"
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="Element bearbeiten"
Width="400" SizeToContent="Height"
ResizeMode="NoResize"
ShowInTaskbar="False"
ExtendsContentIntoTitleBar="True"
WindowBackdropType="Mica"
WindowStartupLocation="CenterOwner"
FocusManager.FocusedElement="{Binding ElementName=TitleBox}">
<StackPanel>
<ui:TitleBar x:Name="Bar" Title="Element bearbeiten" ShowMinimize="False" ShowMaximize="False" />
<StackPanel Margin="24,8,24,24">
<Label Content="_Titel" Target="{Binding ElementName=TitleBox}" />
<ui:TextBox x:Name="TitleBox" Margin="0,0,0,12" PlaceholderText="Optional" />
<Label x:Name="DurationLabel" Content="_Länge (m:ss)" Target="{Binding ElementName=DurationBox}" />
<ui:TextBox x:Name="DurationBox" />
<TextBlock x:Name="ErrorText"
Margin="0,12,0,0"
Foreground="{DynamicResource SystemFillColorCriticalBrush}"
Text="Länge als Minuten und Sekunden eingeben, zum Beispiel 5:00."
TextWrapping="Wrap"
Visibility="Collapsed" />
<StackPanel Margin="0,24,0,0" HorizontalAlignment="Right" Orientation="Horizontal">
<ui:Button Content="Speichern" Appearance="Primary" IsDefault="True" MinWidth="90" Click="OnSave" />
<ui:Button Margin="8,0,0,0" Content="Abbrechen" IsCancel="True" MinWidth="90" />
</StackPanel>
</StackPanel>
</StackPanel>
</ui:FluentWindow>
@@ -0,0 +1,46 @@
using System.Globalization;
using System.Windows;
using Radiosender.Models;
using Wpf.Ui.Controls;
namespace Radiosender.Views;
/// <summary>
/// Dialog for the title of a news, ad or moderator item and, for news and moderator items, its length.
/// Only collects input; the caller changes the schedule.
/// </summary>
public partial class ScheduleItemEditWindow : FluentWindow
{
private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"];
public ScheduleItemEditWindow(ScheduleItem item)
{
InitializeComponent();
Title = Bar.Title = $"{item.KindName} bearbeiten";
TitleBox.Text = item.Title;
DurationBox.Text = item.Duration.ToString(@"m\:ss");
Duration = item.Duration;
// Ads keep their length.
DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
}
public string ItemTitle => TitleBox.Text;
public TimeSpan Duration { get; private set; }
private void OnSave(object sender, RoutedEventArgs e)
{
if (DurationBox.IsEnabled)
{
if (!TimeSpan.TryParseExact(DurationBox.Text.Trim(), DurationFormats, CultureInfo.InvariantCulture, out var duration)
|| duration <= TimeSpan.Zero)
{
ErrorText.Visibility = Visibility.Visible;
return;
}
Duration = duration;
}
DialogResult = true;
}
}