using System; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Media.Imaging; using Avalonia.Threading; namespace UltraParadise.Linux { internal sealed class MprisState { public string Title = "", Artist = "", Album = "", Art = "", Loop = "None"; public long LengthUs, PosUs; public bool Playing, Shuffle, HasShuffle, HasLoop; public string Line => Title.Length == 0 ? "" : (Artist.Length > 0 ? Artist + " - " : "") + Title; } internal sealed partial class MainWindow { private readonly Image npArt = new() { Width = 200, Height = 200, Stretch = Stretch.UniformToFill }; private readonly TextBlock npNoArt = T("♫", 64, Ui.B(Ui.Faint), true); private readonly TextBlock npJam = T("", 15, Ui.B(Ui.Orange), true, true); private readonly TextBlock npTitle = T("", 18, Ui.B(Ui.Bright), true, true); private readonly TextBlock npArtist = T("", 14, Ui.B(Ui.Soft), false, true); private readonly TextBlock npApp = T("", 12, Ui.B(Ui.Dim), false, true); private readonly Slider npBar = new() { Minimum = 0, Maximum = 1, Value = 0 }; private readonly TextBlock npPos = T("0:00", 12, Ui.B(Ui.Soft)); private readonly TextBlock npLen = T("", 12, Ui.B(Ui.Soft)); private readonly Button npShuffle = new(), npPrev = new(), npPlay = new(), npNext = new(), npRepeat = new(); private readonly StackPanel npControls = new() { Spacing = 8 }; private MprisState np; private DateTime npStamp; private string npArtUrl; private bool npQuiet; private static Button RoundBtn(Button b, string text, double size, double font) { b.Content = text; b.Width = size; b.Height = size; b.FontSize = font; b.Padding = new Thickness(0); b.CornerRadius = new CornerRadius(size / 2); b.HorizontalContentAlignment = HorizontalAlignment.Center; b.VerticalContentAlignment = VerticalAlignment.Center; return b; } private void BuildNowPlaying(StackPanel ab) { npJam.TextAlignment = TextAlignment.Center; ab.Children.Add(npJam); Grid art = new() { Width = 200, Height = 200, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 6, 0, 6) }; Border ab2 = new() { CornerRadius = new CornerRadius(8), ClipToBounds = true, Background = Ui.B(Ui.Sunk), Child = npArt }; art.Children.Add(ab2); npNoArt.HorizontalAlignment = HorizontalAlignment.Center; npNoArt.VerticalAlignment = VerticalAlignment.Center; art.Children.Add(npNoArt); ab.Children.Add(art); foreach (TextBlock tb in new[] { npTitle, npArtist, npApp }) { tb.TextAlignment = TextAlignment.Center; ab.Children.Add(tb); } ab.Children.Add(npBar); Grid times = new() { ColumnDefinitions = new ColumnDefinitions("*,*") }; times.Children.Add(npPos); npLen.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(npLen, 1); times.Children.Add(npLen); ab.Children.Add(times); npBar.PropertyChanged += (_, e) => { if (e.Property != RangeBase.ValueProperty || npQuiet || np == null || np.LengthUs <= 0) return; long target = (long)(npBar.Value * np.LengthUs); long cur = LivePosUs(); _ = MprisCall("Seek", "int64:" + (target - cur).ToString(CultureInfo.InvariantCulture)); np.PosUs = target; npStamp = DateTime.UtcNow; }; StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 10, HorizontalAlignment = HorizontalAlignment.Center }; row.Children.Add(RoundBtn(npShuffle, "⇄", 40, 18)); row.Children.Add(RoundBtn(npPrev, "⏮", 40, 18)); row.Children.Add(RoundBtn(npPlay, "▶", 56, 24)); row.Children.Add(RoundBtn(npNext, "⏭", 40, 18)); row.Children.Add(RoundBtn(npRepeat, "↻", 40, 18)); npPlay.Background = Ui.B(Ui.Bright); npPlay.Foreground = Ui.B(Ui.Back); ToolTip.SetTip(npShuffle, "Shuffle"); ToolTip.SetTip(npRepeat, "Repeat: off, all, one"); npShuffle.Click += (_, _) => { if (np != null) _ = MprisSet("Shuffle", "variant:boolean:" + (np.Shuffle ? "false" : "true")); }; npPrev.Click += (_, _) => _ = Mpris("Previous"); npPlay.Click += (_, _) => _ = Mpris("PlayPause"); npNext.Click += (_, _) => _ = Mpris("Next"); npRepeat.Click += (_, _) => { if (np != null) _ = MprisSet("LoopStatus", "variant:string:" + (np.Loop == "None" ? "Playlist" : np.Loop == "Playlist" ? "Track" : "None")); }; npControls.Children.Add(row); StackPanel vol = new() { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Center }; vol.Children.Add(Btn("Volume -", () => _ = MprisVolume(-0.1))); vol.Children.Add(Btn("Volume +", () => _ = MprisVolume(0.1))); npControls.Children.Add(vol); ab.Children.Add(npControls); ab.Children.Add(T("Works with Spotify and YouTube Music Desktop, straight through the player (MPRIS). Volume is the player's own volume.", 12, Ui.B(Ui.Dim), false, true)); DispatcherTimer t = new() { Interval = TimeSpan.FromMilliseconds(250) }; t.Tick += (_, _) => { if (MusicVisible) { UpdateProgress(); LyricsTick(); } }; t.Start(); RefreshNowPlaying(); } private long LivePosUs() { if (np == null) return 0; long p = np.PosUs; if (np.Playing) p += (long)((DateTime.UtcNow - npStamp).TotalMilliseconds * 1000); if (np.LengthUs > 0) p = Math.Min(p, np.LengthUs); return Math.Max(0, p); } private static string UsClock(long us) { long s = us / 1000000; return s >= 3600 ? (s / 3600) + ":" + (s / 60 % 60).ToString("00") + ":" + (s % 60).ToString("00") : (s / 60) + ":" + (s % 60).ToString("00"); } private void UpdateProgress() { bool has = np != null && np.Title.Length > 0; long p = LivePosUs(); npQuiet = true; npBar.Value = has && np.LengthUs > 0 ? (double)p / np.LengthUs : 0; npQuiet = false; npBar.IsEnabled = has && np.LengthUs > 0; npPos.Text = has ? UsClock(p) : ""; npLen.Text = has && np.LengthUs > 0 ? UsClock(np.LengthUs) : ""; } private void RefreshNowPlaying() { bool has = np != null && np.Title.Length > 0; npJam.Text = extFound ? "Jamming? Control your media here!" : "No Spotify or YouTube Music Desktop open right now."; npJam.Foreground = Ui.B(extFound ? Ui.Orange : Ui.Dim); npTitle.Text = has ? np.Title : extFound ? (extBus == null ? "The player isn't answering yet" : "Nothing playing") : ""; npArtist.Text = has ? np.Artist : ""; npApp.Text = extFound ? (has && np.Album.Length > 0 ? np.Album + " · " : "") + extApp : ""; npPlay.Content = has && np.Playing ? "⏸" : "▶"; npShuffle.Foreground = Ui.B(np != null && np.Shuffle ? Ui.Orange : Ui.Text); npShuffle.IsEnabled = np != null && np.HasShuffle; npRepeat.Content = np != null && np.Loop == "Track" ? "↻1" : "↻"; npRepeat.Foreground = Ui.B(np != null && np.Loop != "None" ? Ui.Orange : Ui.Text); npRepeat.IsEnabled = np != null && np.HasLoop; npControls.IsEnabled = extFound && extBus != null; npNoArt.IsVisible = npArt.Source == null; UpdateProgress(); } private void ApplyMpris(MprisState st) { np = st; npStamp = DateTime.UtcNow; string url = st?.Art ?? ""; if (url != npArtUrl) { npArtUrl = url; _ = LoadArt(url); } RefreshNowPlaying(); } private async Task LoadArt(string url) { Bitmap bmp = null; try { byte[] data = null; if (url.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) data = await File.ReadAllBytesAsync(new Uri(url).LocalPath); else if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) data = await Http.Client.GetByteArrayAsync(url); if (data != null && data.Length < 10_000_000) bmp = new Bitmap(new MemoryStream(data)); } catch (Exception) { bmp = null; } if (url != npArtUrl) { bmp?.Dispose(); return; } Bitmap old = npArt.Source as Bitmap; npArt.Source = bmp; old?.Dispose(); npNoArt.IsVisible = bmp == null; } private static async Task PlayerProp(string bus, string name) => await DBus("--print-reply", "--dest=" + bus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:" + name); private static string Str(string md, string key) { Match m = Regex.Match(md, "\"" + Regex.Escape(key) + "\"\\s*variant\\s+(?:array\\s*\\[\\s*)?string\\s+\"((?:[^\"\\\\]|\\\\.)*)\""); return m.Success ? Unescape(m.Groups[1].Value) : ""; } private static long Num(string md, string key) { Match m = Regex.Match(md, "\"" + Regex.Escape(key) + "\"\\s*variant\\s+u?int(?:64|32)\\s+(-?\\d+)"); return m.Success && long.TryParse(m.Groups[1].Value, out long v) ? v : 0; } private static async Task StateOf(string bus) { MprisState s = new(); string md = await PlayerProp(bus, "Metadata"); if (md != null) { s.Title = Str(md, "xesam:title"); s.Artist = Str(md, "xesam:artist"); s.Album = Str(md, "xesam:album"); s.Art = Str(md, "mpris:artUrl"); s.LengthUs = Num(md, "mpris:length"); } string pos = await PlayerProp(bus, "Position"); Match pm = pos == null ? Match.Empty : Regex.Match(pos, "int64\\s+(-?\\d+)"); if (pm.Success) long.TryParse(pm.Groups[1].Value, out s.PosUs); string st = await PlayerProp(bus, "PlaybackStatus"); s.Playing = st != null && st.Contains("\"Playing\""); string sh = await PlayerProp(bus, "Shuffle"); s.HasShuffle = sh != null; s.Shuffle = sh != null && sh.Contains("boolean true"); string lp = await PlayerProp(bus, "LoopStatus"); s.HasLoop = lp != null; Match lm = lp == null ? Match.Empty : Regex.Match(lp, "string\\s+\"(\\w+)\""); if (lm.Success) s.Loop = lm.Groups[1].Value; return s; } private async Task MprisCall(string method, string arg) { if (extBus == null) return; await DBus("--type=method_call", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player." + method, arg); extNext = DateTime.UtcNow.AddMilliseconds(400); } private async Task MprisSet(string prop, string value) { if (extBus == null) return; await DBus("--print-reply", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Set", "string:org.mpris.MediaPlayer2.Player", "string:" + prop, value); extNext = DateTime.UtcNow; } } }