Pass of code standardisation

This commit is contained in:
Théo Marchal 2021-09-01 02:35:37 +02:00
parent 984d2056de
commit 48b5bc5d28
9 changed files with 249 additions and 289 deletions

View File

@ -5,35 +5,35 @@ namespace unison
{ {
public partial class App : Application public partial class App : Application
{ {
private TaskbarIcon Systray; private TaskbarIcon _systray;
private HotkeyHandler Hotkeys; private HotkeyHandler _hotkeys;
private SnapcastHandler Snapcast; private SnapcastHandler _snapcast;
private MPDHandler MPD; private MPDHandler _mpd;
protected override void OnStartup(StartupEventArgs e) protected override void OnStartup(StartupEventArgs e)
{ {
base.OnStartup(e); base.OnStartup(e);
MPD = new MPDHandler(); _mpd = new MPDHandler();
Current.Properties["mpd"] = MPD; Current.Properties["mpd"] = _mpd;
Hotkeys = new HotkeyHandler(); _hotkeys = new HotkeyHandler();
Current.Properties["hotkeys"] = Hotkeys; Current.Properties["hotkeys"] = _hotkeys;
Snapcast = new SnapcastHandler(); _snapcast = new SnapcastHandler();
Current.Properties["snapcast"] = Snapcast; Current.Properties["snapcast"] = _snapcast;
Current.MainWindow = new MainWindow(); Current.MainWindow = new MainWindow();
Systray = (TaskbarIcon)FindResource("SystrayTaskbar"); _systray = (TaskbarIcon)FindResource("SystrayTaskbar");
Current.Properties["systray"] = Systray; Current.Properties["systray"] = _systray;
} }
protected override void OnExit(ExitEventArgs e) protected override void OnExit(ExitEventArgs e)
{ {
Systray.Dispose(); _systray.Dispose();
Snapcast.Stop(); _snapcast.LaunchOrExit(true);
Hotkeys.RemoveHotKeys(); _hotkeys.RemoveHotKeys();
base.OnExit(e); base.OnExit(e);
} }
} }

View File

@ -1,5 +1,4 @@
using System; using System;
using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
using System.Windows.Interop; using System.Windows.Interop;
@ -31,14 +30,15 @@ namespace unison
private const uint VK_VOLUME_DOWN = 0xAE; private const uint VK_VOLUME_DOWN = 0xAE;
private const uint VK_ENTER = 0x0D; private const uint VK_ENTER = 0x0D;
private MainWindow _appWindow;
private readonly MPDHandler _mpd;
private IntPtr _windowHandle; private IntPtr _windowHandle;
private HwndSource _source; private HwndSource _source;
private readonly MPDHandler mpd;
public HotkeyHandler() public HotkeyHandler()
{ {
mpd = (MPDHandler)Application.Current.Properties["mpd"]; _mpd = (MPDHandler)Application.Current.Properties["mpd"];
} }
public void Activate(Window win) public void Activate(Window win)
@ -65,49 +65,45 @@ namespace unison
if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID) if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID)
{ {
uint vkey = ((uint)lParam >> 16) & 0xFFFF; uint vkey = ((uint)lParam >> 16) & 0xFFFF;
MainWindow AppWindow = (MainWindow)Application.Current.MainWindow;
switch (vkey) switch (vkey)
{ {
case VK_MEDIA_NEXT_TRACK: case VK_MEDIA_NEXT_TRACK:
mpd.Next(); _mpd.Next();
break; break;
case VK_MEDIA_PREV_TRACK: case VK_MEDIA_PREV_TRACK:
mpd.Prev(); _mpd.Prev();
break; break;
case VK_VOLUME_DOWN: case VK_VOLUME_DOWN:
mpd._currentVolume -= Properties.Settings.Default.volume_offset; _mpd.VolumeDown();
if (mpd._currentVolume < 0)
mpd._currentVolume = 0;
mpd.SetVolume(mpd._currentVolume);
break; break;
case VK_VOLUME_UP: case VK_VOLUME_UP:
mpd._currentVolume += Properties.Settings.Default.volume_offset; _mpd.VolumeUp();
if (mpd._currentVolume > 100)
mpd._currentVolume = 100;
mpd.SetVolume(mpd._currentVolume);
break; break;
case VK_MEDIA_PLAY_PAUSE: case VK_MEDIA_PLAY_PAUSE:
mpd.PlayPause(); _mpd.PlayPause();
break; break;
case VK_ENTER: case VK_ENTER:
if (AppWindow.WindowState == WindowState.Minimized) if (_appWindow == null)
_appWindow = (MainWindow)Application.Current.MainWindow;
if (_appWindow.WindowState == WindowState.Minimized)
{ {
AppWindow.Show(); _appWindow.Show();
AppWindow.Activate(); _appWindow.Activate();
AppWindow.WindowState = WindowState.Normal; _appWindow.WindowState = WindowState.Normal;
} }
else else
{ {
if (AppWindow.IsActive) if (_appWindow.IsActive)
{ {
AppWindow.Hide(); _appWindow.Hide();
AppWindow.WindowState = WindowState.Minimized; _appWindow.WindowState = WindowState.Minimized;
} }
else // not minimized but not in front else // not minimized but not in front
{ {
AppWindow.Show(); _appWindow.Show();
AppWindow.Activate(); _appWindow.Activate();
AppWindow.WindowState = WindowState.Normal; _appWindow.WindowState = WindowState.Normal;
} }
} }
break; break;

View File

@ -8,7 +8,6 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Windows.Threading;
using MpcNET; using MpcNET;
using MpcNET.Commands.Database; using MpcNET.Commands.Database;
using MpcNET.Commands.Playback; using MpcNET.Commands.Playback;
@ -21,46 +20,29 @@ namespace unison
{ {
public class MPDHandler public class MPDHandler
{ {
public bool _connected; private bool _connected;
public string _version; public string _version;
public int _currentVolume; private int _currentVolume;
public bool _currentRandom; private bool _currentRandom;
public bool _currentRepeat; private bool _currentRepeat;
public bool _currentSingle; private bool _currentSingle;
public bool _currentConsume; private bool _currentConsume;
public double _currentTime; private double _currentTime;
public double _totalTime; private double _totalTime;
BitmapFrame _cover;
public event EventHandler ConnectionChanged;
public event EventHandler StatusChanged;
public event EventHandler SongChanged;
public event EventHandler CoverChanged;
public static MpdStatus BOGUS_STATUS = new MpdStatus(0, false, false, false, false, -1, -1, -1, MpdState.Unknown, -1, -1, -1, -1, TimeSpan.Zero, TimeSpan.Zero, -1, -1, -1, -1, -1, "", "");
public MpdStatus CurrentStatus { get; private set; } = BOGUS_STATUS;
IMpdFile CurrentSong { get; set; }
private MpdStatus _currentStatus;
private IMpdFile _currentSong;
private BitmapFrame _cover;
private readonly System.Timers.Timer _elapsedTimer; private readonly System.Timers.Timer _elapsedTimer;
private async void ElapsedTimer(object sender, System.Timers.ElapsedEventArgs e)
{ private event EventHandler ConnectionChanged;
if ((_currentTime < _totalTime) && (CurrentStatus.State == MpdState.Play)) private event EventHandler StatusChanged;
{ private event EventHandler SongChanged;
_currentTime += 0.5; private event EventHandler CoverChanged;
await Task.Delay(5);
}
else
{
_elapsedTimer.Stop();
}
}
private MpcConnection _connection; private MpcConnection _connection;
private MpcConnection _commandConnection; private MpcConnection _commandConnection;
private IPEndPoint _mpdEndpoint; private IPEndPoint _mpdEndpoint;
private CancellationTokenSource cancelToken; private CancellationTokenSource cancelToken;
public MPDHandler() public MPDHandler()
@ -78,6 +60,14 @@ namespace unison
CoverChanged += OnCoverChanged; CoverChanged += OnCoverChanged;
} }
private void ElapsedTimer(object sender, System.Timers.ElapsedEventArgs e)
{
if ((_currentTime < _totalTime || _totalTime == -1) && (_currentStatus.State == MpdState.Play))
_currentTime += 0.5;
else
_elapsedTimer.Stop();
}
static void OnConnectionChanged(object sender, EventArgs e) static void OnConnectionChanged(object sender, EventArgs e)
{ {
Application.Current.Dispatcher.Invoke(() => Application.Current.Dispatcher.Invoke(() =>
@ -87,8 +77,7 @@ namespace unison
SnapcastHandler Snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"]; SnapcastHandler Snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"];
Snapcast.OnConnectionChanged(sender, e); Snapcast.OnConnectionChanged(sender, e);
});
}, DispatcherPriority.ContextIdle);
} }
static void OnStatusChanged(object sender, EventArgs e) static void OnStatusChanged(object sender, EventArgs e)
@ -97,7 +86,7 @@ namespace unison
{ {
MainWindow MainWin = (MainWindow)Application.Current.MainWindow; MainWindow MainWin = (MainWindow)Application.Current.MainWindow;
MainWin.OnStatusChanged(sender, e); MainWin.OnStatusChanged(sender, e);
}, DispatcherPriority.ContextIdle); });
} }
static void OnSongChanged(object sender, EventArgs e) static void OnSongChanged(object sender, EventArgs e)
@ -106,7 +95,7 @@ namespace unison
{ {
MainWindow MainWin = (MainWindow)Application.Current.MainWindow; MainWindow MainWin = (MainWindow)Application.Current.MainWindow;
MainWin.OnSongChanged(sender, e); MainWin.OnSongChanged(sender, e);
}, DispatcherPriority.ContextIdle); });
} }
static void OnCoverChanged(object sender, EventArgs e) static void OnCoverChanged(object sender, EventArgs e)
@ -115,7 +104,7 @@ namespace unison
{ {
MainWindow MainWin = (MainWindow)Application.Current.MainWindow; MainWindow MainWin = (MainWindow)Application.Current.MainWindow;
MainWin.OnCoverChanged(sender, e); MainWin.OnCoverChanged(sender, e);
}, DispatcherPriority.ContextIdle); });
} }
private void Initialize() private void Initialize()
@ -125,7 +114,7 @@ namespace unison
public async void Connect() public async void Connect()
{ {
var token = cancelToken.Token; CancellationToken token = cancelToken.Token;
try try
{ {
_connection = await ConnectInternal(token); _connection = await ConnectInternal(token);
@ -162,6 +151,7 @@ namespace unison
if (!result.IsResponseValid) if (!result.IsResponseValid)
{ {
string mpdError = result.Response?.Result?.MpdError; string mpdError = result.Response?.Result?.MpdError;
Trace.WriteLine(mpdError);
} }
} }
@ -216,29 +206,6 @@ namespace unison
} }
} }
private async Task UpdateStatusCommand()
{
if (_commandConnection == null) return;
try
{
MpdStatus response = await SafelySendCommandAsync(new StatusCommand());
if (response != null)
{
CurrentStatus = response;
UpdateStatus();
}
else
throw new Exception();
}
catch (Exception e)
{
Trace.WriteLine($"Error in Idle connection thread: {e.Message}");
Connect();
}
}
bool _isUpdatingStatus = false; bool _isUpdatingStatus = false;
private async Task UpdateStatusAsync() private async Task UpdateStatusAsync()
{ {
@ -252,7 +219,7 @@ namespace unison
IMpdMessage<MpdStatus> response = await _connection.SendAsync(new StatusCommand()); IMpdMessage<MpdStatus> response = await _connection.SendAsync(new StatusCommand());
if (response != null && response.IsResponseValid) if (response != null && response.IsResponseValid)
{ {
CurrentStatus = response.Response.Content; _currentStatus = response.Response.Content;
UpdateStatus(); UpdateStatus();
} }
else else
@ -279,7 +246,7 @@ namespace unison
IMpdMessage<IMpdFile> response = await _connection.SendAsync(new CurrentSongCommand()); IMpdMessage<IMpdFile> response = await _connection.SendAsync(new CurrentSongCommand());
if (response != null && response.IsResponseValid) if (response != null && response.IsResponseValid)
{ {
CurrentSong = response.Response.Content; _currentSong = response.Response.Content;
UpdateSong(); UpdateSong();
} }
else else
@ -299,7 +266,7 @@ namespace unison
{ {
try try
{ {
var response = await _commandConnection.SendAsync(command); IMpdMessage<T> response = await _commandConnection.SendAsync(command);
if (!response.IsResponseValid) if (!response.IsResponseValid)
{ {
// If we have an MpdError string, only show that as the error to avoid extra noise // If we have an MpdError string, only show that as the error to avoid extra noise
@ -347,7 +314,7 @@ namespace unison
} }
catch (Exception e) catch (Exception e)
{ {
Debug.WriteLine("Exception caught while getting albumart: " + e); Trace.WriteLine("Exception caught while getting albumart: " + e);
return; return;
} }
@ -368,17 +335,17 @@ namespace unison
{ {
if (!_connected) if (!_connected)
return; return;
if (CurrentSong == null) if (_currentSong == null)
return; return;
_currentTime = CurrentStatus.Elapsed.TotalSeconds; _currentTime = _currentStatus.Elapsed.TotalSeconds;
_totalTime = CurrentSong.Time; _totalTime = _currentSong.Time;
if (!_elapsedTimer.Enabled) if (!_elapsedTimer.Enabled)
_elapsedTimer.Start(); _elapsedTimer.Start();
SongChanged?.Invoke(this, EventArgs.Empty); SongChanged?.Invoke(this, EventArgs.Empty);
string uri = Regex.Escape(CurrentSong.Path); string uri = Regex.Escape(_currentSong.Path);
GetAlbumBitmap(uri); GetAlbumBitmap(uri);
} }
@ -391,23 +358,26 @@ namespace unison
{ {
if (!_connected) if (!_connected)
return; return;
if (_currentStatus == null)
if (CurrentStatus == null)
return; return;
_currentRandom = CurrentStatus.Random; _currentRandom = _currentStatus.Random;
_currentRepeat = CurrentStatus.Repeat; _currentRepeat = _currentStatus.Repeat;
_currentConsume = CurrentStatus.Consume; _currentConsume = _currentStatus.Consume;
_currentSingle = CurrentStatus.Single; _currentSingle = _currentStatus.Single;
_currentVolume = CurrentStatus.Volume; _currentVolume = _currentStatus.Volume;
StatusChanged?.Invoke(this, EventArgs.Empty); StatusChanged?.Invoke(this, EventArgs.Empty);
} }
public IMpdFile GetCurrentSong() => CurrentSong; public IMpdFile GetCurrentSong() => _currentSong;
public MpdStatus GetStatus() => CurrentStatus; public MpdStatus GetStatus() => _currentStatus;
public BitmapFrame GetCover() => _cover; public BitmapFrame GetCover() => _cover;
public string GetVersion() => _version; public string GetVersion() => _version;
public double GetCurrentTime() => _currentTime;
public bool IsConnected() => _connected;
public bool IsPlaying() => _currentStatus?.State == MpdState.Play;
public async void Prev() => await SafelySendCommandAsync(new PreviousCommand()); public async void Prev() => await SafelySendCommandAsync(new PreviousCommand());
public async void Next() => await SafelySendCommandAsync(new NextCommand()); public async void Next() => await SafelySendCommandAsync(new NextCommand());
@ -418,9 +388,23 @@ namespace unison
public async void Single() => await SafelySendCommandAsync(new SingleCommand(!_currentSingle)); public async void Single() => await SafelySendCommandAsync(new SingleCommand(!_currentSingle));
public async void Consume() => await SafelySendCommandAsync(new ConsumeCommand(!_currentConsume)); public async void Consume() => await SafelySendCommandAsync(new ConsumeCommand(!_currentConsume));
public async void SetVolume(int value) => await SafelySendCommandAsync(new SetVolumeCommand((byte)value));
public async void SetTime(double value) => await SafelySendCommandAsync(new SeekCurCommand(value)); public async void SetTime(double value) => await SafelySendCommandAsync(new SeekCurCommand(value));
public async void SetVolume(int value) => await SafelySendCommandAsync(new SetVolumeCommand((byte)value));
public void VolumeUp()
{
_currentVolume += Properties.Settings.Default.volume_offset;
if (_currentVolume > 100)
_currentVolume = 100;
SetVolume(_currentVolume);
}
public bool IsPlaying() => CurrentStatus?.State == MpdState.Play; public void VolumeDown()
{
_currentVolume -= Properties.Settings.Default.volume_offset;
if (_currentVolume < 0)
_currentVolume = 0;
SetVolume(_currentVolume);
}
} }
} }

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Windows; using System.Windows;
using System.Windows.Threading;
using Hardcodet.Wpf.TaskbarNotification; using Hardcodet.Wpf.TaskbarNotification;
namespace unison namespace unison
@ -9,19 +8,15 @@ namespace unison
public class SnapcastHandler public class SnapcastHandler
{ {
private readonly Process _snapcast = new(); private readonly Process _snapcast = new();
public bool Started { get; private set; } public bool HasStarted { get; private set; }
public SnapcastHandler()
{
}
public void OnConnectionChanged(object sender, EventArgs e) public void OnConnectionChanged(object sender, EventArgs e)
{ {
if (Properties.Settings.Default.snapcast_startup) if (Properties.Settings.Default.snapcast_startup)
{ {
var mpd = (MPDHandler)Application.Current.Properties["mpd"]; var mpd = (MPDHandler)Application.Current.Properties["mpd"];
if (mpd._connected) if (mpd.IsConnected())
Start(); LaunchOrExit();
} }
} }
@ -35,12 +30,12 @@ namespace unison
{ {
MainWindow MainWin = (MainWindow)Application.Current.MainWindow; MainWindow MainWin = (MainWindow)Application.Current.MainWindow;
MainWin.OnSnapcastChanged(); MainWin.OnSnapcastChanged();
}, DispatcherPriority.ContextIdle); });
} }
public void Start() public void LaunchOrExit(bool ForceExit = false)
{ {
if (!Started) if (!HasStarted && !ForceExit)
{ {
_snapcast.StartInfo.FileName = Properties.Settings.Default.snapcast_path + @"\snapclient.exe"; _snapcast.StartInfo.FileName = Properties.Settings.Default.snapcast_path + @"\snapclient.exe";
_snapcast.StartInfo.Arguments = $"--host {Properties.Settings.Default.mpd_host}"; _snapcast.StartInfo.Arguments = $"--host {Properties.Settings.Default.mpd_host}";
@ -53,28 +48,18 @@ namespace unison
{ {
MessageBox.Show($"[Snapcast error]\nInvalid path: {err.Message}\n\nCurrent path: {Properties.Settings.Default.snapcast_path}\nYou can reset it in the settings if needed.", MessageBox.Show($"[Snapcast error]\nInvalid path: {err.Message}\n\nCurrent path: {Properties.Settings.Default.snapcast_path}\nYou can reset it in the settings if needed.",
"unison", MessageBoxButton.OK, MessageBoxImage.Error); "unison", MessageBoxButton.OK, MessageBoxImage.Error);
Trace.WriteLine(err.Message);
return; return;
} }
Started = true; HasStarted = true;
UpdateInterface();
} }
else else if (HasStarted)
{ {
_snapcast.Kill(); _snapcast.Kill();
Started = false; HasStarted = false;
UpdateInterface();
} }
}
public void Stop() if (!ForceExit)
{
if (Started)
{
_snapcast.Kill();
Started = false;
UpdateInterface(); UpdateInterface();
}
} }
} }
} }

