feat(schedule): rework the schedule page controls and timeline

- Mixer in two areas: what the listeners hear (music, microphone) and
  what you hear; the master volume is gone.
- One start button starts the created plan and goes live when laut.fm
  is on; while on air it ends the broadcast.
- The start field takes Jetzt (default), a full hour or a typed time.
  A Jetzt plan moves to the moment it starts.
- Timeline rows can be dragged to a new place; HinzufĂĽgen inserts a
  song, news, an ad or moderator talk as the item after next.
- All page texts are translated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Opus 5.5 committed 2026-11-26 09:23:06 +01:00
1 parent 4c8740774d
commit ef388d82f4
8 files changed
+563 -245

No files matched your search

@@ -1,6 +1,7 @@
using Radiosender.Models;
using Radiosender.Services.Audio;
using Radiosender.Services.Library;
using Radiosender.Services.Localization;
using Radiosender.Services.Scheduling;
namespace Radiosender.Controllers;
@@ -18,6 +19,7 @@ public class ScheduleController
private readonly Func<DateTime> _now;
// Plan edits (UI thread) vs. hourly extension (engine thread).
private readonly Lock _planLock = new();
private bool _fromNow; // plan starts at its creation moment, not at a set time
private DateTime _itemStartedAt;
public ScheduleController(SongRepository songs, ScheduleGenerator generator, PlaybackEngine engine, Func<DateTime> now)
@@ -32,7 +34,7 @@ public class ScheduleController
ExtendIfUnlimited();
ItemStarted?.Invoke(this, e.Index);
};
_engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"\"{e.Item.Title}\" ĂĽbersprungen: {e.Error.Message}");
_engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, Loc.F("Schedule_ItemFailedText", e.Item.Title, e.Error.Message));
_engine.Finished += (_, _) => Finished?.Invoke(this, EventArgs.Empty);
}
@@ -54,12 +56,6 @@ public class ScheduleController
? TimeSpan.FromTicks(Math.Clamp((_now() - _itemStartedAt).Ticks, 0, item.Duration.Ticks))
: TimeSpan.Zero;
public float Volume
{
get => MusicPlayer.Instance.Volume;
set => MusicPlayer.Instance.Volume = value;
}
// hours null = unlimited; start null = next full hour.
/// <exception cref="ScheduleException">Library cannot fill the plan.</exception>
public IReadOnlyList<ScheduleItem> CreatePlan(int? hours, DateTime? start = null)
@@ -79,17 +75,11 @@ public class ScheduleController
{
Plan = plan;
IsUnlimited = hours is null;
_fromNow = from <= now;
}
return plan;
}
/// <exception cref="ScheduleException">Library cannot fill the plan.</exception>
public void StartNow(int? hours)
{
CreatePlan(hours, _now());
_engine.Start(Plan);
}
// Engine thread. shortcut: played items stay in Plan (~20/h), trim if broadcasts run for weeks.
private void ExtendIfUnlimited()
{
@@ -112,7 +102,7 @@ public class ScheduleController
}
catch (ScheduleException ex)
{
ItemFailed?.Invoke(this, $"Der Plan konnte nicht verlängert werden: {ex.Message}");
ItemFailed?.Invoke(this, Loc.F("Schedule_ExtendFailed", ex.Message));
}
}
@@ -120,11 +110,23 @@ public class ScheduleController
public void Start()
{
if (Plan.Count == 0)
throw new InvalidOperationException("Zuerst einen Plan erstellen.");
if (Plan[^1].Start <= _now())
throw new InvalidOperationException("Dieser Plan ist bereits vorbei. Einen neuen erstellen.");
_engine.Start(Plan);
lock (_planLock)
{
if (Plan.Count == 0)
throw new InvalidOperationException(Loc.T("Schedule_CreateFirst"));
var now = _now();
// "Jetzt" plan, first start: shift to now, else the engine skips what began while the user waited.
// shortcut: news drift by that wait; regenerate if users wait minutes between create and start.
if (_fromNow && Plan[0].Start < now)
{
var offset = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind) - Plan[0].Start;
Plan = [.. Plan.Select(item => item with { Start = item.Start + offset })];
}
_fromNow = false;
if (Plan[^1].Start <= now)
throw new InvalidOperationException(Loc.T("Schedule_PlanOver"));
_engine.Start(Plan);
}
}
public void Stop() => _engine.Stop();
@@ -159,7 +161,7 @@ public class ScheduleController
{
var target = index + offset;
if (target < 0 || target >= Plan.Count)
throw new ScheduleException("Das Element ist bereits am Rand des Plans.");
throw new ScheduleException(Loc.T("Schedule_AtEdge"));
return Change(Math.Min(index, target), change: items =>
{
var item = items[index];
@@ -168,6 +170,23 @@ public class ScheduleController
});
}
// index == Plan.Count appends. Song: songId required, its length is used.
/// <exception cref="ScheduleException">No plan, position on air or over, song missing, or length not positive.</exception>
public IReadOnlyList<ScheduleItem> Insert(int index, ScheduleItemKind kind, string title, TimeSpan duration, long? songId = null)
{
Song? song = null;
if (kind == ScheduleItemKind.Song)
{
song = (songId is { } id ? _songs.GetById(id) : null) ?? throw new ScheduleException(Loc.T("Schedule_SongGone"));
title = string.IsNullOrWhiteSpace(song.Artist) ? song.Title : $"{song.Artist} - {song.Title}";
duration = song.Duration;
}
if (duration <= TimeSpan.Zero)
throw new ScheduleException(Loc.T("Schedule_LengthPositive"));
var item = new ScheduleItem(kind, title.Trim(), default, duration, song);
return Change(index, change: items => items.Insert(index, item), appendAllowed: true);
}
/// <exception cref="ScheduleException">Item on air or over.</exception>
public IReadOnlyList<ScheduleItem> Remove(int index) => Change(index, change: items => items.RemoveAt(index));
@@ -176,7 +195,7 @@ public class ScheduleController
{
var index = CurrentIndex;
if (CurrentItem is null)
throw new ScheduleException("Es ist nichts auf Sendung.");
throw new ScheduleException(Loc.T("Schedule_NothingOnAirError"));
var now = _now();
// Whole seconds: next start not in the future.
var end = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind);
@@ -192,29 +211,29 @@ public class ScheduleController
{
var item = items[index];
if (item.Kind == ScheduleItemKind.Song)
throw new ScheduleException("Songs werden in der Bibliothek bearbeitet.");
throw new ScheduleException(Loc.T("Schedule_SongsEditInLibrary"));
if (duration != item.Duration && item.Kind == ScheduleItemKind.Ad)
throw new ScheduleException("Nur Nachrichten und Moderation können ihre Länge ändern.");
throw new ScheduleException(Loc.T("Schedule_OnlyNewsModeratorLength"));
if (duration <= TimeSpan.Zero)
throw new ScheduleException("Die Länge muss größer als null sein.");
throw new ScheduleException(Loc.T("Schedule_LengthPositive"));
items[index] = item with { Title = title.Trim(), Duration = duration };
});
// Ripple re-time from firstChanged; news may leave :00/:30 (intended).
private IReadOnlyList<ScheduleItem> Change(int firstChanged, Action<List<ScheduleItem>> change, bool currentAllowed = false)
private IReadOnlyList<ScheduleItem> Change(int firstChanged, Action<List<ScheduleItem>> change, bool currentAllowed = false, bool appendAllowed = false)
{
lock (_planLock)
{
if (firstChanged < 0 || firstChanged >= Plan.Count)
throw new ScheduleException("Ein Element im Plan auswählen.");
if (Plan.Count == 0)
throw new ScheduleException(Loc.T("Schedule_CreateFirst"));
if (firstChanged < 0 || firstChanged > Plan.Count || (firstChanged == Plan.Count && !appendAllowed))
throw new ScheduleException(Loc.T("Schedule_SelectItem"));
var onAir = IsPlaying && firstChanged == CurrentIndex;
if (IsPlaying && (firstChanged < CurrentIndex || (onAir && !currentAllowed)))
throw new ScheduleException(onAir
? "Dieses Element ist auf Sendung. Es kann bearbeitet oder beendet, aber nicht verschoben oder entfernt werden."
: "Dieses Element ist bereits vorbei. Ein späteres wählen.");
throw new ScheduleException(Loc.T(onAir ? "Schedule_OnAirLocked" : "Schedule_ItemOver"));
List<ScheduleItem> items = [.. Plan];
var start = items[firstChanged].Start;
var start = firstChanged < items.Count ? items[firstChanged].Start : items[^1].End;
change(items);
for (var i = firstChanged; i < items.Count; i++)
{
@@ -223,7 +242,7 @@ public class ScheduleController
}
if (IsPlaying && !(onAir ? _engine.ReplaceCurrent(items, firstChanged) : _engine.ReplaceUpcoming(items, firstChanged)))
throw new ScheduleException("Die Sendung ist inzwischen weitergelaufen. Erneut versuchen.");
throw new ScheduleException(Loc.T("Schedule_RunMovedOn"));
Plan = items;
return items;
}
@@ -238,16 +257,16 @@ public class ScheduleController
lock (_planLock)
{
if (Plan.Count == 0)
throw new ScheduleException("Zuerst einen Plan erstellen.");
throw new ScheduleException(Loc.T("Schedule_CreateFirst"));
if (index < 0 || index >= Plan.Count)
throw new ScheduleException("Ein Element im Plan auswählen.");
throw new ScheduleException(Loc.T("Schedule_SelectItem"));
if (IsPlaying && index <= CurrentIndex)
throw new ScheduleException("Dieses Element ist bereits auf Sendung oder vorbei. Ein späteres wählen.");
var song = _songs.GetById(songId) ?? throw new ScheduleException("Der Song ist nicht mehr in der Bibliothek.");
throw new ScheduleException(Loc.T("Schedule_SwapOnAirOrOver"));
var song = _songs.GetById(songId) ?? throw new ScheduleException(Loc.T("Schedule_SongGone"));
var plan = _generator.Replace(Plan, index, song, _songs.GetAll());
if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
throw new ScheduleException("Dieses Element ist inzwischen auf Sendung gegangen. Ein späteres wählen.");
throw new ScheduleException(Loc.T("Schedule_SwapWentOnAir"));
Plan = plan;
return plan;
}
+4 -19
View File
@@ -1,5 +1,6 @@
using System.IO;
using NAudio.Wave;
using Radiosender.Services.Localization;
namespace Radiosender.Services.Audio;
@@ -12,7 +13,6 @@ public sealed class MusicPlayer : IAudioPlayer
private readonly Lock _lock = new();
private AudioFileReader? _reader;
private ISampleProvider? _input;
private float _volume = 1f;
private MusicPlayer()
{
@@ -36,21 +36,6 @@ public sealed class MusicPlayer : IAudioPlayer
get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
}
public float Volume
{
get { lock (_lock) return _volume; }
set
{
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
lock (_lock)
{
_volume = value;
_reader?.Volume = value;
}
}
}
public void Play(string filePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
@@ -60,17 +45,17 @@ public sealed class MusicPlayer : IAudioPlayer
Release();
if (!File.Exists(filePath))
throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath);
throw new FileNotFoundException(Loc.F("Audio_FileNotFound", filePath), filePath);
try
{
_reader = new AudioFileReader(filePath) { Volume = _volume };
_reader = new AudioFileReader(filePath);
_input = _output.Add(_reader, AudioSource.Music);
}
catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
{
Release();
throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
throw new InvalidDataException(Loc.F("Audio_FileUnreadable", filePath), ex);
}
catch
{
+106 -81
View File
@@ -2,7 +2,9 @@
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="Sendeplan"
xmlns:models="clr-namespace:Radiosender.Models"
xmlns:l="clr-namespace:Radiosender.Views"
Title="{l:Tr Schedule_Title}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ScrollViewer.CanContentScroll="False"
Loaded="OnLoaded"
@@ -45,20 +47,23 @@
<!-- Wraps on narrow windows instead of cutting off the buttons. -->
<WrapPanel Grid.Row="1" Margin="0,-8,0,0">
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="Start" />
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="{l:Tr Schedule_Start}" />
<!-- Editable: pick "Jetzt" or a full hour, or type a time like 14:30 -->
<ComboBox x:Name="StartBox"
Width="112"
IsEditable="True"
ToolTip="{l:Tr Schedule_StartTimeTip}"
Margin="0,8,12,0"
VerticalAlignment="Center"
AutomationProperties.Name="Startzeit"
AutomationProperties.Name="{l:Tr Schedule_StartTimeName}"
DisplayMemberPath="Label"
DropDownOpened="OnStartDropDownOpened" />
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="Stunden" />
<ui:TextBlock Margin="0,8,8,0" VerticalAlignment="Center" Text="{l:Tr Schedule_Hours}" />
<ui:NumberBox x:Name="HoursBox"
Width="112"
Margin="0,8,12,0"
VerticalAlignment="Center"
AutomationProperties.Name="Zu planende Stunden"
AutomationProperties.Name="{l:Tr Schedule_HoursName}"
Minimum="1"
Maximum="24"
Value="1"
@@ -69,33 +74,22 @@
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."
Content="{l:Tr Schedule_Unlimited}"
ToolTip="{l:Tr Schedule_UnlimitedTip}"
Checked="OnUnlimitedChanged"
Unchecked="OnUnlimitedChanged" />
<ui:Button x:Name="CreateButton"
Margin="0,8,8,0"
VerticalAlignment="Center"
Appearance="Primary"
Content="Plan erstellen"
Content="{l:Tr Schedule_Create}"
Click="OnCreate" />
<!-- Start: plan from now, play, and go live when laut.fm is on. Stop: ends both. Text set in code. -->
<ui:Button x:Name="StartNowButton"
MinWidth="150"
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" />
<!-- Only while laut.fm is on: sends the program live to the station, independent of the plan. -->
<ui:Button x:Name="LiveButton"
MinWidth="100"
Margin="8,8,0,0"
VerticalAlignment="Center"
Content="Live"
Icon="{ui:SymbolIcon Live24}"
ToolTip="Sendet alles, was auf Sendung ist, live auf deine laut.fm-Station."
Visibility="Collapsed"
Click="OnLiveToggle" />
Click="OnStartNowToggle" />
</WrapPanel>
<ui:InfoBar x:Name="Message"
@@ -122,7 +116,7 @@
<StackPanel VerticalAlignment="Center">
<ui:TextBlock FontTypography="Caption"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Läuft gerade" />
Text="{l:Tr Schedule_NowPlaying}" />
<DockPanel Margin="0,4,0,0">
<ContentPresenter x:Name="NowKind"
Margin="0,0,8,0"
@@ -132,7 +126,7 @@
<ui:TextBlock x:Name="NowTitle"
FontTypography="Subtitle"
TextTrimming="CharacterEllipsis"
Text="Nichts auf Sendung" />
Text="{l:Tr Schedule_NothingOnAir}" />
</DockPanel>
</StackPanel>
@@ -141,21 +135,21 @@
<ui:Button x:Name="MicButton"
MinWidth="120"
Margin="0,0,20,0"
Content="Mikro ein"
Content="{l:Tr Schedule_MicOn}"
Icon="{ui:SymbolIcon Mic24}"
ToolTip="Schaltet das Mikrofon auf Sendung, auch ĂĽber laufende Musik."
ToolTip="{l:Tr Schedule_MicTip}"
Click="OnMicToggle" />
<ui:Button x:Name="EndNowButton"
Content="Jetzt beenden"
Content="{l:Tr Schedule_EndNow}"
Icon="{ui:SymbolIcon Next24}"
ToolTip="Beendet das laufende Element sofort; das nächste startet."
ToolTip="{l:Tr Schedule_EndNowTip}"
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="{l:Tr Schedule_Start}"
Icon="{ui:SymbolIcon Play24}"
IsEnabled="False"
Click="OnPlayToggle" />
@@ -164,7 +158,7 @@
<ProgressBar x:Name="NowProgress"
Margin="0,14,0,0"
AutomationProperties.Name="Fortschritt des aktuellen Elements"
AutomationProperties.Name="{l:Tr Schedule_ProgressName}"
Maximum="1" />
<ui:TextBlock x:Name="NowTime"
Margin="0,6,0,0"
@@ -197,7 +191,7 @@
</WrapPanel.Resources>
<StackPanel Style="{StaticResource Group}">
<ui:TextBlock Style="{StaticResource Heading}" Text="Sendung (fĂĽr andere)" />
<ui:TextBlock Style="{StaticResource Heading}" Text="{l:Tr Schedule_MixListeners}" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
@@ -207,17 +201,17 @@
<RowDefinition Height="32" />
<RowDefinition Height="32" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" Text="Musik" />
<ui:TextBlock VerticalAlignment="Center" Text="{l:Tr Schedule_Music}" />
<Slider x:Name="MusicForOthersSlider" Grid.Column="1"
AutomationProperties.Name="Musik fĂĽr andere" ValueChanged="OnMixChanged" />
<ui:TextBlock Grid.Row="1" VerticalAlignment="Center" Text="Mikrofon" />
AutomationProperties.Name="{l:Tr Schedule_MusicForListenersName}" ValueChanged="OnMixChanged" />
<ui:TextBlock Grid.Row="1" VerticalAlignment="Center" Text="{l:Tr Schedule_Microphone}" />
<Slider x:Name="MicrophoneForOthersSlider" Grid.Row="1" Grid.Column="1"
AutomationProperties.Name="Mikrofon fĂĽr andere" ValueChanged="OnMixChanged" />
AutomationProperties.Name="{l:Tr Schedule_MicForListenersName}" ValueChanged="OnMixChanged" />
</Grid>
</StackPanel>
<StackPanel Style="{StaticResource Group}">
<ui:TextBlock Style="{StaticResource Heading}" Text="FĂĽr mich" />
<StackPanel Style="{StaticResource Group}" Margin="0,0,0,8">
<ui:TextBlock Style="{StaticResource Heading}" Text="{l:Tr Schedule_MixYou}" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
@@ -227,36 +221,22 @@
<RowDefinition Height="32" />
<RowDefinition Height="32" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" Text="Musik" />
<ui:TextBlock VerticalAlignment="Center" Text="{l:Tr Schedule_Music}" />
<Slider x:Name="MusicForMeSlider" Grid.Column="1"
AutomationProperties.Name="Musik fĂĽr mich" ValueChanged="OnMixChanged" />
AutomationProperties.Name="{l:Tr Schedule_MusicForMeName}"
ToolTip="{l:Tr Schedule_MusicForMeTip}"
ValueChanged="OnMixChanged" />
<CheckBox x:Name="ListenToBroadcastBox"
Grid.Row="1" Grid.ColumnSpan="2"
MinWidth="0"
Padding="8,0,0,0"
VerticalAlignment="Center"
Content="Sendung 1:1 hören"
ToolTip="Du hörst genau das, was andere hören: gleiche Lautstärke von dir, Musik und allem anderen."
Content="{l:Tr Schedule_SameAsListeners}"
ToolTip="{l:Tr Schedule_SameAsListenersTip}"
Checked="OnMixChanged"
Unchecked="OnMixChanged" />
</Grid>
</StackPanel>
<StackPanel Style="{StaticResource Group}" Margin="0,0,0,8">
<ui:TextBlock Style="{StaticResource Heading}" Text="Musik gesamt" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="32" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" Text="Lautstärke" />
<Slider x:Name="VolumeSlider" Grid.Column="1"
AutomationProperties.Name="Lautstärke der Musik gesamt" ValueChanged="OnVolumeChanged" />
</Grid>
</StackPanel>
</WrapPanel>
</StackPanel>
</Border>
@@ -271,11 +251,11 @@
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Songwunsch" />
<ui:TextBlock Grid.Column="0" VerticalAlignment="Center" Text="{l:Tr Schedule_RequestLabel}" />
<ComboBox x:Name="RequestSong"
Grid.Column="1"
Margin="12,0,0,0"
AutomationProperties.Name="GewĂĽnschter Song"
AutomationProperties.Name="{l:Tr Schedule_RequestName}"
DisplayMemberPath="Label"
IsEditable="True"
IsTextSearchEnabled="True"
@@ -284,36 +264,52 @@
<ui:Button x:Name="SwapButton"
Grid.Column="2"
Margin="12,0,0,0"
Content="Auswahl ersetzen"
Content="{l:Tr Schedule_Swap}"
Icon="{ui:SymbolIcon ArrowSwap24}"
IsEnabled="False"
Click="OnSwap" />
<StackPanel Grid.Column="4" Margin="12,0,0,0" Orientation="Horizontal">
<!-- Inserts as the one after next -->
<ui:DropDownButton x:Name="AddButton"
Margin="0,0,8,0"
Content="{l:Tr Schedule_Add}"
Icon="{ui:SymbolIcon Add24}"
ToolTip="{l:Tr Schedule_AddTip}"
IsEnabled="False">
<ui:DropDownButton.Flyout>
<ContextMenu>
<MenuItem Header="{l:Tr Schedule_AddSong}" Tag="{x:Static models:ScheduleItemKind.Song}" Click="OnAddItem" />
<MenuItem Header="{l:Tr Kind_News}" Tag="{x:Static models:ScheduleItemKind.News}" Click="OnAddItem" />
<MenuItem Header="{l:Tr Kind_Ad}" Tag="{x:Static models:ScheduleItemKind.Ad}" Click="OnAddItem" />
<MenuItem Header="{l:Tr Kind_Moderator}" Tag="{x:Static models:ScheduleItemKind.Moderator}" Click="OnAddItem" />
</ContextMenu>
</ui:DropDownButton.Flyout>
</ui:DropDownButton>
<ui:Button x:Name="MoveUpButton"
Icon="{ui:SymbolIcon ArrowUp24}"
ToolTip="Nach oben"
AutomationProperties.Name="Ausgewähltes Element nach oben verschieben"
ToolTip="{l:Tr Schedule_MoveUp}"
AutomationProperties.Name="{l:Tr Schedule_MoveUpName}"
IsEnabled="False"
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"
ToolTip="{l:Tr Schedule_MoveDown}"
AutomationProperties.Name="{l:Tr Schedule_MoveDownName}"
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"
ToolTip="{l:Tr Schedule_EditTip}"
AutomationProperties.Name="{l:Tr Schedule_EditName}"
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"
ToolTip="{l:Tr Schedule_RemoveTip}"
AutomationProperties.Name="{l:Tr Schedule_RemoveName}"
IsEnabled="False"
Click="OnRemove" />
</StackPanel>
@@ -329,42 +325,71 @@
Grid.Row="5"
SelectionMode="Single"
IsHitTestVisible="True"
AutomationProperties.Name="Sendeplan"
AutomationProperties.Name="{l:Tr Schedule_Title}"
AllowDrop="True"
SelectionChanged="OnTimelineSelectionChanged"
MouseDoubleClick="OnEditItem">
MouseDoubleClick="OnEditItem"
PreviewMouseLeftButtonDown="OnTimelineMouseDown"
PreviewMouseMove="OnTimelineMouseMove"
DragOver="OnTimelineDragOver"
DragLeave="OnTimelineDragLeave"
Drop="OnTimelineDrop">
<ui:ListView.View>
<ui:GridView>
<ui:GridViewColumn Width="36">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:SymbolIcon x:Name="OnAir"
Symbol="Play24"
Filled="True"
Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}"
AutomationProperties.Name="Auf Sendung"
Visibility="Collapsed" />
<Grid>
<ui:SymbolIcon x:Name="OnAir"
Symbol="Play24"
Filled="True"
Foreground="{DynamicResource AccentTextFillColorPrimaryBrush}"
AutomationProperties.Name="{l:Tr Schedule_OnAirName}"
Visibility="Collapsed" />
<!-- Grip on hover or selection: the row can be dragged -->
<ui:SymbolIcon x:Name="Grip"
Symbol="ReOrderDotsVertical24"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Cursor="SizeAll"
ToolTip="{l:Tr Schedule_DragTip}"
Visibility="Hidden" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsCurrent}" Value="True">
<Setter TargetName="OnAir" Property="Visibility" Value="Visible" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding CanMove}" Value="True" />
<Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListViewItem}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Grip" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding CanMove}" Value="True" />
<Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListViewItem}}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Grip" Property="Visibility" Value="Visible" />
</MultiDataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn Width="90" Header="Start">
<ui:GridViewColumn Width="90" Header="{l:Tr Schedule_Start}">
<ui:GridViewColumn.DisplayMemberBinding>
<Binding Path="Item.Start" StringFormat="HH:mm:ss" />
</ui:GridViewColumn.DisplayMemberBinding>
</ui:GridViewColumn>
<ui:GridViewColumn Width="120" Header="Typ">
<ui:GridViewColumn Width="120" Header="{l:Tr Schedule_ColType}">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Item}" ContentTemplate="{StaticResource KindChip}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn Width="360" Header="Titel" DisplayMemberBinding="{Binding Item.Title}" />
<ui:GridViewColumn Width="90" Header="Dauer">
<ui:GridViewColumn Width="360" Header="{l:Tr Schedule_ColTitle}" DisplayMemberBinding="{Binding Item.Title}" />
<ui:GridViewColumn Width="90" Header="{l:Tr Schedule_ColDuration}">
<ui:GridViewColumn.DisplayMemberBinding>
<Binding Path="Item.Duration" StringFormat="m\:ss" />
</ui:GridViewColumn.DisplayMemberBinding>
@@ -379,7 +404,7 @@
HorizontalAlignment="Center"
VerticalAlignment="Top"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Noch kein Plan. Stunden wählen und Plan erstellen."
Text="{l:Tr Schedule_Empty}"
Visibility="Visible" />
</Grid>
</Page>
+339 -85
View File
@@ -1,13 +1,19 @@
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services.Audio;
using Radiosender.Services.Localization;
using Radiosender.Services.Scheduling;
using Radiosender.Services.Streaming;
using Wpf.Ui.Controls;
using MenuItem = System.Windows.Controls.MenuItem;
namespace Radiosender.Views.Pages;
@@ -17,10 +23,8 @@ public partial class SchedulePage : Page
private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) };
private bool _loading;
private int _scrolledTo = -1;
private bool _shownPlaying;
// UI language, not Windows culture.
private static readonly System.Globalization.CultureInfo German = new("de-DE");
private bool? _shownPlaying;
private (bool OnAir, bool Live, bool Enabled)? _shownStart;
private readonly ObservableCollection<TimelineRow> _rows = [];
@@ -55,9 +59,9 @@ public partial class SchedulePage : Page
_controller.ItemFailed += OnItemFailed;
_controller.Finished += OnFinished;
_live.Problem += OnLiveProblem;
Loc.Changed += OnLanguageChanged;
_loading = true;
VolumeSlider.Value = _controller.Volume;
MusicForMeSlider.Value = _mixer.MusicForMe;
MusicForOthersSlider.Value = _mixer.MusicForOthers;
MicrophoneForOthersSlider.Value = _mixer.MicrophoneForOthers;
@@ -65,7 +69,6 @@ public partial class SchedulePage : Page
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
_loading = false;
ShowMicrophone();
ShowLive();
FillStartTimes();
if (_controller.Plan.Count > 0)
UnlimitedBox.IsChecked = _controller.IsUnlimited;
@@ -85,19 +88,38 @@ public partial class SchedulePage : Page
_controller.ItemFailed -= OnItemFailed;
_controller.Finished -= OnFinished;
_live.Problem -= OnLiveProblem;
Loc.Changed -= OnLanguageChanged;
_progressTimer.Stop();
}
// Rewrite every text set in code; the open InfoBar keeps its language.
private void OnLanguageChanged(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
{
_shownStart = null;
_shownPlaying = null;
var selected = Timeline.SelectedIndex;
_rows.Clear();
NowKind.Content = null; // same item again would not refresh the chip
ShowMicrophone();
FillStartTimes();
ShowCurrent();
if (selected < _rows.Count)
Timeline.SelectedIndex = selected;
});
// Rebuilt on dropdown open: never offers a past hour.
private void FillStartTimes()
{
var selected = (StartBox.SelectedItem as StartOption)?.Time;
var now = DateTime.Now;
var next = now.Date.AddHours(now.Hour + 1);
var options = Enumerable.Range(0, 12)
.Select(i => next.AddHours(i))
.Select(t => new StartOption(t, t.Date == now.Date ? $"{t:HH:mm}" : t.ToString("ddd HH:mm", German)))
.ToList();
List<StartOption> options =
[
new(null, Loc.T("Schedule_Now")),
.. Enumerable.Range(0, 12)
.Select(i => next.AddHours(i))
.Select(t => new StartOption(t, t.Date == now.Date ? $"{t:HH:mm}" : t.ToString("ddd HH:mm", Loc.Culture))),
];
StartBox.ItemsSource = options;
StartBox.SelectedItem = options.FirstOrDefault(o => o.Time == selected) ?? options[0];
}
@@ -107,22 +129,77 @@ public partial class SchedulePage : Page
private void OnUnlimitedChanged(object sender, RoutedEventArgs e) =>
HoursBox.IsEnabled = UnlimitedBox.IsChecked != true;
private void OnCreate(object sender, RoutedEventArgs e) => CreatePlan(startNow: false);
private static readonly string[] TimeFormats = ["H:mm", "HH:mm", "H.mm", "HH.mm", "H"];
private void OnStartNow(object sender, RoutedEventArgs e) => CreatePlan(startNow: true);
private async void CreatePlan(bool startNow)
private async void OnCreate(object sender, RoutedEventArgs e)
{
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 (ChosenStart() is not { } start)
{
if (startNow)
_controller.StartNow(hours);
else
_controller.CreatePlan(hours, start);
ShowMessage(InfoBarSeverity.Warning, Loc.T("Schedule_StartUnclearTitle"), Loc.T("Schedule_StartUnclear"));
return;
}
await RunAsync(Loc.T("Schedule_CreateFailed"),() => _controller.CreatePlan(hours, start));
}
// Typed time already passed today: tomorrow.
private DateTime? ChosenStart()
{
if (StartBox.SelectedItem is StartOption option)
return option.Time ?? DateTime.Now;
if (!TimeOnly.TryParseExact(StartBox.Text.Trim(), TimeFormats, Loc.Culture, System.Globalization.DateTimeStyles.None, out var time))
return null;
var start = DateTime.Today.Add(time.ToTimeSpan());
return start <= DateTime.Now ? start.AddDays(1) : start;
}
private void OnStartNowToggle(object sender, RoutedEventArgs e)
{
if (OnAir)
EndBroadcast();
else
StartBroadcast();
}
private bool OnAir => (_expectPlaying ?? _controller.IsPlaying) || _live.IsLive;
private async void StartBroadcast()
{
_expectPlaying = true;
if (await RunAsync(Loc.T("Schedule_StartFailed"), _controller.Start) && _live.IsEnabled)
await GoLiveAsync();
}
// Music keeps playing when laut.fm fails: a broken stream must not silence the program.
private async Task GoLiveAsync()
{
_working = true;
UpdateButtons();
try
{
await Task.Run(() => _live.StartAsync());
}
catch (Exception ex) when (ex is LiveStreamException or NAudio.MmException)
{
ShowMessage(InfoBarSeverity.Warning, Loc.T("Schedule_NoLautFm"), ex.Message);
}
finally
{
_working = false;
UpdateButtons();
}
}
private async void EndBroadcast()
{
NowKind.Visibility = Visibility.Collapsed;
_expectPlaying = false;
UpdateProgress();
await RunAsync(Loc.T("Schedule_EndBroadcastFailed"), () =>
{
_live.Stop();
if (_controller.IsPlaying)
_controller.Stop();
});
}
@@ -154,9 +231,9 @@ public partial class SchedulePage : Page
if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song)
return;
ScheduleItem? placed = null;
if (await RunAsync("Der Songwunsch konnte nicht eingeplant werden", () => placed = _controller.Swap(row.Index, song.Id)[row.Index]))
ShowMessage(InfoBarSeverity.Success, "Songwunsch eingeplant",
$"\"{placed!.Title}\" läuft um {placed.Start:HH:mm:ss}.");
if (await RunAsync(Loc.T("Schedule_SwapFailed"), () => placed = _controller.Swap(row.Index, song.Id)[row.Index]))
ShowMessage(InfoBarSeverity.Success, Loc.T("Schedule_SwapDone"),
Loc.F("Schedule_SwapDoneText", placed!.Title, placed.Start));
}
private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
@@ -165,11 +242,11 @@ public partial class SchedulePage : Page
private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1);
private void MoveSelected(int offset) => ChangeSelected(row =>
private void MoveSelected(int offset)
{
_controller.Move(row.Index, offset);
Timeline.SelectedIndex = row.Index + offset;
});
if (Timeline.SelectedItem is TimelineRow row)
MoveRow(row.Index, row.Index + offset);
}
private void OnMixChanged(object sender, RoutedEventArgs e)
{
@@ -196,7 +273,7 @@ public partial class SchedulePage : Page
}
catch (InvalidOperationException ex)
{
ShowMessage(InfoBarSeverity.Error, "Mikrofon nicht verfĂĽgbar", ex.Message);
ShowMessage(InfoBarSeverity.Error, Loc.T("Schedule_MicUnavailable"), ex.Message);
}
MicButton.IsEnabled = true;
ShowMicrophone();
@@ -205,50 +282,35 @@ public partial class SchedulePage : Page
private void ShowMicrophone()
{
var on = _microphone.IsOn;
MicButton.Content = on ? "Mikro aus" : "Mikro ein";
MicButton.Content = Loc.T(on ? "Schedule_MicOff" : "Schedule_MicOn");
MicButton.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24);
MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary;
System.Windows.Automation.AutomationProperties.SetName(MicButton, on ? "Mikrofon ausschalten, es ist auf Sendung" : "Mikrofon einschalten");
}
private async void OnLiveToggle(object sender, RoutedEventArgs e)
{
LiveButton.IsEnabled = false;
try
{
if (_live.IsLive)
{
await Task.Run(_live.Stop);
}
else
{
await Task.Run(() => _live.StartAsync());
Message.IsOpen = false;
}
}
catch (Exception ex) when (ex is LiveStreamException or NAudio.MmException)
{
ShowMessage(InfoBarSeverity.Error, "Live nicht möglich", ex.Message);
}
LiveButton.IsEnabled = true;
ShowLive();
System.Windows.Automation.AutomationProperties.SetName(MicButton, Loc.T(on ? "Schedule_MicOffName" : "Schedule_MicOnName"));
}
// Background thread.
private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() =>
{
ShowMessage(InfoBarSeverity.Warning, "laut.fm", message);
ShowLive();
UpdateButtons();
});
private void ShowLive()
private void ShowStartButton()
{
var onAir = OnAir;
var live = _live.IsLive;
// Visible while live: stoppable after laut.fm was switched off.
LiveButton.Visibility = _live.IsEnabled || live ? Visibility.Visible : Visibility.Collapsed;
LiveButton.Content = live ? "Live beenden" : "Live";
LiveButton.Appearance = live ? ControlAppearance.Danger : ControlAppearance.Secondary;
System.Windows.Automation.AutomationProperties.SetName(LiveButton, live ? "Livestream zu laut.fm beenden, er läuft" : "Livestream zu laut.fm starten");
if (_shownStart == (onAir, live, _live.IsEnabled))
return;
_shownStart = (onAir, live, _live.IsEnabled);
StartNowButton.Content = Loc.T(onAir ? "Schedule_EndBroadcast" : _live.IsEnabled ? "Schedule_GoLive" : "Schedule_StartNow");
StartNowButton.Icon = new SymbolIcon(onAir ? SymbolRegular.Stop24 : _live.IsEnabled ? SymbolRegular.Live24 : SymbolRegular.Play24);
StartNowButton.Appearance = onAir ? ControlAppearance.Danger : ControlAppearance.Secondary;
StartNowButton.ToolTip = Loc.T(onAir
? live ? "Schedule_StopLiveTip" : "Schedule_StopTip"
: _live.IsEnabled
? "Schedule_StartLiveTip"
: "Schedule_StartPlanTip");
System.Windows.Automation.AutomationProperties.SetName(StartNowButton, (string)StartNowButton.Content);
}
private void OnEndNow(object sender, RoutedEventArgs e)
@@ -260,13 +322,197 @@ public partial class SchedulePage : Page
}
catch (ScheduleException ex)
{
ShowMessage(InfoBarSeverity.Error, "Das Element konnte nicht beendet werden", ex.Message);
ShowMessage(InfoBarSeverity.Error, Loc.T("Schedule_EndItemFailed"), ex.Message);
}
ShowCurrent();
}
private void OnRemove(object sender, RoutedEventArgs e) => ChangeSelected(row => _controller.Remove(row.Index));
private void OnAddItem(object sender, RoutedEventArgs e)
{
if (sender is not MenuItem { Tag: ScheduleItemKind kind })
return;
var index = InsertPosition();
if (kind == ScheduleItemKind.Song)
{
if (RequestSong.SelectedItem is not SongOption song)
{
ShowMessage(InfoBarSeverity.Warning, Loc.T("Schedule_NoSong"), Loc.T("Schedule_NoSongText"));
return;
}
if (ChangePlan(() => _controller.Insert(index, kind, "", TimeSpan.Zero, song.Id), select: index))
FadeIn(index);
return;
}
var length = kind switch
{
ScheduleItemKind.News => TimeSpan.FromMinutes(5),
ScheduleItemKind.Ad => TimeSpan.FromSeconds(30),
_ => TimeSpan.FromMinutes(1),
};
var dialog = new ScheduleItemEditWindow(new ScheduleItem(kind, "", default, length), adding: true) { Owner = Window.GetWindow(this) };
if (dialog.ShowDialog() == true && ChangePlan(() => _controller.Insert(index, kind, dialog.ItemTitle, dialog.Duration), select: index))
FadeIn(index);
}
// Always the one after next: two after the item on air, else position 2.
private int InsertPosition() => Math.Min((_controller.IsPlaying ? _controller.CurrentIndex : 0) + 2, _rows.Count);
private Point _dragStart;
private TimelineRow? _dragRow;
private TimelineDragAdorner? _drag;
private ScrollViewer? _timelineScroll;
private long _lastScroll;
private void OnTimelineMouseDown(object sender, MouseButtonEventArgs e)
{
_dragStart = e.GetPosition(Timeline);
_dragRow = RowAt(e.OriginalSource) is { CanMove: true } row ? row : null;
}
private void OnTimelineMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed || _dragRow is not { } row)
return;
var moved = e.GetPosition(Timeline) - _dragStart;
if (Math.Abs(moved.X) < SystemParameters.MinimumHorizontalDragDistance && Math.Abs(moved.Y) < SystemParameters.MinimumVerticalDragDistance)
return;
_dragRow = null;
if (Container(row.Index) is not { } item || AdornerLayer.GetAdornerLayer(Timeline) is not { } layer)
return;
var label = row.Item.Title.Length > 0 ? $"{row.Item.KindName} · {row.Item.Title}" : row.Item.KindName;
_drag = new TimelineDragAdorner(Timeline, label, e.GetPosition(Timeline),
ThemeBrush("AccentFillColorDefaultBrush", SystemColors.HighlightBrush),
ThemeBrush("SolidBackgroundFillColorTertiaryBrush", SystemColors.WindowBrush),
ThemeBrush("TextFillColorPrimaryBrush", SystemColors.WindowTextBrush),
ThemeBrush("CardStrokeColorDefaultBrush", SystemColors.ActiveBorderBrush));
layer.Add(_drag);
item.Opacity = 0.35;
try
{
DragDrop.DoDragDrop(Timeline, row, DragDropEffects.Move);
}
finally
{
item.Opacity = 1;
layer.Remove(_drag);
_drag = null;
}
}
private void OnTimelineDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
if (e.Data.GetData(typeof(TimelineRow)) is not TimelineRow row)
{
e.Effects = DragDropEffects.None;
return;
}
var cursor = e.GetPosition(Timeline);
var y = cursor.Y;
var gap = DropGap(y, out var lineY);
e.Effects = gap >= 0 ? DragDropEffects.Move : DragDropEffects.None;
// No line where the row would stay put.
_drag?.Update(cursor, gap >= 0 && gap != row.Index && gap != row.Index + 1 ? lineY : null);
AutoScroll(y);
}
// Also raised when the cursor crosses child elements: hide the line only when really outside.
private void OnTimelineDragLeave(object sender, DragEventArgs e)
{
var at = e.GetPosition(Timeline);
if (at.X < 0 || at.Y < 0 || at.X >= Timeline.ActualWidth || at.Y >= Timeline.ActualHeight)
_drag?.Update(at, null);
}
private void OnTimelineDrop(object sender, DragEventArgs e)
{
if (e.Data.GetData(typeof(TimelineRow)) is not TimelineRow row)
return;
var gap = DropGap(e.GetPosition(Timeline).Y, out _);
var target = gap > row.Index ? gap - 1 : gap;
if (gap >= 0 && target != row.Index)
MoveRow(row.Index, target);
}
// Gap under the cursor, 0..Count: before the first row whose middle is below. -1: before the item on air.
private int DropGap(double y, out double lineY)
{
lineY = 0;
var gap = -1;
for (var i = 0; i < _rows.Count; i++)
{
if (Container(i) is not { } item)
continue;
var top = TopOf(item);
if (y < top + item.ActualHeight / 2)
{
(gap, lineY) = (i, top);
break;
}
(gap, lineY) = (i + 1, top + item.ActualHeight);
}
return _controller.IsPlaying && gap <= _controller.CurrentIndex ? -1 : gap;
}
// Edges of the rows area, not of the list: the column header sits on top.
private void AutoScroll(double y)
{
const double Edge = 24;
if (Environment.TickCount64 - _lastScroll < 120)
return;
_timelineScroll ??= Descendant<ScrollViewer>(Timeline);
var header = Descendant<System.Windows.Controls.GridViewHeaderRowPresenter>(Timeline);
var top = header is null ? 0 : header.TranslatePoint(new Point(0, header.ActualHeight), Timeline).Y;
if (y >= top && y < top + Edge)
_timelineScroll?.LineUp();
else if (y > Timeline.ActualHeight - Edge)
_timelineScroll?.LineDown();
else
return;
_lastScroll = Environment.TickCount64;
}
private void MoveRow(int from, int to)
{
if (ChangePlan(() => _controller.Move(from, to - from), select: to))
FadeIn(to);
}
// Fade only, no sliding: rows are rebuilt after a change, so old positions are not reliable.
private void FadeIn(int index)
{
if (!SystemParameters.ClientAreaAnimation)
return;
Timeline.UpdateLayout();
Container(index)?.BeginAnimation(OpacityProperty,
new DoubleAnimation(0.2, 1, TimeSpan.FromMilliseconds(300)) { EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut } });
}
private FrameworkElement? Container(int index) =>
Timeline.ItemContainerGenerator.ContainerFromIndex(index) is FrameworkElement { IsVisible: true } item ? item : null;
private double TopOf(UIElement item) => item.TranslatePoint(default, Timeline).Y;
private Brush ThemeBrush(string key, Brush fallback) => TryFindResource(key) as Brush ?? fallback;
private static T? Descendant<T>(DependencyObject parent) where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if ((child as T ?? Descendant<T>(child)) is { } found)
return found;
}
return null;
}
private TimelineRow? RowAt(object source) =>
source is DependencyObject element && ItemsControl.ContainerFromElement(Timeline, element) is System.Windows.Controls.ListViewItem item
? item.DataContext as TimelineRow
: null;
private void OnEditItem(object sender, RoutedEventArgs e)
{
if (!EditItemButton.IsEnabled || Timeline.SelectedItem is not TimelineRow row)
@@ -278,18 +524,27 @@ public partial class SchedulePage : Page
private void ChangeSelected(Action<TimelineRow> change)
{
if (Timeline.SelectedItem is not TimelineRow row)
return;
if (Timeline.SelectedItem is TimelineRow row)
ChangePlan(() => change(row));
}
private bool ChangePlan(Action change, int? select = null)
{
var changed = true;
try
{
change(row);
change();
Message.IsOpen = false;
}
catch (ScheduleException ex)
{
ShowMessage(InfoBarSeverity.Error, "Der Plan konnte nicht geändert werden", ex.Message);
ShowMessage(InfoBarSeverity.Error, Loc.T("Schedule_ChangeFailed"), ex.Message);
changed = false;
}
ShowCurrent();
if (changed && select is { } index)
Timeline.SelectedIndex = index;
return changed;
}
private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons();
@@ -301,23 +556,18 @@ public partial class SchedulePage : Page
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)
{
if (!_loading) _controller.Volume = (float)e.NewValue;
await RunAsync(Loc.T("Schedule_StartFailed"), stop ? _controller.Stop : _controller.Start);
}
// BeginInvoke, not Invoke: engine Stop waits for this pool thread -> deadlock.
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
private void OnItemFailed(object? sender, string message) =>
Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Element ĂĽbersprungen", message));
Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, Loc.T("Schedule_ItemSkipped"), message));
private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
{
ShowMessage(InfoBarSeverity.Informational, "Sendung beendet", "Der ganze Plan wurde gespielt.");
ShowMessage(InfoBarSeverity.Informational, Loc.T("Schedule_Finished"), Loc.T("Schedule_FinishedText"));
ShowCurrent();
});
@@ -331,7 +581,7 @@ public partial class SchedulePage : Page
// Replace changed rows only: keeps selection (swap target).
for (var i = 0; i < plan.Count; i++)
{
var updated = new TimelineRow(i, plan[i], i == current);
var updated = new TimelineRow(i, plan[i], i == current, !_controller.IsPlaying || i > current);
if (i == _rows.Count)
_rows.Add(updated);
else if (_rows[i] != updated)
@@ -360,11 +610,14 @@ public partial class SchedulePage : Page
{
var playing = _expectPlaying ?? _controller.IsPlaying;
PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0);
CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working;
CreateButton.IsEnabled = !_working;
// Without a plan only stopping makes sense.
StartNowButton.IsEnabled = !_working && (OnAir || _controller.Plan.Count > 0);
ShowStartButton();
if (playing != _shownPlaying)
{
_shownPlaying = playing;
PlayButton.Content = playing ? "Stopp" : "Start";
PlayButton.Content = Loc.T(playing ? "Schedule_Stop" : "Schedule_Start");
PlayButton.Icon = new SymbolIcon(playing ? SymbolRegular.Stop24 : SymbolRegular.Play24);
}
@@ -374,6 +627,7 @@ public partial class SchedulePage : Page
var current = _controller.CurrentIndex;
bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current);
var index = row?.Index ?? -1;
AddButton.IsEnabled = !_working && count > 0 && (!playing || index >= current || index < 0);
MoveUpButton.IsEnabled = Editable(index) && Editable(index - 1);
MoveDownButton.IsEnabled = Editable(index) && Editable(index + 1);
RemoveButton.IsEnabled = Editable(index);
@@ -383,12 +637,12 @@ public partial class SchedulePage : Page
var blocker = row switch
{
null => "Ein kommendes Element im Plan auswählen.",
{ Item.Kind: ScheduleItemKind.News } => "Nachrichten können nicht ersetzt werden.",
_ when playing && row.Index <= _controller.CurrentIndex => "Dieses Element ist bereits auf Sendung oder vorbei.",
null => Loc.T("Schedule_HintSelect"),
{ Item.Kind: ScheduleItemKind.News } => Loc.T("Schedule_NewsNoReplace"),
_ when playing && row.Index <= _controller.CurrentIndex => Loc.T("Schedule_HintOnAirOrOver"),
_ => null,
};
SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}.";
SwapHint.Text = blocker ?? Loc.F("Schedule_HintReplaces", row!.Item.Start);
var requested = RequestSong.SelectedItem is not null;
SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed;
SwapButton.IsEnabled = !_working && requested && blocker is null;
@@ -401,7 +655,7 @@ public partial class SchedulePage : Page
NowProgress.Value = 0;
// Here, not in ShowCurrent: engine starts waiting shortly after Start.
var waiting = _expectPlaying == false ? null : _controller.WaitingUntil;
NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung";
NowTitle.Text = waiting is { } at ? Loc.F("Schedule_WaitingUntil", at) : Loc.T("Schedule_NothingOnAir");
NowTime.Text = " ";
return;
}
@@ -419,9 +673,9 @@ public partial class SchedulePage : Page
Message.IsOpen = true;
}
private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent);
private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent, bool CanMove);
private sealed record SongOption(long Id, string Label);
private sealed record StartOption(DateTime Time, string Label);
private sealed record StartOption(DateTime? Time, string Label); // Time null: now
}
@@ -2,7 +2,8 @@
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"
xmlns:l="clr-namespace:Radiosender.Views"
Title="{l:Tr ItemEdit_Window}"
Width="400" SizeToContent="Height"
ResizeMode="NoResize"
ShowInTaskbar="False"
@@ -11,25 +12,25 @@
WindowStartupLocation="CenterOwner"
FocusManager.FocusedElement="{Binding ElementName=TitleBox}">
<StackPanel>
<ui:TitleBar x:Name="Bar" Title="Element bearbeiten" ShowMinimize="False" ShowMaximize="False" />
<ui:TitleBar x:Name="Bar" Title="{l:Tr ItemEdit_Window}" 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 Content="{l:Tr ItemEdit_TitleLabel}" Target="{Binding ElementName=TitleBox}" />
<ui:TextBox x:Name="TitleBox" Margin="0,0,0,12" PlaceholderText="{l:Tr ItemEdit_Optional}" />
<Label x:Name="DurationLabel" Content="_Länge (m:ss)" Target="{Binding ElementName=DurationBox}" />
<Label x:Name="DurationLabel" Content="{l:Tr ItemEdit_Length}" 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."
Text="{l:Tr ItemEdit_LengthError}"
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" />
<ui:Button x:Name="SaveButton" Content="{l:Tr ItemEdit_Save}" Appearance="Primary" IsDefault="True" MinWidth="90" Click="OnSave" />
<ui:Button Margin="8,0,0,0" Content="{l:Tr ItemEdit_Cancel}" IsCancel="True" MinWidth="90" />
</StackPanel>
</StackPanel>
</StackPanel>
@@ -1,6 +1,7 @@
using System.Globalization;
using System.Windows;
using Radiosender.Models;
using Radiosender.Services.Localization;
using Wpf.Ui.Controls;
namespace Radiosender.Views;
@@ -9,14 +10,16 @@ public partial class ScheduleItemEditWindow : FluentWindow
{
private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"];
public ScheduleItemEditWindow(ScheduleItem item)
// adding: new item, so every kind may set its length.
public ScheduleItemEditWindow(ScheduleItem item, bool adding = false)
{
InitializeComponent();
Title = Bar.Title = $"{item.KindName} bearbeiten";
Title = Bar.Title = Loc.F(adding ? "ItemEdit_AddTitle" : "ItemEdit_EditTitle", item.KindName);
SaveButton.Content = Loc.T(adding ? "Schedule_Add" : "ItemEdit_Save");
TitleBox.Text = item.Title;
DurationBox.Text = item.Duration.ToString(@"m\:ss");
Duration = item.Duration;
DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
DurationLabel.IsEnabled = DurationBox.IsEnabled = adding || item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
}
public string ItemTitle => TitleBox.Text;