refactor(cleanup): comments, files and outdated code

This commit is contained in:
fraujulian committed 2026-11-26 08:24:19 +01:00
1 parent 7a9ba99a27
commit e81257eca6
64 files changed
+504 -889

No files matched your search

+6 -16
View File
@@ -7,34 +7,25 @@ using System.Windows.Media;
namespace Radiosender.Views;
/// <summary>Sizes the text columns of a list so that every row can be read in full.</summary>
public static class GridColumns
{
// Cell padding on both sides plus a little air, so the text never touches the next column.
private const double Slack = 28;
// Rows use this size when no row exists yet to ask.
private const double DefaultFontSize = 14;
// The width from the XAML stays the minimum, so an empty or short list keeps its designed look.
// XAML width = minimum.
private static readonly ConditionalWeakTable<GridViewColumn, object> MinWidths = [];
// Laying out text is the slow part and the same titles come up on every refresh, so widths are remembered.
// All lists share one font. shortcut: never trimmed; clear it if libraries reach hundreds of thousands of songs.
// Assumes one shared font. shortcut: never trimmed, clear if libraries reach 100k+ songs.
private static readonly Dictionary<string, double> TextWidths = [];
/// <summary>
/// Widens each column with a <see cref="GridViewColumn.DisplayMemberBinding"/> to its longest text over
/// all rows, not only the visible ones: the lists are virtualized, so the built-in auto width would miss
/// rows that are scrolled out of view. Columns with a cell template keep their width, and so do columns
/// with a string format: those show times, which always have the same length.
/// </summary>
// Measures all rows: lists are virtualized, built-in auto width misses off-screen rows.
public static void Fit(ListView list)
{
if (list.View is not GridView view)
return;
// The rows have their own font size, so a realized row is asked rather than the list.
// Rows have own font size: ask realized row, not list.
var row = list.ItemContainerGenerator.ContainerFromIndex(0) as Control;
var typeface = new Typeface(row?.FontFamily ?? list.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
var fontSize = row?.FontSize ?? DefaultFontSize;
@@ -63,13 +54,12 @@ public static class GridColumns
}
var fitted = Math.Max(min, Math.Ceiling(widest + Slack));
if (column.Width != fitted) // setting it triggers a layout pass
if (column.Width != fitted) // set triggers layout pass
column.Width = fitted;
}
}
// Follows a simple property path such as "Item.Title". A binding on a probe element would not do:
// it only resolves once the element is part of the window.
// Reflection, not probe binding: binding resolves only once in the visual tree.
private static string Text(object? value, string[] properties)
{
foreach (var property in properties)
+2 -7
View File
@@ -3,7 +3,7 @@ using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Radiosender.Services.Settings;
using Radiosender.Views.Pages;
using Wpf.Ui.Controls;
@@ -21,16 +21,13 @@ public partial class MainWindow : FluentWindow
_schedule = schedule;
_settings = settings;
InitializeComponent();
// The navigation view asks the container for each page, so pages get their controllers injected.
RootNavigation.SetServiceProvider(services);
// Re-themes the app when the user switches the Windows theme while it runs.
Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this);
Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage));
_reminderTimer.Tick += (_, _) => RemindSpeaker();
_reminderTimer.Start();
}
// Shortly before news or moderator talk goes on air, the person at the microphone gets a heads-up.
private void RemindSpeaker()
{
var settings = _settings.Current;
@@ -43,7 +40,6 @@ public partial class MainWindow : FluentWindow
var what = item.KindName;
if (isNews ? settings.NewsAlertSound : settings.ModeratorAlertSound)
PlayBing();
// A dialog in the middle of the screen that stays until OK is clicked; the broadcast keeps running behind it.
_ = new Wpf.Ui.Controls.MessageBox
{
Title = "Gleich bist du dran.",
@@ -54,7 +50,6 @@ public partial class MainWindow : FluentWindow
}.ShowDialogAsync();
}
// A short generated tone on its own output, so it sounds over the running broadcast.
private static void PlayBing()
{
try
@@ -68,7 +63,7 @@ public partial class MainWindow : FluentWindow
}
catch (Exception ex) when (ex is NAudio.MmException or InvalidOperationException)
{
// No audio device: the dialog still reminds the speaker.
// No audio device: dialog still reminds.
}
}
}
+8 -21
View File
@@ -7,22 +7,21 @@ using Microsoft.Win32;
using NAudio.Wave;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Radiosender.Services.Providers;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
/// <summary>Adds music to the library from local files or from an online provider; both list their results in one place.</summary>
public partial class ImportPage : Page
{
private readonly OnlineImportController _online;
private readonly UploadController _upload;
private readonly ObservableCollection<SessionRow> _session = [];
// Preview has its own output, so it never interrupts a running broadcast.
// Own output: never interrupts broadcast.
private WaveOut? _previewOutput;
private MediaFoundationReader? _previewReader;
private int _previewId; // changes on every start and stop; a late callback with an old id is ignored
private int _previewId; // bumped on start/stop; late callbacks with old id ignored
private bool _uploading;
private bool _busy;
private bool _previewing;
@@ -32,7 +31,6 @@ public partial class ImportPage : Page
_online = online;
_upload = upload;
InitializeComponent();
// One provider needs no choice: the tab carries its name. Several get a list next to the search box.
var providers = _online.Providers;
ProviderBox.ItemsSource = providers;
ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1;
@@ -48,8 +46,6 @@ public partial class ImportPage : Page
};
}
// ---- From computer ----
private async void OnChooseFiles(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter, Multiselect = true };
@@ -75,7 +71,6 @@ public partial class ImportPage : Page
await UploadAsync(paths);
}
// Files are imported one by one on a pool thread; each result shows up as soon as it is known.
private async Task UploadAsync(IReadOnlyList<string> paths)
{
if (paths.Count == 0) return;
@@ -104,8 +99,6 @@ public partial class ImportPage : Page
}
}
// ---- Online providers ----
private ResultRow? Selected => Results.SelectedItem as ResultRow;
private void OnQueryKeyDown(object sender, KeyEventArgs e)
@@ -141,8 +134,7 @@ public partial class ImportPage : Page
}
}
// One button: starts the preview, or stops the running one.
// NAudio, not WPF's MediaPlayer: that one cannot open https URLs.
// NAudio, not WPF MediaPlayer: MediaPlayer cannot open https.
private async void OnPreview(object sender, RoutedEventArgs e)
{
if (_previewing)
@@ -157,7 +149,6 @@ public partial class ImportPage : Page
var id = ++_previewId;
try
{
// Connects to the server, so it runs off the UI thread. The file is streamed, nothing is saved.
var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri));
if (id != _previewId) // stopped or page left in the meantime
{
@@ -200,7 +191,7 @@ public partial class ImportPage : Page
_previewOutput = null;
_previewReader = null;
SetPreviewing(false);
// Disposing waits for the audio thread, which can sit in a network read; not on the UI thread.
// Off UI thread: Dispose waits for audio thread, may block in network read.
if (output is not null || reader is not null)
Task.Run(() =>
{
@@ -211,10 +202,9 @@ public partial class ImportPage : Page
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
// Everything selected that can still be imported.
private List<ResultRow> Importable => Results.SelectedItems.OfType<ResultRow>().Where(r => r.CanImport).ToList();
private List<ResultRow> Importable => [.. Results.SelectedItems.OfType<ResultRow>().Where(r => r.CanImport)];
// One after the other: providers limit anonymous requests, and each result shows up as soon as it is done.
// Sequential: providers rate-limit anonymous requests.
private async void OnImport(object sender, RoutedEventArgs e)
{
var rows = Importable;
@@ -240,7 +230,7 @@ public partial class ImportPage : Page
}
catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException)
{
// The database error text is technical and English; the usual cause is a song that is already stored.
// DB error text is technical English; usual cause: song already stored.
var reason = ex is MusicProviderException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden.";
_session.Insert(0, SessionRow.Failed(row.Track.Title, reason));
failed++;
@@ -283,7 +273,6 @@ public partial class ImportPage : Page
var importable = Importable.Count;
ImportButton.IsEnabled = !_busy && importable > 0;
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
// Why the selection cannot be imported ("In Bibliothek", "Keine Dauer"); shown on the disabled button.
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
}
@@ -295,8 +284,6 @@ public partial class ImportPage : Page
Message.IsOpen = true;
}
// ---- Shared ----
private void OnOpenLibrary(object sender, RoutedEventArgs e) =>
(Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage));
@@ -19,7 +19,6 @@ public partial class LibraryPage : Page
private Song? Selected => SongList.SelectedItem as Song;
// Loaded fires on every navigation to the page, so the list is reloaded from the database each time.
private void OnLoaded(object sender, RoutedEventArgs e) => Refresh();
private void OnSearchChanged(object sender, TextChangedEventArgs e) => Refresh();
@@ -4,7 +4,9 @@ using System.Windows.Controls;
using System.Windows.Threading;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
using Radiosender.Services.Audio;
using Radiosender.Services.Scheduling;
using Radiosender.Services.Streaming;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
@@ -17,16 +19,14 @@ public partial class SchedulePage : Page
private int _scrolledTo = -1;
private bool _shownPlaying;
// Weekday names in the start list follow the interface language, not the Windows setting.
// UI language, not Windows culture.
private static readonly System.Globalization.CultureInfo German = new("de-DE");
// Bound once and updated row by row, so a click never rebuilds the whole list.
private readonly ObservableCollection<TimelineRow> _rows = [];
// A controller call is running on a pool thread; the buttons that would collide with it are off.
private bool _working;
// Optimistic state: what the user just asked for, shown before the engine has caught up.
// Optimistic: shown before engine catches up.
private bool? _expectPlaying;
private readonly Microphone _microphone;
@@ -41,7 +41,7 @@ public partial class SchedulePage : Page
_mixer = output.Mixer;
InitializeComponent();
Timeline.ItemsSource = _rows;
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
// Buttons too: Finished can arrive before engine reports stopped.
_progressTimer.Tick += (_, _) =>
{
UpdateButtons();
@@ -49,7 +49,6 @@ public partial class SchedulePage : Page
};
}
// The page can be shown again while a broadcast runs, so it always rebuilds from the controller.
private void OnLoaded(object sender, RoutedEventArgs e)
{
_controller.ItemStarted += OnItemStarted;
@@ -65,13 +64,12 @@ public partial class SchedulePage : Page
ListenToBroadcastBox.IsChecked = _mixer.ListenToBroadcast;
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
_loading = false;
ShowMicrophone(); // it stays on while the user visits other pages
ShowMicrophone();
ShowLive();
FillStartTimes();
if (_controller.Plan.Count > 0)
UnlimitedBox.IsChecked = _controller.IsUnlimited;
// The library can change on other pages.
RequestSong.ItemsSource = _controller.LibrarySongs()
.OrderBy(s => s.Artist).ThenBy(s => s.Title)
.Select(s => new SongOption(s.Id, $"{(string.IsNullOrWhiteSpace(s.Artist) ? s.Title : $"{s.Artist} - {s.Title}")} ({s.Duration:m\\:ss})"))
@@ -90,7 +88,7 @@ public partial class SchedulePage : Page
_progressTimer.Stop();
}
// The next 12 full hours; rebuilt when the list opens, so it never offers a past hour.
// Rebuilt on dropdown open: never offers a past hour.
private void FillStartTimes()
{
var selected = (StartBox.SelectedItem as StartOption)?.Time;
@@ -128,10 +126,6 @@ public partial class SchedulePage : Page
});
}
/// <summary>
/// Runs a controller call that can take a moment (planning, waiting for the audio thread to stop)
/// off the UI thread, so the window stays responsive. Returns <c>false</c> after showing the error.
/// </summary>
private async Task<bool> RunAsync(string errorTitle, Action work)
{
_working = true;
@@ -171,7 +165,6 @@ public partial class SchedulePage : Page
private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1);
// The selection follows the item, so it can be moved several steps in a row.
private void MoveSelected(int offset) => ChangeSelected(row =>
{
_controller.Move(row.Index, offset);
@@ -185,7 +178,6 @@ public partial class SchedulePage : Page
_mixer.MusicForOthers = (float)MusicForOthersSlider.Value;
_mixer.MicrophoneForOthers = (float)MicrophoneForOthersSlider.Value;
_mixer.ListenToBroadcast = ListenToBroadcastBox.IsChecked == true;
// While the monitor copies the broadcast, its own music level has no effect.
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
}
@@ -195,7 +187,6 @@ public partial class SchedulePage : Page
MicButton.IsEnabled = false;
try
{
// Opening the devices can take a moment, so it runs off the UI thread.
await Task.Run(() =>
{
if (turnOn) _microphone.TurnOn();
@@ -214,7 +205,6 @@ public partial class SchedulePage : Page
private void ShowMicrophone()
{
var on = _microphone.IsOn;
// The label names the action; the red button shows that the microphone is live.
MicButton.Content = on ? "Mikro aus" : "Mikro ein";
MicButton.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24);
MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary;
@@ -232,7 +222,6 @@ public partial class SchedulePage : Page
}
else
{
// Opening the devices and the connection can take a moment, so it runs off the UI thread.
await Task.Run(() => _live.StartAsync());
Message.IsOpen = false;
}
@@ -245,7 +234,7 @@ public partial class SchedulePage : Page
ShowLive();
}
// Comes from a background thread; the stream may have ended.
// Background thread.
private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() =>
{
ShowMessage(InfoBarSeverity.Warning, "laut.fm", message);
@@ -255,7 +244,7 @@ public partial class SchedulePage : Page
private void ShowLive()
{
var live = _live.IsLive;
// Stays visible while live, so a stream can be stopped after laut.fm was switched off.
// 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;
@@ -308,7 +297,6 @@ public partial class SchedulePage : Page
private async void OnPlayToggle(object sender, RoutedEventArgs e)
{
var stop = _controller.IsPlaying;
// The button and the card switch at once; stopping waits for the audio thread in the background.
_expectPlaying = !stop;
if (stop)
NowKind.Visibility = Visibility.Collapsed;
@@ -321,7 +309,7 @@ public partial class SchedulePage : Page
if (!_loading) _controller.Volume = (float)e.NewValue;
}
// Engine events arrive on a pool thread. BeginInvoke, not Invoke: Stop waits for that thread.
// 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) =>
@@ -333,7 +321,6 @@ public partial class SchedulePage : Page
ShowCurrent();
});
// Syncs the rows with the controller; the selection is the user's swap target and is kept.
private void ShowCurrent()
{
var item = _controller.CurrentItem;
@@ -341,7 +328,7 @@ public partial class SchedulePage : Page
var plan = _controller.Plan;
var selected = Timeline.SelectedIndex;
// Rows are records: only the ones whose content changed are replaced.
// 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);
@@ -352,12 +339,10 @@ public partial class SchedulePage : Page
}
while (_rows.Count > plan.Count)
_rows.RemoveAt(_rows.Count - 1);
var rows = _rows;
GridColumns.Fit(Timeline);
Timeline.SelectedIndex = selected < rows.Count ? selected : -1;
// Follow the broadcast when it moves on; otherwise keep the user's row in view.
if (current != _scrolledTo && current >= 0 && current < rows.Count)
Timeline.ScrollIntoView(rows[current]);
Timeline.SelectedIndex = selected < _rows.Count ? selected : -1;
if (current != _scrolledTo && current >= 0 && current < _rows.Count)
Timeline.ScrollIntoView(_rows[current]);
else if (Timeline.SelectedItem is { } row)
Timeline.ScrollIntoView(row);
_scrolledTo = current;
@@ -376,7 +361,6 @@ public partial class SchedulePage : Page
var playing = _expectPlaying ?? _controller.IsPlaying;
PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0);
CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working;
// Called every timer tick, so the label and icon change only with the state.
if (playing != _shownPlaying)
{
_shownPlaying = playing;
@@ -386,7 +370,6 @@ public partial class SchedulePage : Page
var row = Timeline.SelectedItem as TimelineRow;
// Only items that are not on air or over can be moved or removed; the one on air can still be edited.
var count = _controller.Plan.Count;
var current = _controller.CurrentIndex;
bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current);
@@ -406,7 +389,6 @@ public partial class SchedulePage : Page
_ => null,
};
SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}.";
// The hint only matters once a song is chosen.
var requested = RequestSong.SelectedItem is not null;
SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed;
SwapButton.IsEnabled = !_working && requested && blocker is null;
@@ -417,7 +399,7 @@ public partial class SchedulePage : Page
if (_expectPlaying == false || _controller.CurrentItem is not { } item)
{
NowProgress.Value = 0;
// Checked here, not in ShowCurrent: the engine starts waiting a moment after Start.
// 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";
NowTime.Text = " ";
@@ -1,12 +1,12 @@
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Radiosender.Services;
using Radiosender.Services.Audio;
using Radiosender.Services.Settings;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
/// <summary>Edits <see cref="AppSettings"/>. Nothing changes until Save.</summary>
public partial class SettingsPage : Page
{
private readonly SettingsStore _store;
@@ -17,16 +17,14 @@ public partial class SettingsPage : Page
InitializeComponent();
}
// Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped.
private void OnLoaded(object sender, RoutedEventArgs e) => Show(_store.Current);
// First entry of each list: the choice that names no device.
// Index 0 of each list = no device name (null).
private const string DefaultDevice = "Windows-Standardgerät";
private const string NoDevice = "Kein eigenes Gerät";
private void Show(AppSettings settings)
{
// Read again on every visit, so a headset plugged in meanwhile shows up.
var devices = ProgramOutput.DeviceNames().ToList();
BroadcastDeviceBox.ItemsSource = devices.Prepend(DefaultDevice).ToList();
MonitorDeviceBox.ItemsSource = devices.Prepend(NoDevice).ToList();
@@ -52,11 +50,10 @@ public partial class SettingsPage : Page
OnLautFmChanged(this, new RoutedEventArgs());
}
// The access fields only matter while laut.fm is on.
private void OnLautFmChanged(object sender, RoutedEventArgs e) =>
LautFmFields.Visibility = LautFmSwitch.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
// An emptied number box counts as its default.
// Empty number box -> default.
private static AppSettings Defaults { get; } = new();
private AppSettings Read() => new()
@@ -5,10 +5,6 @@ using Wpf.Ui.Controls;
namespace Radiosender.Views;
/// <summary>
/// Dialog for the title of a news, ad or moderator item and, for news and moderator items, its length.
/// Only collects input; the caller changes the schedule.
/// </summary>
public partial class ScheduleItemEditWindow : FluentWindow
{
private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"];
@@ -20,7 +16,6 @@ public partial class ScheduleItemEditWindow : FluentWindow
TitleBox.Text = item.Title;
DurationBox.Text = item.Duration.ToString(@"m\:ss");
Duration = item.Duration;
// Ads keep their length.
DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
}
@@ -4,7 +4,6 @@ using Wpf.Ui.Controls;
namespace Radiosender.Views;
/// <summary>Dialog for the editable song metadata. Only collects input; saving is done by the caller.</summary>
public partial class SongEditWindow : FluentWindow
{
public SongEditWindow(Song song)