View File

@ -4,8 +4,6 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:emoji="clr-namespace:Emoji.Wpf;assembly=Emoji.Wpf" xmlns:emoji="clr-namespace:Emoji.Wpf;assembly=Emoji.Wpf"
xmlns:clr="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:unison"
mc:Ignorable="d" mc:Ignorable="d"
Title="unison" Title="unison"
Closing="Window_Closing" Icon="/images/icon-full.ico" ResizeMode="CanMinimize" SizeToContent="WidthAndHeight"> Closing="Window_Closing" Icon="/images/icon-full.ico" ResizeMode="CanMinimize" SizeToContent="WidthAndHeight">

View File

@ -9,35 +9,122 @@ using System.Windows.Controls.Primitives;
namespace unison namespace unison
{ {
public partial class MainWindow : Window, INotifyPropertyChanged public partial class MainWindow : Window
{ {
public readonly Settings SettingsWindow = new Settings(); private readonly Settings _settingsWin;
private readonly DispatcherTimer _timer;
private readonly MPDHandler mpd; private readonly MPDHandler _mpd;
DispatcherTimer timer = new DispatcherTimer();
public MainWindow() public MainWindow()
{ {
InitHwnd(); InitHwnd();
InitializeComponent(); InitializeComponent();
WindowState = WindowState.Minimized; WindowState = WindowState.Minimized;
mpd = (MPDHandler)Application.Current.Properties["mpd"]; _settingsWin = new Settings();
_timer = new DispatcherTimer();
_mpd = (MPDHandler)Application.Current.Properties["mpd"];
timer.Interval = TimeSpan.FromSeconds(0.5); _timer.Interval = TimeSpan.FromSeconds(0.5);
timer.Tick += Timer_Tick; _timer.Tick += Timer_Tick;
timer.Start(); _timer.Start();
} }
private void Timer_Tick(object sender, EventArgs e) private void Timer_Tick(object sender, EventArgs e)
{ {
if (mpd.GetCurrentSong() == null) if (_mpd.GetCurrentSong() == null)
return; return;
CurrentTime.Text = FormatSeconds(mpd._currentTime); CurrentTime.Text = FormatSeconds(_mpd.GetCurrentTime());
TimeSlider.Value = mpd._currentTime / mpd.GetCurrentSong().Time * 100; TimeSlider.Value = _mpd.GetCurrentTime() / _mpd.GetCurrentSong().Time * 100;
}
public void OnConnectionChanged(object sender, EventArgs e)
{
Connection.Text = (_mpd.IsConnected() ? "✔️" : "❌") + $"{Properties.Settings.Default.mpd_host}:{Properties.Settings.Default.mpd_port}";
_settingsWin.UpdateConnectionStatus();
if (_mpd.IsConnected())
Snapcast.IsEnabled = true;
}
public void OnSongChanged(object sender, EventArgs e)
{
if (_mpd.GetCurrentSong() == null)
return;
if (!_mpd.GetCurrentSong().HasName)
SongTitle.Text = _mpd.GetCurrentSong().Title;
else
SongTitle.Text = _mpd.GetCurrentSong().Name;
SongTitle.ToolTip = _mpd.GetCurrentSong().Path;
SongArtist.Text = _mpd.GetCurrentSong().Artist;
SongAlbum.Text = _mpd.GetCurrentSong().Album;
SongGenre.Text = _mpd.GetCurrentSong().Genre;
if (_mpd.GetCurrentSong().Date != null)
SongAlbum.Text += $" ({ _mpd.GetCurrentSong().Date})";
Format.Text = _mpd.GetCurrentSong().Path.Substring(_mpd.GetCurrentSong().Path.LastIndexOf(".") + 1);
if (_mpd.GetCurrentSong().Time == -1)
{
CurrentTime.Text = "";
EndTime.Text = "";
_timer.Stop();
TimeSlider.Value = 50;
TimeSlider.IsEnabled = false;
}
else
{
if (!_timer.IsEnabled)
_timer.Start();
EndTime.Text = FormatSeconds(_mpd.GetCurrentSong().Time);
}
}
public void OnStatusChanged(object sender, EventArgs e)
{
if (_mpd.GetStatus() == null)
return;
if (VolumeSlider.Value != _mpd.GetStatus().Volume)
{
VolumeSlider.Value = _mpd.GetStatus().Volume;
VolumeSlider.ToolTip = _mpd.GetStatus().Volume;
}
if (_mpd.IsPlaying())
PlayPause.Text = "\xedb4";
else
PlayPause.Text = "\xedb5";
UpdateButton(ref BorderRandom, _mpd.GetStatus().Random);
UpdateButton(ref BorderRepeat, _mpd.GetStatus().Repeat);
UpdateButton(ref BorderSingle, _mpd.GetStatus().Single);
UpdateButton(ref BorderConsume, _mpd.GetStatus().Consume);
}
public void OnCoverChanged(object sender, EventArgs e)
{
if (_mpd.GetCover() == null)
{
NoCover.Visibility = Visibility.Visible;
Cover.Visibility = Visibility.Collapsed;
}
else if (Cover.Source != _mpd.GetCover())
{
Cover.Source = _mpd.GetCover();
Cover.Visibility = Visibility.Visible;
NoCover.Visibility = Visibility.Collapsed;
}
}
public void OnSnapcastChanged()
{
SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"];
if (snapcast.HasStarted)
SnapcastText.Text = "Stop Snapcast";
else
SnapcastText.Text = "Start Snapcast";
} }
public void UpdateButton(ref Border border, bool b) public void UpdateButton(ref Border border, bool b)
@ -56,119 +143,34 @@ namespace unison
return timespan.ToString(@"mm\:ss"); return timespan.ToString(@"mm\:ss");
} }
public void OnConnectionChanged(object sender, EventArgs e) public void Pause_Clicked(object sender, RoutedEventArgs e) => _mpd.PlayPause();
{ public void Previous_Clicked(object sender, RoutedEventArgs e) => _mpd.Prev();
Connection.Text = (mpd._connected ? "✔️" : "❌") + $"{Properties.Settings.Default.mpd_host}:{Properties.Settings.Default.mpd_port}"; public void Next_Clicked(object sender, RoutedEventArgs e) => _mpd.Next();
SettingsWindow.UpdateConnectionStatus();
if (mpd._connected)
Snapcast.IsEnabled = true;
}
public void OnSongChanged(object sender, EventArgs e) public void Random_Clicked(object sender, RoutedEventArgs e) => _mpd.Random();
{ public void Repeat_Clicked(object sender, RoutedEventArgs e) => _mpd.Repeat();
if (mpd.GetCurrentSong() == null) public void Single_Clicked(object sender, RoutedEventArgs e) => _mpd.Single();
return; public void Consume_Clicked(object sender, RoutedEventArgs e) => _mpd.Consume();
public void ChangeVolume(int value) => _mpd.SetVolume(value);
if (!mpd.GetCurrentSong().HasName)
SongTitle.Text = mpd.GetCurrentSong().Title;
else
SongTitle.Text = mpd.GetCurrentSong().Title;
SongTitle.ToolTip = mpd.GetCurrentSong().Path;
SongArtist.Text = mpd.GetCurrentSong().Artist;
SongAlbum.Text = mpd.GetCurrentSong().Album;
SongGenre.Text = mpd.GetCurrentSong().Genre;
if (mpd.GetCurrentSong().Date != null)
SongAlbum.Text += $" ({ mpd.GetCurrentSong().Date})";
Format.Text = mpd.GetCurrentSong().Path.Substring(mpd.GetCurrentSong().Path.LastIndexOf(".") + 1);
EndTime.Text = FormatSeconds(mpd.GetCurrentSong().Time);
}
public void OnStatusChanged(object sender, EventArgs e)
{
if (mpd.GetStatus() == null)
return;
if (VolumeSlider.Value != mpd._currentVolume)
{
VolumeSlider.Value = mpd._currentVolume;
VolumeSlider.ToolTip = mpd._currentVolume;
}
if (mpd.IsPlaying())
PlayPause.Text = "\xedb4";
else
PlayPause.Text = "\xedb5";
UpdateButton(ref BorderRandom, mpd._currentRandom);
UpdateButton(ref BorderRepeat, mpd._currentRepeat);
UpdateButton(ref BorderSingle, mpd._currentSingle);
UpdateButton(ref BorderConsume, mpd._currentConsume);
}
public void OnCoverChanged(object sender, EventArgs e)
{
if (mpd.GetCover() == null)
{
NoCover.Visibility = Visibility.Visible;
Cover.Visibility = Visibility.Collapsed;
}
else if (Cover.Source != mpd.GetCover())
{
Cover.Source = mpd.GetCover();
Cover.Visibility = Visibility.Visible;
NoCover.Visibility = Visibility.Collapsed;
}
}
public void OnSnapcastChanged()
{
SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"];
if (snapcast.Started)
SnapcastText.Text = "Stop Snapcast";
else
SnapcastText.Text = "Start Snapcast";
}
public void Pause_Clicked(object sender, RoutedEventArgs e) => mpd.PlayPause();
public void Previous_Clicked(object sender, RoutedEventArgs e) => mpd.Prev();
public void Next_Clicked(object sender, RoutedEventArgs e) => mpd.Next();
public void Random_Clicked(object sender, RoutedEventArgs e) => mpd.Random();
public void Repeat_Clicked(object sender, RoutedEventArgs e) => mpd.Repeat();
public void Single_Clicked(object sender, RoutedEventArgs e) => mpd.Single();
public void Consume_Clicked(object sender, RoutedEventArgs e) => mpd.Consume();
public void ChangeVolume(int value) => mpd.SetVolume(value);
public void Snapcast_Clicked(object sender, RoutedEventArgs e) public void Snapcast_Clicked(object sender, RoutedEventArgs e)
{ {
SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"]; SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"];
if (!snapcast.Started) snapcast.LaunchOrExit();
snapcast.Start();
else
snapcast.Stop();
} }
public void Settings_Clicked(object sender, RoutedEventArgs e) public void Settings_Clicked(object sender, RoutedEventArgs e)
{ {
SettingsWindow.Show(); _settingsWin.Show();
SettingsWindow.Activate(); _settingsWin.Activate();
if (SettingsWindow.WindowState == WindowState.Minimized) if (_settingsWin.WindowState == WindowState.Minimized)
SettingsWindow.WindowState = WindowState.Normal; _settingsWin.WindowState = WindowState.Normal;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
e.Cancel = true;
WindowState = WindowState.Minimized;
Hide();
} }
private void TimeSlider_DragStarted(object sender, DragStartedEventArgs e) private void TimeSlider_DragStarted(object sender, DragStartedEventArgs e)
{ {
timer.Stop(); _timer.Stop();
} }
private void TimeSlider_DragCompleted(object sender, MouseButtonEventArgs e) private void TimeSlider_DragCompleted(object sender, MouseButtonEventArgs e)
@ -176,18 +178,18 @@ namespace unison
Slider slider = (Slider)sender; Slider slider = (Slider)sender;
double SongPercentage = slider.Value; double SongPercentage = slider.Value;
double SongTime = mpd._totalTime; double SongTime = _mpd.GetCurrentSong().Time;
double SeekTime = SongPercentage / 100 * SongTime; double SeekTime = SongPercentage / 100 * SongTime;
mpd.SetTime(SeekTime); _mpd.SetTime(SeekTime);
timer.Start(); _timer.Start();
} }
private void VolumeSlider_DragCompleted(object sender, MouseButtonEventArgs e) private void VolumeSlider_DragCompleted(object sender, MouseButtonEventArgs e)
{ {
Slider slider = (Slider)sender; Slider slider = (Slider)sender;
mpd.SetVolume((int)slider.Value); _mpd.SetVolume((int)slider.Value);
slider.ToolTip = mpd._currentVolume; slider.ToolTip = (int)slider.Value;
} }
protected override void OnSourceInitialized(EventArgs e) protected override void OnSourceInitialized(EventArgs e)
@ -203,11 +205,11 @@ namespace unison
helper.EnsureHandle(); helper.EnsureHandle();
} }
public event PropertyChangedEventHandler PropertyChanged; private void Window_Closing(object sender, CancelEventArgs e)
protected virtual void OnPropertyChanged(string propertyName)
{ {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); e.Cancel = true;
WindowState = WindowState.Minimized;
Hide();
} }
} }
} }

