From ef388d82f4e40b6dbc44b2eeaea2cf5eebae3d86 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Thu, 26 Nov 2026 09:23:06 +0100 Subject: [PATCH] feat(schedule): rework the schedule page controls and timeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../Controllers/ScheduleController.cs | 95 ++-- src/Radiosender/Services/Audio/MusicPlayer.cs | 23 +- src/Radiosender/Views/Pages/SchedulePage.xaml | 187 ++++---- .../Views/Pages/SchedulePage.xaml.cs | 424 ++++++++++++++---- .../Views/ScheduleItemEditWindow.xaml | 17 +- .../Views/ScheduleItemEditWindow.xaml.cs | 9 +- tests/Radiosender.Tests/MusicPlayerTests.cs | 7 - .../ScheduleControllerTests.cs | 46 +- 8 files changed, 563 insertions(+), 245 deletions(-) diff --git a/src/Radiosender/Controllers/ScheduleController.cs b/src/Radiosender/Controllers/ScheduleController.cs index 51457bc..15fc7d5 100644 --- a/src/Radiosender/Controllers/ScheduleController.cs +++ b/src/Radiosender/Controllers/ScheduleController.cs @@ -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 _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 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. /// Library cannot fill the plan. public IReadOnlyList CreatePlan(int? hours, DateTime? start = null) @@ -79,17 +75,11 @@ public class ScheduleController { Plan = plan; IsUnlimited = hours is null; + _fromNow = from <= now; } return plan; } - /// Library cannot fill the plan. - 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. + /// No plan, position on air or over, song missing, or length not positive. + public IReadOnlyList 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); + } + /// Item on air or over. public IReadOnlyList 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 Change(int firstChanged, Action> change, bool currentAllowed = false) + private IReadOnlyList Change(int firstChanged, Action> 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 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; } diff --git a/src/Radiosender/Services/Audio/MusicPlayer.cs b/src/Radiosender/Services/Audio/MusicPlayer.cs index bb06a79..9993130 100644 --- a/src/Radiosender/Services/Audio/MusicPlayer.cs +++ b/src/Radiosender/Services/Audio/MusicPlayer.cs @@ -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 { diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml b/src/Radiosender/Views/Pages/SchedulePage.xaml index e7d4438..b3bf2cc 100644 --- a/src/Radiosender/Views/Pages/SchedulePage.xaml +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml @@ -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 @@ - + + - + + - - + Click="OnStartNowToggle" /> + Text="{l:Tr Schedule_NowPlaying}" /> + Text="{l:Tr Schedule_NothingOnAir}" /> @@ -141,21 +135,21 @@ @@ -164,7 +158,7 @@ - + @@ -207,17 +201,17 @@ - + - + AutomationProperties.Name="{l:Tr Schedule_MusicForListenersName}" ValueChanged="OnMixChanged" /> + + AutomationProperties.Name="{l:Tr Schedule_MicForListenersName}" ValueChanged="OnMixChanged" /> - - + + @@ -227,36 +221,22 @@ - + + AutomationProperties.Name="{l:Tr Schedule_MusicForMeName}" + ToolTip="{l:Tr Schedule_MusicForMeTip}" + ValueChanged="OnMixChanged" /> - - - - - - - - - - - - - - - @@ -271,11 +251,11 @@ - + + + + + + + + + + + + @@ -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"> - + + + + + + + + + + + + + + + + + + + - + - + - - + + @@ -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" /> diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs index b752fa1..80fc1dc 100644 --- a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs @@ -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 _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 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(Timeline); + var header = Descendant(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(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(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 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 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 } diff --git a/src/Radiosender/Views/ScheduleItemEditWindow.xaml b/src/Radiosender/Views/ScheduleItemEditWindow.xaml index eeb4627..b2dbb58 100644 --- a/src/Radiosender/Views/ScheduleItemEditWindow.xaml +++ b/src/Radiosender/Views/ScheduleItemEditWindow.xaml @@ -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}"> - + - diff --git a/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs b/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs index 7e01f12..484dd02 100644 --- a/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs +++ b/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs @@ -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; diff --git a/tests/Radiosender.Tests/MusicPlayerTests.cs b/tests/Radiosender.Tests/MusicPlayerTests.cs index 46086c8..7f216c1 100644 --- a/tests/Radiosender.Tests/MusicPlayerTests.cs +++ b/tests/Radiosender.Tests/MusicPlayerTests.cs @@ -102,13 +102,6 @@ public sealed class MusicPlayerTests : IDisposable Assert.False(MusicPlayer.Instance.IsPlaying); } - [Fact] - public void Volume_OutOfRange_Throws() - { - Assert.Throws(() => MusicPlayer.Instance.Volume = 1.5f); - Assert.Throws(() => MusicPlayer.Instance.Volume = -0.1f); - } - [AudioDeviceFact] public void Stop_DoesNotRaiseTrackFinished() { diff --git a/tests/Radiosender.Tests/ScheduleControllerTests.cs b/tests/Radiosender.Tests/ScheduleControllerTests.cs index b48956b..ff3eb80 100644 --- a/tests/Radiosender.Tests/ScheduleControllerTests.cs +++ b/tests/Radiosender.Tests/ScheduleControllerTests.cs @@ -100,18 +100,23 @@ public sealed class ScheduleControllerTests : IDisposable } [Fact] - public void StartNow_PlansFromThisMomentAndGoesOnAir() + public void PlanFromNow_ShiftsToTheMomentOfTheFirstStart() { AddSongs(); var hold = new TaskCompletionSource(); var controller = Create((_, token) => hold.Task.WaitAsync(token)); + var created = controller.CreatePlan(1, _now); + Assert.Equal(_now, created[0].Start); + Assert.NotEqual(ScheduleItemKind.News, created[0].Kind); + Assert.Equal(new DateTime(2026, 11, 23, 16, 0, 0), created[^1].End); - controller.StartNow(1); + _now = _now.AddSeconds(40); // the user waited before pressing Start + controller.Start(); Assert.True(controller.IsPlaying); Assert.Equal(_now, controller.Plan[0].Start); - Assert.NotEqual(ScheduleItemKind.News, controller.Plan[0].Kind); - Assert.Equal(new DateTime(2026, 11, 23, 16, 0, 0), controller.Plan[^1].End); + Assert.Equal(created[^1].End.AddSeconds(40), controller.Plan[^1].End); + Assert.Equal(created.Select(i => i.Duration), controller.Plan.Select(i => i.Duration)); controller.Stop(); } @@ -150,6 +155,39 @@ public sealed class ScheduleControllerTests : IDisposable Assert.Throws(() => controller.Move(0, -1)); } + [Fact] + public void Insert_AddsAnyKindAndShiftsTheLaterItems() + { + AddSongs(); + var controller = Create(); + var plan = controller.CreatePlan(1); + var song = _songs.GetAll()[0]; + + var withAd = controller.Insert(1, ScheduleItemKind.Ad, " Spot ", TimeSpan.FromSeconds(30)); + var withSong = controller.Insert(withAd.Count, ScheduleItemKind.Song, "", TimeSpan.Zero, song.Id); + + Assert.Equal(plan.Count + 2, withSong.Count); + Assert.Equal(new ScheduleItem(ScheduleItemKind.Ad, "Spot", plan[0].End, TimeSpan.FromSeconds(30)), withSong[1]); + Assert.Equal(plan[1].Start + TimeSpan.FromSeconds(30), withSong[2].Start); + Assert.Equal(ScheduleItemKind.Song, withSong[^1].Kind); + Assert.Equal("Artist - Song 0", withSong[^1].Title); + Assert.Equal(song.Duration, withSong[^1].Duration); + Assert.Equal(withSong[^2].End, withSong[^1].Start); + } + + [Fact] + public void Insert_RejectsMissingPlanSongAndLength() + { + AddSongs(); + var controller = Create(); + + Assert.Throws(() => controller.Insert(0, ScheduleItemKind.News, "", TimeSpan.FromMinutes(5))); + controller.CreatePlan(1); + Assert.Throws(() => controller.Insert(0, ScheduleItemKind.Moderator, "", TimeSpan.Zero)); + Assert.Throws(() => controller.Insert(0, ScheduleItemKind.Song, "", TimeSpan.Zero, songId: 999)); + Assert.Throws(() => controller.Insert(controller.Plan.Count + 1, ScheduleItemKind.Ad, "", TimeSpan.FromSeconds(30))); + } + [Fact] public void Remove_ClosesTheGap() {