cu-trainer/Ultra Paradise Linux/app/NowPlaying.cs
| 1 | using System; |
| 2 | using System.Globalization; |
| 3 | using System.IO; |
| 4 | using System.Text.RegularExpressions; |
| 5 | using System.Threading.Tasks; |
| 6 | using Avalonia; |
| 7 | using Avalonia.Controls; |
| 8 | using Avalonia.Controls.Primitives; |
| 9 | using Avalonia.Layout; |
| 10 | using Avalonia.Media; |
| 11 | using Avalonia.Media.Imaging; |
| 12 | using Avalonia.Threading; |
| 13 | |
| 14 | namespace UltraParadise.Linux |
| 15 | { |
| 16 | internal sealed class MprisState |
| 17 | { |
| 18 | public string Title = "", Artist = "", Album = "", Art = "", Loop = "None"; |
| 19 | public long LengthUs, PosUs; |
| 20 | public bool Playing, Shuffle, HasShuffle, HasLoop; |
| 21 | public string Line => Title.Length == 0 ? "" : (Artist.Length > 0 ? Artist + " - " : "") + Title; |
| 22 | } |
| 23 | |
| 24 | internal sealed partial class MainWindow |
| 25 | { |
| 26 | private readonly Image npArt = new() { Width = 200, Height = 200, Stretch = Stretch.UniformToFill }; |
| 27 | private readonly TextBlock npNoArt = T("♫", 64, Ui.B(Ui.Faint), true); |
| 28 | private readonly TextBlock npJam = T("", 15, Ui.B(Ui.Orange), true, true); |
| 29 | private readonly TextBlock npTitle = T("", 18, Ui.B(Ui.Bright), true, true); |
| 30 | private readonly TextBlock npArtist = T("", 14, Ui.B(Ui.Soft), false, true); |
| 31 | private readonly TextBlock npApp = T("", 12, Ui.B(Ui.Dim), false, true); |
| 32 | private readonly Slider npBar = new() { Minimum = 0, Maximum = 1, Value = 0 }; |
| 33 | private readonly TextBlock npPos = T("0:00", 12, Ui.B(Ui.Soft)); |
| 34 | private readonly TextBlock npLen = T("", 12, Ui.B(Ui.Soft)); |
| 35 | private readonly Button npShuffle = new(), npPrev = new(), npPlay = new(), npNext = new(), npRepeat = new(); |
| 36 | private readonly StackPanel npControls = new() { Spacing = 8 }; |
| 37 | private MprisState np; |
| 38 | private DateTime npStamp; |
| 39 | private string npArtUrl; |
| 40 | private bool npQuiet; |
| 41 | |
| 42 | private static Button RoundBtn(Button b, string text, double size, double font) |
| 43 | { |
| 44 | b.Content = text; |
| 45 | b.Width = size; |
| 46 | b.Height = size; |
| 47 | b.FontSize = font; |
| 48 | b.Padding = new Thickness(0); |
| 49 | b.CornerRadius = new CornerRadius(size / 2); |
| 50 | b.HorizontalContentAlignment = HorizontalAlignment.Center; |
| 51 | b.VerticalContentAlignment = VerticalAlignment.Center; |
| 52 | return b; |
| 53 | } |
| 54 | |
| 55 | private void BuildNowPlaying(StackPanel ab) |
| 56 | { |
| 57 | npJam.TextAlignment = TextAlignment.Center; |
| 58 | ab.Children.Add(npJam); |
| 59 | Grid art = new() { Width = 200, Height = 200, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 6, 0, 6) }; |
| 60 | Border ab2 = new() { CornerRadius = new CornerRadius(8), ClipToBounds = true, Background = Ui.B(Ui.Sunk), Child = npArt }; |
| 61 | art.Children.Add(ab2); |
| 62 | npNoArt.HorizontalAlignment = HorizontalAlignment.Center; |
| 63 | npNoArt.VerticalAlignment = VerticalAlignment.Center; |
| 64 | art.Children.Add(npNoArt); |
| 65 | ab.Children.Add(art); |
| 66 | foreach (TextBlock tb in new[] { npTitle, npArtist, npApp }) { tb.TextAlignment = TextAlignment.Center; ab.Children.Add(tb); } |
| 67 | |
| 68 | ab.Children.Add(npBar); |
| 69 | Grid times = new() { ColumnDefinitions = new ColumnDefinitions("*,*") }; |
| 70 | times.Children.Add(npPos); |
| 71 | npLen.HorizontalAlignment = HorizontalAlignment.Right; |
| 72 | Grid.SetColumn(npLen, 1); |
| 73 | times.Children.Add(npLen); |
| 74 | ab.Children.Add(times); |
| 75 | npBar.PropertyChanged += (_, e) => |
| 76 | { |
| 77 | if (e.Property != RangeBase.ValueProperty || npQuiet || np == null || np.LengthUs <= 0) return; |
| 78 | long target = (long)(npBar.Value * np.LengthUs); |
| 79 | long cur = LivePosUs(); |
| 80 | _ = MprisCall("Seek", "int64:" + (target - cur).ToString(CultureInfo.InvariantCulture)); |
| 81 | np.PosUs = target; |
| 82 | npStamp = DateTime.UtcNow; |
| 83 | }; |
| 84 | |
| 85 | StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 10, HorizontalAlignment = HorizontalAlignment.Center }; |
| 86 | row.Children.Add(RoundBtn(npShuffle, "⇄", 40, 18)); |
| 87 | row.Children.Add(RoundBtn(npPrev, "⏮", 40, 18)); |
| 88 | row.Children.Add(RoundBtn(npPlay, "▶", 56, 24)); |
| 89 | row.Children.Add(RoundBtn(npNext, "⏭", 40, 18)); |
| 90 | row.Children.Add(RoundBtn(npRepeat, "↻", 40, 18)); |
| 91 | npPlay.Background = Ui.B(Ui.Bright); |
| 92 | npPlay.Foreground = Ui.B(Ui.Back); |
| 93 | ToolTip.SetTip(npShuffle, "Shuffle"); |
| 94 | ToolTip.SetTip(npRepeat, "Repeat: off, all, one"); |
| 95 | npShuffle.Click += (_, _) => { if (np != null) _ = MprisSet("Shuffle", "variant:boolean:" + (np.Shuffle ? "false" : "true")); }; |
| 96 | npPrev.Click += (_, _) => _ = Mpris("Previous"); |
| 97 | npPlay.Click += (_, _) => _ = Mpris("PlayPause"); |
| 98 | npNext.Click += (_, _) => _ = Mpris("Next"); |
| 99 | npRepeat.Click += (_, _) => { if (np != null) _ = MprisSet("LoopStatus", "variant:string:" + (np.Loop == "None" ? "Playlist" : np.Loop == "Playlist" ? "Track" : "None")); }; |
| 100 | npControls.Children.Add(row); |
| 101 | StackPanel vol = new() { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Center }; |
| 102 | vol.Children.Add(Btn("Volume -", () => _ = MprisVolume(-0.1))); |
| 103 | vol.Children.Add(Btn("Volume +", () => _ = MprisVolume(0.1))); |
| 104 | npControls.Children.Add(vol); |
| 105 | ab.Children.Add(npControls); |
| 106 | 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)); |
| 107 | |
| 108 | DispatcherTimer t = new() { Interval = TimeSpan.FromMilliseconds(250) }; |
| 109 | t.Tick += (_, _) => { if (MusicVisible) { UpdateProgress(); LyricsTick(); } }; |
| 110 | t.Start(); |
| 111 | RefreshNowPlaying(); |
| 112 | } |
| 113 | |
| 114 | private long LivePosUs() |
| 115 | { |
| 116 | if (np == null) return 0; |
| 117 | long p = np.PosUs; |
| 118 | if (np.Playing) p += (long)((DateTime.UtcNow - npStamp).TotalMilliseconds * 1000); |
| 119 | if (np.LengthUs > 0) p = Math.Min(p, np.LengthUs); |
| 120 | return Math.Max(0, p); |
| 121 | } |
| 122 | |
| 123 | private static string UsClock(long us) |
| 124 | { |
| 125 | long s = us / 1000000; |
| 126 | return s >= 3600 ? (s / 3600) + ":" + (s / 60 % 60).ToString("00") + ":" + (s % 60).ToString("00") : (s / 60) + ":" + (s % 60).ToString("00"); |
| 127 | } |
| 128 | |
| 129 | private void UpdateProgress() |
| 130 | { |
| 131 | bool has = np != null && np.Title.Length > 0; |
| 132 | long p = LivePosUs(); |
| 133 | npQuiet = true; |
| 134 | npBar.Value = has && np.LengthUs > 0 ? (double)p / np.LengthUs : 0; |
| 135 | npQuiet = false; |
| 136 | npBar.IsEnabled = has && np.LengthUs > 0; |
| 137 | npPos.Text = has ? UsClock(p) : ""; |
| 138 | npLen.Text = has && np.LengthUs > 0 ? UsClock(np.LengthUs) : ""; |
| 139 | } |
| 140 | |
| 141 | private void RefreshNowPlaying() |
| 142 | { |
| 143 | bool has = np != null && np.Title.Length > 0; |
| 144 | npJam.Text = extFound ? "Jamming? Control your media here!" : "No Spotify or YouTube Music Desktop open right now."; |
| 145 | npJam.Foreground = Ui.B(extFound ? Ui.Orange : Ui.Dim); |
| 146 | npTitle.Text = has ? np.Title : extFound ? (extBus == null ? "The player isn't answering yet" : "Nothing playing") : ""; |
| 147 | npArtist.Text = has ? np.Artist : ""; |
| 148 | npApp.Text = extFound ? (has && np.Album.Length > 0 ? np.Album + " · " : "") + extApp : ""; |
| 149 | npPlay.Content = has && np.Playing ? "⏸" : "▶"; |
| 150 | npShuffle.Foreground = Ui.B(np != null && np.Shuffle ? Ui.Orange : Ui.Text); |
| 151 | npShuffle.IsEnabled = np != null && np.HasShuffle; |
| 152 | npRepeat.Content = np != null && np.Loop == "Track" ? "↻1" : "↻"; |
| 153 | npRepeat.Foreground = Ui.B(np != null && np.Loop != "None" ? Ui.Orange : Ui.Text); |
| 154 | npRepeat.IsEnabled = np != null && np.HasLoop; |
| 155 | npControls.IsEnabled = extFound && extBus != null; |
| 156 | npNoArt.IsVisible = npArt.Source == null; |
| 157 | UpdateProgress(); |
| 158 | } |
| 159 | |
| 160 | private void ApplyMpris(MprisState st) |
| 161 | { |
| 162 | np = st; |
| 163 | npStamp = DateTime.UtcNow; |
| 164 | string url = st?.Art ?? ""; |
| 165 | if (url != npArtUrl) |
| 166 | { |
| 167 | npArtUrl = url; |
| 168 | _ = LoadArt(url); |
| 169 | } |
| 170 | RefreshNowPlaying(); |
| 171 | } |
| 172 | |
| 173 | private async Task LoadArt(string url) |
| 174 | { |
| 175 | Bitmap bmp = null; |
| 176 | try |
| 177 | { |
| 178 | byte[] data = null; |
| 179 | if (url.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) data = await File.ReadAllBytesAsync(new Uri(url).LocalPath); |
| 180 | else if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) data = await Http.Client.GetByteArrayAsync(url); |
| 181 | if (data != null && data.Length < 10_000_000) bmp = new Bitmap(new MemoryStream(data)); |
| 182 | } |
| 183 | catch (Exception) { bmp = null; } |
| 184 | if (url != npArtUrl) { bmp?.Dispose(); return; } |
| 185 | Bitmap old = npArt.Source as Bitmap; |
| 186 | npArt.Source = bmp; |
| 187 | old?.Dispose(); |
| 188 | npNoArt.IsVisible = bmp == null; |
| 189 | } |
| 190 | |
| 191 | private static async Task<string> PlayerProp(string bus, string name) => |
| 192 | await DBus("--print-reply", "--dest=" + bus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:" + name); |
| 193 | |
| 194 | private static string Str(string md, string key) |
| 195 | { |
| 196 | Match m = Regex.Match(md, "\"" + Regex.Escape(key) + "\"\\s*variant\\s+(?:array\\s*\\[\\s*)?string\\s+\"((?:[^\"\\\\]|\\\\.)*)\""); |
| 197 | return m.Success ? Unescape(m.Groups[1].Value) : ""; |
| 198 | } |
| 199 | |
| 200 | private static long Num(string md, string key) |
| 201 | { |
| 202 | Match m = Regex.Match(md, "\"" + Regex.Escape(key) + "\"\\s*variant\\s+u?int(?:64|32)\\s+(-?\\d+)"); |
| 203 | return m.Success && long.TryParse(m.Groups[1].Value, out long v) ? v : 0; |
| 204 | } |
| 205 | |
| 206 | private static async Task<MprisState> StateOf(string bus) |
| 207 | { |
| 208 | MprisState s = new(); |
| 209 | string md = await PlayerProp(bus, "Metadata"); |
| 210 | if (md != null) |
| 211 | { |
| 212 | s.Title = Str(md, "xesam:title"); |
| 213 | s.Artist = Str(md, "xesam:artist"); |
| 214 | s.Album = Str(md, "xesam:album"); |
| 215 | s.Art = Str(md, "mpris:artUrl"); |
| 216 | s.LengthUs = Num(md, "mpris:length"); |
| 217 | } |
| 218 | string pos = await PlayerProp(bus, "Position"); |
| 219 | Match pm = pos == null ? Match.Empty : Regex.Match(pos, "int64\\s+(-?\\d+)"); |
| 220 | if (pm.Success) long.TryParse(pm.Groups[1].Value, out s.PosUs); |
| 221 | string st = await PlayerProp(bus, "PlaybackStatus"); |
| 222 | s.Playing = st != null && st.Contains("\"Playing\""); |
| 223 | string sh = await PlayerProp(bus, "Shuffle"); |
| 224 | s.HasShuffle = sh != null; |
| 225 | s.Shuffle = sh != null && sh.Contains("boolean true"); |
| 226 | string lp = await PlayerProp(bus, "LoopStatus"); |
| 227 | s.HasLoop = lp != null; |
| 228 | Match lm = lp == null ? Match.Empty : Regex.Match(lp, "string\\s+\"(\\w+)\""); |
| 229 | if (lm.Success) s.Loop = lm.Groups[1].Value; |
| 230 | return s; |
| 231 | } |
| 232 | |
| 233 | private async Task MprisCall(string method, string arg) |
| 234 | { |
| 235 | if (extBus == null) return; |
| 236 | await DBus("--type=method_call", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player." + method, arg); |
| 237 | extNext = DateTime.UtcNow.AddMilliseconds(400); |
| 238 | } |
| 239 | |
| 240 | private async Task MprisSet(string prop, string value) |
| 241 | { |
| 242 | if (extBus == null) return; |
| 243 | await DBus("--print-reply", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Set", "string:org.mpris.MediaPlayer2.Player", "string:" + prop, value); |
| 244 | extNext = DateTime.UtcNow; |
| 245 | } |
| 246 | } |
| 247 | } |