Two widget pages share one process (Game Bar + a window). After CrossSound restarted, both reconnected to /events at once; with System.Net.Http on UWP the HTTP cache made the second GET wait for the first to finish, which an event stream never does, and the request had no timeout. - Move to Windows.Web.Http with the cache off and 16 connections per server - Unique query per stream request; headers must arrive within 8 s or retry - Timeouts on commands (10 s) and library calls (30 s) - Connection log in LocalState\widget.log - Skip SoundCloud's "Recently played" shelf (repeats the history) - deploy.ps1: close the widget first, update the layout in place, and re-register a dev-mode package of the same version Co-Authored-By: Claude Opus 5.5 <[email protected]>
1168 lines
46 KiB
C#
1168 lines
46 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices.WindowsRuntime;
|
|
using System.Threading.Tasks;
|
|
using CrossSoundWidget.Models;
|
|
using CrossSoundWidget.Services;
|
|
using Microsoft.Gaming.XboxGameBar;
|
|
using Windows.Data.Json;
|
|
using Windows.Storage.Streams;
|
|
using Windows.System;
|
|
using Windows.UI.Core;
|
|
using Windows.UI.ViewManagement;
|
|
using Windows.UI.Xaml;
|
|
using Windows.UI.Xaml.Automation;
|
|
using Windows.UI.Xaml.Controls;
|
|
using Windows.UI.Xaml.Input;
|
|
using Windows.UI.Xaml.Media;
|
|
using Windows.UI.Xaml.Media.Animation;
|
|
using Windows.UI.Xaml.Media.Imaging;
|
|
using Windows.UI.Xaml.Navigation;
|
|
using Windows.UI.Xaml.Shapes;
|
|
|
|
namespace CrossSoundWidget
|
|
{
|
|
public sealed partial class MediaWidget : Page
|
|
{
|
|
private enum Tab { Player, Queue, Discover, Search }
|
|
|
|
private const string GlyphPlay = "";
|
|
private const string GlyphPause = "";
|
|
private const string GlyphHeart = "";
|
|
private const string GlyphHeartFill = "";
|
|
|
|
private readonly UISettings _uiSettings = new UISettings();
|
|
private readonly DispatcherTimer _tick = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
|
private readonly DispatcherTimer _searchDebounce = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(450) };
|
|
private readonly DispatcherTimer _toastTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2.4) };
|
|
|
|
private XboxGameBarWidget _widget;
|
|
private CrossSoundClient _client;
|
|
private JsonObject _appearance;
|
|
private bool _everConnected;
|
|
|
|
// Player state and the interpolated clock: the server sends a frame only on changes, so the
|
|
// position is the last frame's plus the time since it arrived, while playing.
|
|
private PlayerState _state = PlayerState.Empty;
|
|
private readonly Stopwatch _clock = new Stopwatch();
|
|
private double _clockBase;
|
|
private double _seekTarget = -1;
|
|
private DateTime _seekGuardUntil;
|
|
private DateTime _volumeSentAt;
|
|
private double _volumeBeforeMute = 1;
|
|
|
|
private string _coverKey;
|
|
private int _coverLoad;
|
|
private string _queueSignature;
|
|
private bool _queueDirty = true;
|
|
|
|
private Tab _tab = Tab.Player;
|
|
private DateTime _discoverLoadedAt = DateTime.MinValue;
|
|
private bool _discoverLoading;
|
|
private bool _discoverFailed;
|
|
|
|
private string _searchKind = "tracks";
|
|
private int _searchSeq;
|
|
private string _lastSearch;
|
|
|
|
private MediaCard _detailCard;
|
|
private List<MediaCard> _detailTracks = new List<MediaCard>();
|
|
private int _detailSeq;
|
|
|
|
public MediaWidget()
|
|
{
|
|
InitializeComponent();
|
|
_tick.Tick += (s, e) => UpdateClock();
|
|
_searchDebounce.Tick += (s, e) => { _searchDebounce.Stop(); var ignored = RunSearchAsync(); };
|
|
_toastTimer.Tick += (s, e) => { _toastTimer.Stop(); Fade(Toast, 0, 120); };
|
|
|
|
Seek.Preview += Seek_Preview;
|
|
Seek.Committed += Seek_Committed;
|
|
VolumeBar.Preview += Volume_Preview;
|
|
VolumeBar.Committed += Volume_Committed;
|
|
VolumeBar.Step = 0.05;
|
|
}
|
|
|
|
// ================================================================ lifecycle
|
|
|
|
protected override void OnNavigatedTo(NavigationEventArgs e)
|
|
{
|
|
base.OnNavigatedTo(e);
|
|
// App.xaml.cs passes the Game Bar widget as the navigation parameter (null outside Game Bar).
|
|
_widget = e.Parameter as XboxGameBarWidget;
|
|
if (_widget != null)
|
|
{
|
|
_widget.RequestedThemeChanged += Widget_RequestedThemeChanged;
|
|
_widget.RequestedOpacityChanged += Widget_RequestedOpacityChanged;
|
|
_widget.VisibleChanged += Widget_VisibleChanged;
|
|
}
|
|
else
|
|
{
|
|
_uiSettings.ColorValuesChanged += UiSettings_ColorValuesChanged;
|
|
}
|
|
|
|
_client = new CrossSoundClient(_widget != null ? "gamebar" : "window");
|
|
_client.StateReceived += Client_StateReceived;
|
|
_client.StatusChanged += Client_StatusChanged;
|
|
_client.AppearanceReceived += Client_AppearanceReceived;
|
|
|
|
ApplyTheme();
|
|
SelectTab(Tab.Player);
|
|
SelectKind(KindTracks);
|
|
RenderState();
|
|
RenderStatus(ConnectionStatus.Connecting);
|
|
|
|
if (_widget == null || _widget.Visible) _client.Start();
|
|
}
|
|
|
|
protected override void OnNavigatedFrom(NavigationEventArgs e)
|
|
{
|
|
base.OnNavigatedFrom(e);
|
|
if (_widget != null)
|
|
{
|
|
_widget.RequestedThemeChanged -= Widget_RequestedThemeChanged;
|
|
_widget.RequestedOpacityChanged -= Widget_RequestedOpacityChanged;
|
|
_widget.VisibleChanged -= Widget_VisibleChanged;
|
|
}
|
|
_uiSettings.ColorValuesChanged -= UiSettings_ColorValuesChanged;
|
|
_tick.Stop();
|
|
if (_client != null)
|
|
{
|
|
_client.Dispose();
|
|
_client = null;
|
|
}
|
|
}
|
|
|
|
private async void Widget_VisibleChanged(XboxGameBarWidget sender, object args)
|
|
{
|
|
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
|
|
{
|
|
if (_client == null) return;
|
|
// No streaming while the widget is hidden; the server sends a fresh snapshot on reconnect.
|
|
if (_widget.Visible) _client.Start();
|
|
else { _client.Stop(); _tick.Stop(); }
|
|
});
|
|
}
|
|
|
|
private async void Widget_RequestedThemeChanged(XboxGameBarWidget sender, object args)
|
|
{
|
|
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ApplyTheme);
|
|
}
|
|
|
|
private async void Widget_RequestedOpacityChanged(XboxGameBarWidget sender, object args)
|
|
{
|
|
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ApplyPageBackground);
|
|
}
|
|
|
|
private async void UiSettings_ColorValuesChanged(UISettings sender, object args)
|
|
{
|
|
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ApplyTheme);
|
|
}
|
|
|
|
// ================================================================ theme
|
|
|
|
/// <summary>CrossSound's own look when /appearance answers; else RedWhite by Game Bar's light/dark.</summary>
|
|
private void ApplyTheme()
|
|
{
|
|
var applied = _appearance != null && ThemeManager.ApplyAppearance(_appearance);
|
|
if (!applied) ThemeManager.ApplyFallback(HostIsDark());
|
|
RequestedTheme = ThemeManager.ElementTheme;
|
|
ApplyPageBackground();
|
|
RenderState();
|
|
SelectTab(_tab);
|
|
SelectKind(KindButton(_searchKind));
|
|
}
|
|
|
|
private bool HostIsDark()
|
|
{
|
|
if (_widget != null) return _widget.RequestedTheme == ElementTheme.Dark;
|
|
var bg = _uiSettings.GetColorValue(UIColorType.Background);
|
|
return bg.R + bg.G + bg.B < 384;
|
|
}
|
|
|
|
/// <summary>The page background honors Game Bar's widget transparency setting.</summary>
|
|
private void ApplyPageBackground()
|
|
{
|
|
var bg = ((SolidColorBrush)ThemeManager.Brush("bg")).Color;
|
|
var opacity = _widget != null ? _widget.RequestedOpacity : 1.0;
|
|
PageRoot.Background = new SolidColorBrush(bg) { Opacity = opacity };
|
|
}
|
|
|
|
private void Client_AppearanceReceived(JsonObject appearance)
|
|
{
|
|
_appearance = appearance;
|
|
ApplyTheme();
|
|
}
|
|
|
|
// ================================================================ connection
|
|
|
|
private void Client_StatusChanged(ConnectionStatus status)
|
|
{
|
|
RenderStatus(status);
|
|
if (status == ConnectionStatus.Connected)
|
|
{
|
|
_everConnected = true;
|
|
if (_tab == Tab.Discover && (_discoverFailed || _discoverLoadedAt == DateTime.MinValue))
|
|
{
|
|
var ignored = LoadDiscoverAsync(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
private void RenderStatus(ConnectionStatus status)
|
|
{
|
|
switch (status)
|
|
{
|
|
case ConnectionStatus.Connected:
|
|
StatusBar.Visibility = Visibility.Collapsed;
|
|
break;
|
|
case ConnectionStatus.Connecting:
|
|
StatusTitle.Text = _everConnected ? "RECONNECTING" : "CONNECTING";
|
|
StatusDetail.Text = "Looking for CrossSound on this PC…";
|
|
RetryButton.Visibility = Visibility.Collapsed;
|
|
ShowStatusBar();
|
|
break;
|
|
default:
|
|
StatusTitle.Text = "CROSSSOUND ISN'T RUNNING";
|
|
StatusDetail.Text = "Start CrossSound. If it's already open, the widget may need its loopback exemption.";
|
|
RetryButton.Visibility = Visibility.Visible;
|
|
ShowStatusBar();
|
|
break;
|
|
}
|
|
UpdateControlsEnabled();
|
|
}
|
|
|
|
private void ShowStatusBar()
|
|
{
|
|
if (StatusBar.Visibility == Visibility.Visible) return;
|
|
StatusBar.Visibility = Visibility.Visible;
|
|
Fade(StatusBar, 1, 150, 0);
|
|
}
|
|
|
|
private void Retry_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
if (_client == null) return;
|
|
RenderStatus(ConnectionStatus.Connecting);
|
|
_client.Reconnect();
|
|
}
|
|
|
|
private bool Connected { get { return _client != null && _client.Status == ConnectionStatus.Connected; } }
|
|
|
|
// ================================================================ player state
|
|
|
|
private void Client_StateReceived(PlayerState s)
|
|
{
|
|
var sameTrack = s.Title == _state.Title && s.QueueIndex == _state.QueueIndex;
|
|
|
|
// Right after a seek, a frame sent before the server applied it would yank the thumb back.
|
|
if (_seekTarget >= 0 && DateTime.UtcNow < _seekGuardUntil && sameTrack && Math.Abs(s.Position - _seekTarget) > 3)
|
|
{
|
|
s = s.WithPosition(CurrentPosition());
|
|
}
|
|
else
|
|
{
|
|
_seekTarget = -1;
|
|
}
|
|
|
|
_state = s;
|
|
RebaseClock(s.Position);
|
|
RenderState();
|
|
}
|
|
|
|
private void RenderState()
|
|
{
|
|
var s = _state;
|
|
if (s.IsEmpty)
|
|
{
|
|
TitleText.Text = "Nothing playing";
|
|
ArtistText.Text = "Pick something in Discover or Search.";
|
|
}
|
|
else
|
|
{
|
|
TitleText.Text = string.IsNullOrEmpty(s.Title) ? "Untitled" : s.Title;
|
|
ArtistText.Text = s.Artist ?? "";
|
|
}
|
|
|
|
PlayButton.Content = s.IsPlaying ? GlyphPause : GlyphPlay;
|
|
AutomationProperties.SetName(PlayButton, s.IsPlaying ? "Pause" : "Play");
|
|
ToolTipService.SetToolTip(PlayButton, s.IsPlaying ? "Pause" : "Play");
|
|
|
|
LikeButton.Content = s.IsLiked ? GlyphHeartFill : GlyphHeart;
|
|
AutomationProperties.SetName(LikeButton, s.IsLiked ? "Unlike" : "Like");
|
|
ToolTipService.SetToolTip(LikeButton, s.IsLiked ? "Liked" : "Like");
|
|
|
|
ShuffleButton.Foreground = ThemeManager.Brush(s.Shuffle ? "text" : "iconInactive");
|
|
ShuffleButton.Background = s.Shuffle ? ThemeManager.Brush("redSoft") : new SolidColorBrush(Windows.UI.Colors.Transparent);
|
|
ToolTipService.SetToolTip(ShuffleButton, s.Shuffle ? "Shuffle: on" : "Shuffle: off");
|
|
|
|
if (s.Volume != null)
|
|
{
|
|
VolumeRow.Visibility = Visibility.Visible;
|
|
VolumeBar.Value = s.Volume.Value;
|
|
MuteButton.Content = VolumeGlyph(s.Volume.Value);
|
|
}
|
|
else
|
|
{
|
|
VolumeRow.Visibility = Visibility.Collapsed;
|
|
}
|
|
|
|
Seek.Step = s.Duration > 0 ? Math.Min(1, 5 / s.Duration) : 0.05;
|
|
DurationText.Text = s.Duration > 0 ? PlayerState.FormatClock(s.Duration) : "--:--";
|
|
|
|
var coverKey = s.IsEmpty ? "" : s.Artwork ?? "";
|
|
if (coverKey != _coverKey)
|
|
{
|
|
_coverKey = coverKey;
|
|
var ignored = LoadCoverAsync(coverKey);
|
|
}
|
|
|
|
var signature = QueueSignature(s);
|
|
if (signature != _queueSignature)
|
|
{
|
|
_queueSignature = signature;
|
|
_queueDirty = true;
|
|
}
|
|
if (_queueDirty && _tab == Tab.Queue) RenderQueue(false);
|
|
|
|
UpdateControlsEnabled();
|
|
UpdateClock();
|
|
if (s.IsPlaying && _client != null && _client.IsRunning) _tick.Start(); else _tick.Stop();
|
|
}
|
|
|
|
private void UpdateControlsEnabled()
|
|
{
|
|
var live = Connected && !_state.IsEmpty;
|
|
PlayButton.IsEnabled = live;
|
|
PrevButton.IsEnabled = live;
|
|
NextButton.IsEnabled = live;
|
|
LikeButton.IsEnabled = live;
|
|
ShuffleButton.IsEnabled = Connected;
|
|
Seek.IsEnabled = live && _state.Duration > 0;
|
|
VolumeBar.IsEnabled = Connected;
|
|
MuteButton.IsEnabled = Connected;
|
|
}
|
|
|
|
private static string VolumeGlyph(double v)
|
|
{
|
|
if (v <= 0.001) return "";
|
|
if (v < 0.34) return "";
|
|
if (v < 0.67) return "";
|
|
return "";
|
|
}
|
|
|
|
// ---------------------------------------------------------------- clock
|
|
|
|
private void RebaseClock(double position)
|
|
{
|
|
_clockBase = position;
|
|
_clock.Restart();
|
|
}
|
|
|
|
private double CurrentPosition()
|
|
{
|
|
var p = _clockBase + (_state.IsPlaying ? _clock.Elapsed.TotalSeconds : 0);
|
|
if (_state.Duration > 0) p = Math.Min(p, _state.Duration);
|
|
return Math.Max(0, p);
|
|
}
|
|
|
|
private void UpdateClock()
|
|
{
|
|
if (Seek.IsInteracting) return;
|
|
var pos = _state.IsEmpty ? 0 : CurrentPosition();
|
|
CurrentTimeText.Text = PlayerState.FormatClock(pos);
|
|
Seek.Value = _state.Duration > 0 ? pos / _state.Duration : 0;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- cover
|
|
|
|
private async Task LoadCoverAsync(string artwork)
|
|
{
|
|
var load = ++_coverLoad;
|
|
if (string.IsNullOrEmpty(artwork))
|
|
{
|
|
CoverImage.Source = null;
|
|
CoverPlaceholder.Visibility = Visibility.Visible;
|
|
return;
|
|
}
|
|
|
|
ImageSource source = null;
|
|
var bytes = _client != null ? await _client.GetArtworkAsync(artwork) : null;
|
|
if (load != _coverLoad) return;
|
|
if (bytes != null)
|
|
{
|
|
try
|
|
{
|
|
var bitmap = new BitmapImage();
|
|
using (var stream = new InMemoryRandomAccessStream())
|
|
{
|
|
await stream.WriteAsync(bytes.AsBuffer());
|
|
stream.Seek(0);
|
|
await bitmap.SetSourceAsync(stream);
|
|
}
|
|
source = bitmap;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
source = null;
|
|
}
|
|
}
|
|
if (source == null)
|
|
{
|
|
// /artwork failed (404/502): load SoundCloud's CDN directly; the URL changes per track.
|
|
Uri uri;
|
|
if (Uri.TryCreate(MediaCard.Sharpen(artwork, "t500x500"), UriKind.Absolute, out uri))
|
|
source = new BitmapImage(uri);
|
|
}
|
|
if (load != _coverLoad) return;
|
|
|
|
CoverImage.Source = source;
|
|
CoverPlaceholder.Visibility = source == null ? Visibility.Visible : Visibility.Collapsed;
|
|
Fade(CoverImage, 1, 150, 0);
|
|
}
|
|
|
|
private void CoverHost_SizeChanged(object sender, SizeChangedEventArgs e)
|
|
{
|
|
var side = Math.Max(0, Math.Min(e.NewSize.Width, e.NewSize.Height));
|
|
CoverBox.Width = side;
|
|
CoverBox.Height = side;
|
|
}
|
|
|
|
// ================================================================ player controls
|
|
|
|
private async void Play_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
if (_state.IsEmpty) return;
|
|
// Flip at once; the /events frame that follows confirms (or corrects) it.
|
|
var position = CurrentPosition();
|
|
_state = _state.WithPlaying(!_state.IsPlaying, position);
|
|
RebaseClock(position);
|
|
RenderState();
|
|
await SendAsync("playpause");
|
|
}
|
|
|
|
private async void Prev_Click(object sender, RoutedEventArgs e) { await SendAsync("prev"); }
|
|
|
|
private async void Next_Click(object sender, RoutedEventArgs e) { await SendAsync("next"); }
|
|
|
|
private async void Like_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
if (_state.IsEmpty) return;
|
|
_state = _state.WithLiked(!_state.IsLiked);
|
|
RenderState();
|
|
await SendAsync("like");
|
|
}
|
|
|
|
private async void Shuffle_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
_state = _state.WithShuffle(!_state.Shuffle);
|
|
RenderState();
|
|
await SendAsync("shuffle");
|
|
}
|
|
|
|
private void Seek_Preview(double fraction)
|
|
{
|
|
CurrentTimeText.Text = PlayerState.FormatClock(fraction * _state.Duration);
|
|
}
|
|
|
|
/// <summary>One seek per gesture: on release, on a click, or once keyboard steps settle.</summary>
|
|
private async void Seek_Committed(double fraction)
|
|
{
|
|
if (_state.IsEmpty || _state.Duration <= 0) return;
|
|
var target = Math.Round(fraction * _state.Duration, 1);
|
|
_seekTarget = target;
|
|
_seekGuardUntil = DateTime.UtcNow.AddSeconds(2);
|
|
_state = _state.WithPosition(target);
|
|
RebaseClock(target);
|
|
UpdateClock();
|
|
await SendAsync("seek", "position", JsonValue.CreateNumberValue(target));
|
|
}
|
|
|
|
private void Volume_Preview(double value)
|
|
{
|
|
MuteButton.Content = VolumeGlyph(value);
|
|
// Live while dragging, but at most ~8 commands a second.
|
|
if ((DateTime.UtcNow - _volumeSentAt).TotalMilliseconds < 120) return;
|
|
_volumeSentAt = DateTime.UtcNow;
|
|
var ignored = SendAsync("volume", "value", JsonValue.CreateNumberValue(Math.Round(value, 3)), false);
|
|
}
|
|
|
|
private async void Volume_Committed(double value)
|
|
{
|
|
_state = _state.WithVolume(value);
|
|
MuteButton.Content = VolumeGlyph(value);
|
|
_volumeSentAt = DateTime.UtcNow;
|
|
await SendAsync("volume", "value", JsonValue.CreateNumberValue(Math.Round(value, 3)));
|
|
}
|
|
|
|
private async void Mute_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
var current = _state.Volume ?? 1;
|
|
double target;
|
|
if (current > 0.001) { _volumeBeforeMute = current; target = 0; }
|
|
else target = _volumeBeforeMute > 0.001 ? _volumeBeforeMute : 1;
|
|
_state = _state.WithVolume(target);
|
|
RenderState();
|
|
await SendAsync("volume", "value", JsonValue.CreateNumberValue(Math.Round(target, 3)));
|
|
}
|
|
|
|
private Task<bool> SendAsync(string action)
|
|
{
|
|
return SendAsync(action, null);
|
|
}
|
|
|
|
private Task<bool> SendAsync(string action, string key, IJsonValue value, bool reportFailure = true)
|
|
{
|
|
var data = new JsonObject();
|
|
data[key] = value;
|
|
return SendAsync(action, data, reportFailure);
|
|
}
|
|
|
|
private async Task<bool> SendAsync(string action, JsonObject data, bool reportFailure = true)
|
|
{
|
|
if (_client == null) return false;
|
|
var ok = await _client.CommandAsync(action, data);
|
|
if (!ok && reportFailure) ShowToast("CrossSound didn't answer. Is it running?");
|
|
return ok;
|
|
}
|
|
|
|
// ================================================================ tabs
|
|
|
|
private void Tab_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
if (sender == TabPlayer) SelectTab(Tab.Player);
|
|
else if (sender == TabQueue) SelectTab(Tab.Queue);
|
|
else if (sender == TabDiscover) SelectTab(Tab.Discover);
|
|
else if (sender == TabSearch) SelectTab(Tab.Search);
|
|
}
|
|
|
|
private void SelectTab(Tab tab)
|
|
{
|
|
var changed = tab != _tab;
|
|
_tab = tab;
|
|
if (changed) CloseDetail();
|
|
|
|
StyleTab(TabPlayer, tab == Tab.Player);
|
|
StyleTab(TabQueue, tab == Tab.Queue);
|
|
StyleTab(TabDiscover, tab == Tab.Discover);
|
|
StyleTab(TabSearch, tab == Tab.Search);
|
|
|
|
ShowPanel(PlayerPanel, tab == Tab.Player, changed);
|
|
ShowPanel(QueuePanel, tab == Tab.Queue, changed);
|
|
ShowPanel(DiscoverPanel, tab == Tab.Discover, changed);
|
|
ShowPanel(SearchPanel, tab == Tab.Search, changed);
|
|
|
|
if (!changed) return;
|
|
if (tab == Tab.Queue) RenderQueue(true);
|
|
else if (tab == Tab.Discover)
|
|
{
|
|
var stale = (DateTime.UtcNow - _discoverLoadedAt).TotalMinutes > 10;
|
|
if (_discoverFailed || stale) { var ignored = LoadDiscoverAsync(true); }
|
|
}
|
|
else if (tab == Tab.Search) SearchBox.Focus(FocusState.Programmatic);
|
|
}
|
|
|
|
private static void StyleTab(Button tab, bool active)
|
|
{
|
|
tab.Foreground = ThemeManager.Brush(active ? "text" : "textMuted");
|
|
tab.BorderBrush = active ? ThemeManager.Brush("red") : new SolidColorBrush(Windows.UI.Colors.Transparent);
|
|
}
|
|
|
|
private void ShowPanel(UIElement panel, bool show, bool animate)
|
|
{
|
|
panel.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
|
|
if (show && animate) Fade(panel, 1, 150, 0);
|
|
}
|
|
|
|
// ================================================================ queue
|
|
|
|
private static string QueueSignature(PlayerState s)
|
|
{
|
|
if (s.Queue.Count == 0) return "0";
|
|
return s.Queue.Count + "|" + s.QueueIndex + "|" + s.Queue[0].Id + "|" + s.Queue[s.Queue.Count - 1].Id;
|
|
}
|
|
|
|
private void RenderQueue(bool scrollToCurrent)
|
|
{
|
|
_queueDirty = false;
|
|
QueueList.Children.Clear();
|
|
var queue = _state.Queue;
|
|
QueueEmpty.Visibility = queue.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
|
|
QueueHeader.Text = queue.Count == 0 ? "QUEUE"
|
|
: "QUEUE · " + Plural(queue.Count, "TRACK");
|
|
|
|
Button current = null;
|
|
for (var i = 0; i < queue.Count; i++)
|
|
{
|
|
var item = queue[i];
|
|
var index = i;
|
|
var isCurrent = i == _state.QueueIndex;
|
|
var row = BuildRow(
|
|
MediaCard.Sharpen(item.Artwork, "t200x200"), false,
|
|
item.Title, item.Artist,
|
|
item.DurationMs > 0 ? PlayerState.FormatClock(item.DurationMs / 1000) : "",
|
|
isCurrent, null);
|
|
AutomationProperties.SetName(row, item.Title + ", " + item.Artist);
|
|
row.Click += async (s, e) =>
|
|
{
|
|
if (index == _state.QueueIndex) { SelectTab(Tab.Player); return; }
|
|
await SendAsync("playIndex", "index", JsonValue.CreateNumberValue(index));
|
|
};
|
|
QueueList.Children.Add(row);
|
|
if (isCurrent) current = row;
|
|
}
|
|
|
|
if (scrollToCurrent && current != null)
|
|
{
|
|
var target = current;
|
|
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
|
|
{
|
|
try
|
|
{
|
|
var y = target.TransformToVisual(QueueList).TransformPoint(new Windows.Foundation.Point(0, 0)).Y;
|
|
QueueScroll.ChangeView(null, Math.Max(0, y - 48), null, true);
|
|
}
|
|
catch (Exception) { }
|
|
});
|
|
}
|
|
}
|
|
|
|
// ================================================================ discover
|
|
|
|
private void Refresh_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
var ignored = LoadDiscoverAsync(true);
|
|
}
|
|
|
|
private async Task LoadDiscoverAsync(bool force)
|
|
{
|
|
if (_discoverLoading || _client == null) return;
|
|
if (!force && !_discoverFailed && _discoverLoadedAt != DateTime.MinValue) return;
|
|
_discoverLoading = true;
|
|
DiscoverBusy.IsActive = true;
|
|
DiscoverMessage.Visibility = Visibility.Collapsed;
|
|
RefreshButton.IsEnabled = false;
|
|
|
|
try
|
|
{
|
|
var historyTask = _client.GetJsonAsync("/discover/history?limit=20");
|
|
var mixedTask = _client.GetJsonAsync("/discover/mixed?limit=10");
|
|
var history = await historyTask;
|
|
var mixed = await mixedTask;
|
|
|
|
if (!history.Ok && !mixed.Ok)
|
|
{
|
|
_discoverFailed = true;
|
|
DiscoverList.Children.Clear();
|
|
ShowMessage(DiscoverMessage, DiscoverMessageText, LibraryMessage(history.Status == LibraryStatus.SignedOut ? history : mixed));
|
|
return;
|
|
}
|
|
|
|
var sections = new List<KeyValuePair<string, List<MediaCard>>>();
|
|
if (history.Ok)
|
|
{
|
|
var cards = Items(history.Value).Select(v => MediaCard.FromHistoryRow(Json.AsObject(v))).Where(c => c != null).ToList();
|
|
if (cards.Count > 0) sections.Add(new KeyValuePair<string, List<MediaCard>>("RECENTLY PLAYED", cards));
|
|
}
|
|
if (mixed.Ok)
|
|
{
|
|
foreach (var shelfValue in Items(mixed.Value))
|
|
{
|
|
var shelf = Json.AsObject(shelfValue);
|
|
if (shelf == null) continue;
|
|
var title = Json.FirstStr(shelf, "title", "description") ?? "MORE";
|
|
// SoundCloud's own "Recently played" shelf repeats the history above, one row per play.
|
|
if (history.Ok && string.Equals(title, "Recently played", StringComparison.OrdinalIgnoreCase)) continue;
|
|
var items = Json.Get(shelf, "items");
|
|
var cards = Items(items).Select(v => MediaCard.Parse(Json.AsObject(v))).Where(c => c != null).ToList();
|
|
if (cards.Count > 0) sections.Add(new KeyValuePair<string, List<MediaCard>>(title.ToUpperInvariant(), cards));
|
|
}
|
|
}
|
|
|
|
DiscoverList.Children.Clear();
|
|
foreach (var section in sections)
|
|
{
|
|
DiscoverList.Children.Add(SectionLabel(section.Key));
|
|
foreach (var card in section.Value) DiscoverList.Children.Add(BuildCardRow(card));
|
|
}
|
|
_discoverFailed = false;
|
|
_discoverLoadedAt = DateTime.UtcNow;
|
|
if (sections.Count == 0) ShowMessage(DiscoverMessage, DiscoverMessageText, "Nothing to show yet. Play something in CrossSound and it'll appear here.");
|
|
else Fade(DiscoverList, 1, 150, 0);
|
|
}
|
|
finally
|
|
{
|
|
_discoverLoading = false;
|
|
DiscoverBusy.IsActive = false;
|
|
RefreshButton.IsEnabled = true;
|
|
}
|
|
}
|
|
|
|
// ================================================================ search
|
|
|
|
private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
|
|
{
|
|
SearchPlaceholder.Visibility = SearchBox.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
|
|
_searchDebounce.Stop();
|
|
_searchDebounce.Start();
|
|
}
|
|
|
|
private void SearchBox_KeyDown(object sender, KeyRoutedEventArgs e)
|
|
{
|
|
if (e.Key != VirtualKey.Enter) return;
|
|
e.Handled = true;
|
|
_searchDebounce.Stop();
|
|
_lastSearch = null;
|
|
var ignored = RunSearchAsync();
|
|
}
|
|
|
|
private void Kind_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
var button = (Button)sender;
|
|
if ((string)button.Tag == _searchKind) return;
|
|
SelectKind(button);
|
|
_lastSearch = null;
|
|
var ignored = RunSearchAsync();
|
|
}
|
|
|
|
private Button KindButton(string kind)
|
|
{
|
|
foreach (var b in new[] { KindTracks, KindPlaylists, KindAlbums, KindUsers })
|
|
if ((string)b.Tag == kind) return b;
|
|
return KindTracks;
|
|
}
|
|
|
|
private void SelectKind(Button selected)
|
|
{
|
|
_searchKind = (string)selected.Tag;
|
|
foreach (var b in new[] { KindTracks, KindPlaylists, KindAlbums, KindUsers }) StyleTab(b, b == selected);
|
|
}
|
|
|
|
private async Task RunSearchAsync()
|
|
{
|
|
if (_client == null) return;
|
|
var q = SearchBox.Text.Trim();
|
|
var key = _searchKind + "\n" + q;
|
|
if (key == _lastSearch) return;
|
|
_lastSearch = key;
|
|
var seq = ++_searchSeq;
|
|
|
|
if (q.Length == 0)
|
|
{
|
|
SearchList.Children.Clear();
|
|
SearchBusy.IsActive = false;
|
|
ShowMessage(SearchMessage, "Find tracks, playlists, albums and artists.");
|
|
return;
|
|
}
|
|
|
|
SearchBusy.IsActive = true;
|
|
SearchMessage.Visibility = Visibility.Collapsed;
|
|
var result = await _client.GetJsonAsync("/search?q=" + Uri.EscapeDataString(q) + "&kind=" + _searchKind + "&limit=20");
|
|
if (seq != _searchSeq) return;
|
|
SearchBusy.IsActive = false;
|
|
SearchList.Children.Clear();
|
|
|
|
if (!result.Ok)
|
|
{
|
|
_lastSearch = null; // let the same query be retried
|
|
ShowMessage(SearchMessage, LibraryMessage(result));
|
|
return;
|
|
}
|
|
var cards = Items(result.Value).Select(v => MediaCard.Parse(Json.AsObject(v))).Where(c => c != null).ToList();
|
|
if (cards.Count == 0)
|
|
{
|
|
ShowMessage(SearchMessage, "No results for “" + q + "”.");
|
|
return;
|
|
}
|
|
foreach (var card in cards) SearchList.Children.Add(BuildCardRow(card));
|
|
SearchScroll.ChangeView(null, 0, null, true);
|
|
Fade(SearchList, 1, 150, 0);
|
|
}
|
|
|
|
// ================================================================ detail
|
|
|
|
private void OpenDetail(MediaCard card)
|
|
{
|
|
_detailCard = card;
|
|
DetailTitle.Text = card.Title;
|
|
DetailSubtitle.Text = !string.IsNullOrEmpty(card.Subtitle) ? card.Subtitle : card.Meta;
|
|
PlayAllButton.Visibility = Visibility.Visible;
|
|
PlayAllButton.IsEnabled = CanPlayWithoutTracks(card);
|
|
DetailPanel.Visibility = Visibility.Visible;
|
|
Fade(DetailPanel, 1, 150, 0);
|
|
var ignored = LoadDetailAsync();
|
|
}
|
|
|
|
private void CloseDetail()
|
|
{
|
|
_detailSeq++;
|
|
_detailCard = null;
|
|
DetailPanel.Visibility = Visibility.Collapsed;
|
|
DetailList.Children.Clear();
|
|
}
|
|
|
|
private void DetailBack_Click(object sender, RoutedEventArgs e) { CloseDetail(); }
|
|
|
|
private void DetailRetry_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
var ignored = LoadDetailAsync();
|
|
}
|
|
|
|
private async Task LoadDetailAsync()
|
|
{
|
|
var card = _detailCard;
|
|
if (card == null || _client == null) return;
|
|
var seq = ++_detailSeq;
|
|
_detailTracks = new List<MediaCard>();
|
|
DetailList.Children.Clear();
|
|
DetailMessage.Visibility = Visibility.Collapsed;
|
|
DetailBusy.IsActive = true;
|
|
|
|
var tracks = await LoadTracksAsync(card);
|
|
var failure = _lastLoadFailure;
|
|
if (seq != _detailSeq) return;
|
|
DetailBusy.IsActive = false;
|
|
|
|
_detailTracks = tracks;
|
|
PlayAllButton.IsEnabled = tracks.Count > 0 || CanPlayWithoutTracks(card);
|
|
if (tracks.Count == 0)
|
|
{
|
|
ShowMessage(DetailMessage, DetailMessageText, failure != null ? LibraryMessage(failure) : "No tracks here.");
|
|
return;
|
|
}
|
|
|
|
for (var i = 0; i < tracks.Count; i++)
|
|
{
|
|
var t = tracks[i];
|
|
var index = i;
|
|
var row = BuildRow(t.ArtUrl, false, t.Title, t.Subtitle, t.Meta, false, null);
|
|
AutomationProperties.SetName(row, "Play " + t.Title);
|
|
row.Click += async (s, e) => await PlayFromDetailAsync(index);
|
|
DetailList.Children.Add(row);
|
|
}
|
|
DetailScroll.ChangeView(null, 0, null, true);
|
|
Fade(DetailList, 1, 150, 0);
|
|
}
|
|
|
|
/// <summary>Why the last LoadTracksAsync came back empty, if a request failed.</summary>
|
|
private LibraryResult _lastLoadFailure;
|
|
|
|
/// <summary>The tracks behind a card, hydrating stub ids through /tracks/batch.</summary>
|
|
private async Task<List<MediaCard>> LoadTracksAsync(MediaCard card)
|
|
{
|
|
_lastLoadFailure = null;
|
|
var idText = card.Id != null ? Json.FormatLong(card.Id.Value) : null;
|
|
LibraryResult r;
|
|
|
|
switch (card.Kind)
|
|
{
|
|
case CardKind.User:
|
|
if (idText == null) return new List<MediaCard>();
|
|
r = await _client.GetJsonAsync("/user/" + idText + "/tracks?limit=50");
|
|
return TracksFrom(r);
|
|
|
|
case CardKind.Station:
|
|
r = await _client.GetJsonAsync(!string.IsNullOrEmpty(card.Urn)
|
|
? "/station?urn=" + Uri.EscapeDataString(card.Urn)
|
|
: "/station?url=" + Uri.EscapeDataString(card.Permalink ?? ""));
|
|
return TracksFrom(r);
|
|
|
|
case CardKind.Playlist:
|
|
case CardKind.Album:
|
|
if (idText != null)
|
|
{
|
|
r = await _client.GetJsonAsync("/playlist/" + idText);
|
|
if (!r.Ok) { _lastLoadFailure = r; return new List<MediaCard>(); }
|
|
var full = MediaCard.Parse(Json.AsObject(r.Value));
|
|
if (full != null) return await HydrateAsync(full);
|
|
}
|
|
return await HydrateAsync(card);
|
|
|
|
default:
|
|
if (card.TrackIds.Count == 0 && !string.IsNullOrEmpty(card.Permalink))
|
|
{
|
|
r = await _client.GetJsonAsync("/resolve?url=" + Uri.EscapeDataString(card.Permalink));
|
|
if (!r.Ok) { _lastLoadFailure = r; return new List<MediaCard>(); }
|
|
var resolved = MediaCard.Parse(Json.AsObject(r.Value));
|
|
if (resolved != null) return await HydrateAsync(resolved);
|
|
}
|
|
return await HydrateAsync(card);
|
|
}
|
|
}
|
|
|
|
private List<MediaCard> TracksFrom(LibraryResult r)
|
|
{
|
|
if (!r.Ok) { _lastLoadFailure = r; return new List<MediaCard>(); }
|
|
return Items(r.Value).Select(v => MediaCard.AsTrack(Json.AsObject(v))).Where(c => c != null && c.Id != null).ToList();
|
|
}
|
|
|
|
/// <summary>The card's tracks in order: inline ones as they are, stubs fetched (first 200).</summary>
|
|
private async Task<List<MediaCard>> HydrateAsync(MediaCard card)
|
|
{
|
|
var ids = card.TrackIds.Take(200).ToList();
|
|
var byId = new Dictionary<long, MediaCard>(card.InlineTracks);
|
|
var missing = ids.Where(id => !byId.ContainsKey(id)).Distinct().ToList();
|
|
if (missing.Count > 0)
|
|
{
|
|
var r = await _client.GetJsonAsync("/tracks/batch?ids=" + string.Join(",", missing.Select(Json.FormatLong)));
|
|
if (r.Ok)
|
|
{
|
|
foreach (var v in Items(r.Value))
|
|
{
|
|
var t = MediaCard.AsTrack(Json.AsObject(v));
|
|
if (t != null && t.Id != null) byId[t.Id.Value] = t;
|
|
}
|
|
}
|
|
else if (byId.Count == 0)
|
|
{
|
|
_lastLoadFailure = r;
|
|
}
|
|
}
|
|
var list = new List<MediaCard>();
|
|
foreach (var id in ids)
|
|
{
|
|
MediaCard t;
|
|
if (byId.TryGetValue(id, out t)) list.Add(t);
|
|
}
|
|
return list;
|
|
}
|
|
|
|
private async void PlayAll_Click(object sender, RoutedEventArgs e)
|
|
{
|
|
if (_detailCard == null) return;
|
|
if (_detailCard.IsUser && _detailTracks.Count > 0) await PlayFromDetailAsync(0);
|
|
else await PlayCardAsync(_detailCard);
|
|
}
|
|
|
|
/// <summary>Play the open list from row <paramref name="index"/> to the end, in order.</summary>
|
|
private async Task PlayFromDetailAsync(int index)
|
|
{
|
|
var urns = new JsonArray();
|
|
foreach (var t in _detailTracks.Skip(index)) urns.Add(JsonValue.CreateStringValue(t.TrackUrn));
|
|
if (urns.Count == 0) return;
|
|
var data = new JsonObject();
|
|
data["urns"] = urns;
|
|
if (await SendAsync("playQueue", data)) ShowToast("Playing " + _detailTracks[index].Title);
|
|
}
|
|
|
|
private static bool CanPlayWithoutTracks(MediaCard card)
|
|
{
|
|
return !card.IsUser && (!string.IsNullOrEmpty(card.Permalink) || card.Id != null || !string.IsNullOrEmpty(card.Urn));
|
|
}
|
|
|
|
/// <summary>Play a whole card: a track, or a playlist / album / mix / station from the top.</summary>
|
|
private async Task PlayCardAsync(MediaCard card)
|
|
{
|
|
bool ok;
|
|
if (card.IsTrack)
|
|
{
|
|
ok = await SendAsync("play", "urn", JsonValue.CreateStringValue(card.TrackUrn));
|
|
}
|
|
else if (!string.IsNullOrEmpty(card.Permalink))
|
|
{
|
|
ok = await SendAsync("play", "url", JsonValue.CreateStringValue(card.Permalink));
|
|
}
|
|
else if ((card.Kind == CardKind.Playlist || card.Kind == CardKind.Album) && card.Id != null)
|
|
{
|
|
ok = await SendAsync("playPlaylist", "id", JsonValue.CreateNumberValue(card.Id.Value));
|
|
}
|
|
else if (_detailCard == card && _detailTracks.Count > 0)
|
|
{
|
|
await PlayFromDetailAsync(0);
|
|
return;
|
|
}
|
|
else if (!string.IsNullOrEmpty(card.Urn))
|
|
{
|
|
ok = await SendAsync("play", "urn", JsonValue.CreateStringValue(card.Urn));
|
|
}
|
|
else return;
|
|
if (ok) ShowToast("Playing " + card.Title);
|
|
}
|
|
|
|
// ================================================================ rows
|
|
|
|
private UIElement SectionLabel(string text)
|
|
{
|
|
return new TextBlock
|
|
{
|
|
Text = text,
|
|
Style = AppStyle("RwLabel"),
|
|
Margin = new Thickness(8, 14, 8, 4),
|
|
};
|
|
}
|
|
|
|
private Button BuildCardRow(MediaCard card)
|
|
{
|
|
Button play = null;
|
|
if (!card.IsUser)
|
|
{
|
|
play = new Button
|
|
{
|
|
Style = AppStyle("RwIconButton"),
|
|
Width = 32,
|
|
Height = 32,
|
|
FontSize = 13,
|
|
Content = GlyphPlay,
|
|
};
|
|
AutomationProperties.SetName(play, "Play " + card.Title);
|
|
ToolTipService.SetToolTip(play, card.IsTrack ? "Play" : "Play all");
|
|
play.Click += async (s, e) => await PlayCardAsync(card);
|
|
}
|
|
var row = BuildRow(card.ArtUrl, card.IsRound, card.Title, card.Subtitle, card.IsTrack ? card.Meta : "", false, play);
|
|
AutomationProperties.SetName(row, card.IsTrack ? "Play " + card.Title : "Open " + card.Title);
|
|
row.Click += async (s, e) =>
|
|
{
|
|
if (card.IsTrack) await PlayCardAsync(card);
|
|
else OpenDetail(card);
|
|
};
|
|
return row;
|
|
}
|
|
|
|
private Button BuildRow(string art, bool round, string title, string subtitle, string meta, bool current, UIElement trailing)
|
|
{
|
|
var grid = new Grid();
|
|
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });
|
|
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
|
|
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
|
|
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
|
|
|
|
grid.Children.Add(Thumb(art, round));
|
|
|
|
var text = new StackPanel { Margin = new Thickness(10, 0, 6, 0), VerticalAlignment = VerticalAlignment.Center };
|
|
var titleBlock = new TextBlock { Text = title ?? "", Style = AppStyle("RwBody"), FontSize = 13.5 };
|
|
if (current) { titleBlock.FontFamily = (FontFamily)Application.Current.Resources["RwFont700"]; titleBlock.FontWeight = Windows.UI.Text.FontWeights.Bold; }
|
|
text.Children.Add(titleBlock);
|
|
if (!string.IsNullOrEmpty(subtitle))
|
|
text.Children.Add(new TextBlock { Text = subtitle, Style = AppStyle("RwCaption"), FontSize = 12 });
|
|
Grid.SetColumn(text, 1);
|
|
grid.Children.Add(text);
|
|
|
|
if (!string.IsNullOrEmpty(meta))
|
|
{
|
|
var metaBlock = new TextBlock { Text = meta, Style = AppStyle("RwSubtle"), FontSize = 12, VerticalAlignment = VerticalAlignment.Center };
|
|
Grid.SetColumn(metaBlock, 2);
|
|
grid.Children.Add(metaBlock);
|
|
}
|
|
if (trailing != null)
|
|
{
|
|
Grid.SetColumn((FrameworkElement)trailing, 3);
|
|
((FrameworkElement)trailing).Margin = new Thickness(4, 0, 0, 0);
|
|
grid.Children.Add(trailing);
|
|
}
|
|
|
|
var row = new Button { Style = AppStyle("RwRowButton"), Content = grid };
|
|
if (current)
|
|
{
|
|
// The playing row: a wash and a red bar on its left edge.
|
|
row.Background = ThemeManager.Brush("redSoft");
|
|
row.BorderBrush = ThemeManager.Brush("red");
|
|
row.BorderThickness = new Thickness(3, 0, 0, 0);
|
|
}
|
|
return row;
|
|
}
|
|
|
|
private UIElement Thumb(string art, bool round)
|
|
{
|
|
var box = new Grid { Width = 40, Height = 40 };
|
|
Uri uri = null;
|
|
if (!string.IsNullOrEmpty(art)) Uri.TryCreate(art, UriKind.Absolute, out uri);
|
|
|
|
if (round)
|
|
{
|
|
var circle = new Ellipse { Fill = ThemeManager.Brush("bg2") };
|
|
box.Children.Add(circle);
|
|
if (uri != null)
|
|
box.Children.Add(new Ellipse { Fill = new ImageBrush { ImageSource = new BitmapImage(uri) { DecodePixelWidth = 80 }, Stretch = Stretch.UniformToFill } });
|
|
}
|
|
else
|
|
{
|
|
box.Children.Add(new Rectangle { Fill = ThemeManager.Brush("bg2") });
|
|
if (uri != null)
|
|
box.Children.Add(new Image { Source = new BitmapImage(uri) { DecodePixelWidth = 80 }, Stretch = Stretch.UniformToFill });
|
|
else
|
|
box.Children.Add(new TextBlock { Text = "", Style = AppStyle("RwIcon"), FontSize = 16, Foreground = ThemeManager.Brush("textSubtle") });
|
|
}
|
|
return box;
|
|
}
|
|
|
|
private static Style AppStyle(string key)
|
|
{
|
|
return (Style)Application.Current.Resources[key];
|
|
}
|
|
|
|
// ================================================================ helpers
|
|
|
|
/// <summary>A list from SoundCloud's JSON: a bare array, or an object's "collection".</summary>
|
|
private static IEnumerable<IJsonValue> Items(IJsonValue value)
|
|
{
|
|
var array = Json.AsArray(value);
|
|
if (array == null)
|
|
{
|
|
var obj = Json.AsObject(value);
|
|
array = Json.Arr(obj, "collection");
|
|
}
|
|
return array != null ? (IEnumerable<IJsonValue>)array : new IJsonValue[0];
|
|
}
|
|
|
|
private static string LibraryMessage(LibraryResult r)
|
|
{
|
|
switch (r.Status)
|
|
{
|
|
case LibraryStatus.SignedOut: return "Sign in to CrossSound to browse SoundCloud.";
|
|
case LibraryStatus.NotRunning: return "Can't reach CrossSound. Is it running?";
|
|
default: return "SoundCloud had a problem: " + (r.Message ?? "unknown error");
|
|
}
|
|
}
|
|
|
|
private void ShowMessage(StackPanel panel, TextBlock text, string message)
|
|
{
|
|
text.Text = message;
|
|
panel.Visibility = Visibility.Visible;
|
|
Fade(panel, 1, 150, 0);
|
|
}
|
|
|
|
private void ShowMessage(TextBlock text, string message)
|
|
{
|
|
text.Text = message;
|
|
text.Visibility = Visibility.Visible;
|
|
Fade(text, 1, 150, 0);
|
|
}
|
|
|
|
private void ShowToast(string message)
|
|
{
|
|
ToastText.Text = message;
|
|
_toastTimer.Stop();
|
|
Fade(Toast, 1, 150);
|
|
_toastTimer.Start();
|
|
}
|
|
|
|
private static string Plural(int n, string word)
|
|
{
|
|
return n.ToString(System.Globalization.CultureInfo.InvariantCulture) + " " + word + (n == 1 ? "" : "S");
|
|
}
|
|
|
|
/// <summary>RedWhite motion: a plain opacity fade, ease-out; instant with animations off.</summary>
|
|
private void Fade(UIElement element, double to, int ms, double? from = null)
|
|
{
|
|
if (!_uiSettings.AnimationsEnabled)
|
|
{
|
|
element.Opacity = to;
|
|
return;
|
|
}
|
|
var animation = new DoubleAnimation
|
|
{
|
|
To = to,
|
|
Duration = TimeSpan.FromMilliseconds(ms),
|
|
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut },
|
|
};
|
|
if (from != null) animation.From = from;
|
|
Storyboard.SetTarget(animation, element);
|
|
Storyboard.SetTargetProperty(animation, "Opacity");
|
|
var storyboard = new Storyboard();
|
|
storyboard.Children.Add(animation);
|
|
storyboard.Begin();
|
|
}
|
|
}
|
|
}
|