View File

@ -4,7 +4,6 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:emoji="clr-namespace:Emoji.Wpf;assembly=Emoji.Wpf" xmlns:emoji="clr-namespace:Emoji.Wpf;assembly=Emoji.Wpf"
xmlns:local="clr-namespace:unison"
mc:Ignorable="d" mc:Ignorable="d"
Closing="Window_Closing" Title="Settings" ResizeMode="CanMinimize" Icon="/images/icon-full.ico" WindowStyle="ToolWindow" SizeToContent="WidthAndHeight"> Closing="Window_Closing" Title="Settings" ResizeMode="CanMinimize" Icon="/images/icon-full.ico" WindowStyle="ToolWindow" SizeToContent="WidthAndHeight">
<Grid> <Grid>

View File

@ -13,8 +13,8 @@ namespace unison
{ {
public partial class Settings : Window public partial class Settings : Window
{ {
private string defaultSnapcastPath = "snapclient_0.25.0-1_win64"; private readonly string defaultSnapcastPath = "snapclient_0.25.0-1_win64";
private string defaultSnapcastPort = "1704"; private readonly string defaultSnapcastPort = "1704";
public static string GetVersion => Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; public static string GetVersion => Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
@ -71,7 +71,7 @@ namespace unison
public void UpdateConnectionStatus() public void UpdateConnectionStatus()
{ {
MPDHandler mpd = (MPDHandler)Application.Current.Properties["mpd"]; MPDHandler mpd = (MPDHandler)Application.Current.Properties["mpd"];
if (mpd._connected) if (mpd.IsConnected())
ConnectionStatus.Text = "Connected to MPD " + mpd.GetVersion() + "."; ConnectionStatus.Text = "Connected to MPD " + mpd.GetVersion() + ".";
else else
ConnectionStatus.Text = "Not connected."; ConnectionStatus.Text = "Not connected.";

View File

@ -8,6 +8,8 @@ namespace unison
{ {
public class SystrayViewModel : INotifyPropertyChanged public class SystrayViewModel : INotifyPropertyChanged
{ {
public event PropertyChangedEventHandler PropertyChanged;
public static string GetAppText => "unison v" + Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; public static string GetAppText => "unison v" + Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
public static ICommand ShowWindowCommand => new DelegateCommand public static ICommand ShowWindowCommand => new DelegateCommand
@ -26,10 +28,7 @@ namespace unison
public static ICommand ExitApplicationCommand => new DelegateCommand public static ICommand ExitApplicationCommand => new DelegateCommand
{ {
CommandAction = () => CommandAction = () => Application.Current.Shutdown(),
{
Application.Current.Shutdown();
},
CanExecuteFunc = () => true CanExecuteFunc = () => true
}; };
@ -38,7 +37,7 @@ namespace unison
get get
{ {
SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"]; SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"];
return snapcast.Started ? "Stop Snapcast" : "Start Snapcast"; return snapcast.HasStarted ? "Stop Snapcast" : "Start Snapcast";
} }
} }
@ -51,7 +50,9 @@ namespace unison
CommandAction = () => CommandAction = () =>
{ {
Application.Current.Dispatcher.BeginInvoke(new Action(() => OnPropertyChanged("SnapcastText"))); Application.Current.Dispatcher.BeginInvoke(new Action(() => OnPropertyChanged("SnapcastText")));
((MainWindow)Application.Current.MainWindow).Snapcast_Clicked(null, null);
SnapcastHandler snapcast = (SnapcastHandler)Application.Current.Properties["snapcast"];
snapcast.LaunchOrExit();
}, },
CanExecuteFunc = () => true CanExecuteFunc = () => true
}; };
@ -64,17 +65,12 @@ namespace unison
{ {
return new DelegateCommand return new DelegateCommand
{ {
CommandAction = () => CommandAction = () => ((MainWindow)Application.Current.MainWindow).Settings_Clicked(null, null),
{
((MainWindow)Application.Current.MainWindow).Settings_Clicked(null, null);
},
CanExecuteFunc = () => true CanExecuteFunc = () => true
}; };
} }
} }
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string propertyName) public virtual void OnPropertyChanged(string propertyName)
{ {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));