using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Globalization; using System.IO; using System.Threading.Tasks; using System.Windows.Forms; using Windows.Media; using Windows.Media.Control; namespace UltraParadise { internal class NowPlayingCard : Control { public bool Has, Found, Playing, Shuffle, CanShuffle, CanRepeat, CanSeek; public int Repeat; public string Title = "", Artist = "", Album = "", App = "", FallbackApp = "", FallbackTitle = ""; public TimeSpan Pos, End; public DateTimeOffset Stamp; public Image Thumb; public event Action Command; public event Action Seek; private readonly Dictionary btns = new Dictionary(); private Rectangle bar; private string hover; private bool hoverBar; private readonly Font head = Theme.F("Segoe UI Semibold", 8f); private readonly Font jam = Theme.F("Segoe UI Semibold", 11f); private readonly Font title = Theme.F("Segoe UI Semibold", 13f); private readonly Font artist = Theme.F("Segoe UI", 10f); private readonly Font small = Theme.F("Segoe UI", 8.5f); private Font icons, iconsBig; public NowPlayingCard() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); try { icons = new Font("Segoe MDL2 Assets", 13f * Theme.Scale); iconsBig = new Font("Segoe MDL2 Assets", 17f * Theme.Scale); if (icons.Name != "Segoe MDL2 Assets") { icons = null; iconsBig = null; } } catch (Exception) { icons = null; iconsBig = null; } } public void SetThumb(Image img) { if (Thumb != null) Thumb.Dispose(); Thumb = img; Invalidate(); } public void Clear() { Has = false; Title = Artist = Album = App = ""; SetThumb(null); } public TimeSpan LivePos() { TimeSpan p = Pos; if (Playing && Stamp != default(DateTimeOffset)) { TimeSpan d = DateTimeOffset.Now - Stamp; if (d > TimeSpan.Zero && d < TimeSpan.FromHours(3)) p += d; } if (End > TimeSpan.Zero && p > End) p = End; if (p < TimeSpan.Zero) p = TimeSpan.Zero; return p; } private static string Clock(TimeSpan t) { int s = (int)t.TotalSeconds; return s >= 3600 ? (s / 3600) + ":" + (s / 60 % 60).ToString("00", CultureInfo.InvariantCulture) + ":" + (s % 60).ToString("00", CultureInfo.InvariantCulture) : (s / 60).ToString(CultureInfo.InvariantCulture) + ":" + (s % 60).ToString("00", CultureInfo.InvariantCulture); } private static GraphicsPath Round(Rectangle r, int rad) { int d = Math.Max(1, rad * 2); GraphicsPath p = new GraphicsPath(); p.AddArc(r.X, r.Y, d, d, 180, 90); p.AddArc(r.Right - d, r.Y, d, d, 270, 90); p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90); p.AddArc(r.X, r.Bottom - d, d, d, 90, 90); p.CloseFigure(); return p; } private void Glyph(Graphics g, string id, char glyph, string fallback, Rectangle r, bool on, bool enabled, bool big) { btns[id] = r; bool hv = hover == id && enabled; Color c = !enabled ? Theme.Faint : on ? Theme.Orange : hv ? Theme.Bright : Theme.Text; StringFormat m = new StringFormat(); m.Alignment = StringAlignment.Center; m.LineAlignment = StringAlignment.Center; if (hv) using (SolidBrush hb = new SolidBrush(Theme.Hover)) g.FillEllipse(hb, r); using (SolidBrush b = new SolidBrush(c)) { if (icons != null) g.DrawString(glyph.ToString(), big ? iconsBig : icons, b, r, m); else g.DrawString(fallback, small, b, r, m); } } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; g.Clear(Theme.Back); btns.Clear(); bar = Rectangle.Empty; int W = Width, pad = Theme.S(16); Rectangle card = new Rectangle(0, 0, W - 1, Height - 1); using (GraphicsPath p = Round(card, Theme.S(10))) { using (SolidBrush b = new SolidBrush(Theme.Panel)) g.FillPath(b, p); using (Pen pe = new Pen(Theme.Line)) g.DrawPath(pe, p); } StringFormat c = new StringFormat(); c.Alignment = StringAlignment.Center; c.LineAlignment = StringAlignment.Center; c.Trimming = StringTrimming.EllipsisCharacter; c.FormatFlags = StringFormatFlags.NoWrap; StringFormat l = new StringFormat(c); l.Alignment = StringAlignment.Near; StringFormat r = new StringFormat(c); r.Alignment = StringAlignment.Far; int y = Theme.S(12); using (SolidBrush o = new SolidBrush(Theme.Orange)) g.DrawString(Theme.Spaced("NOW PLAYING"), head, o, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), l); y += Theme.S(24); bool any = Has || Found; using (SolidBrush jb = new SolidBrush(any ? Theme.Orange : Theme.Dim)) g.DrawString(any ? "Jamming? Control your media here!" : "No Spotify or YouTube Music Desktop open right now.", any ? jam : small, jb, new RectangleF(pad, y, W - pad * 2, Theme.S(36)), c); y += Theme.S(40); int ts = Math.Min(W - pad * 2, Theme.S(190)); Rectangle tr = new Rectangle((W - ts) / 2, y, ts, ts); using (GraphicsPath tp = Round(tr, Theme.S(8))) { if (Thumb != null) { GraphicsState st = g.Save(); g.SetClip(tp); g.InterpolationMode = InterpolationMode.HighQualityBicubic; float sc = Math.Max(ts / (float)Thumb.Width, ts / (float)Thumb.Height); int sw = (int)(ts / sc), sh = (int)(ts / sc); g.DrawImage(Thumb, tr, new Rectangle((Thumb.Width - sw) / 2, (Thumb.Height - sh) / 2, sw, sh), GraphicsUnit.Pixel); g.Restore(st); } else { using (SolidBrush sb = new SolidBrush(Theme.Sunk)) g.FillPath(sb, tp); StringFormat m = new StringFormat(); m.Alignment = StringAlignment.Center; m.LineAlignment = StringAlignment.Center; using (SolidBrush db = new SolidBrush(Theme.Faint)) if (iconsBig != null) using (Font f = new Font("Segoe MDL2 Assets", 40f * Theme.Scale)) g.DrawString("", f, db, tr, m); } } y += ts + Theme.S(14); string t = Has ? Title : FallbackTitle; string a = Has ? Artist : ""; using (SolidBrush tb = new SolidBrush(Theme.Bright)) g.DrawString(t.Length > 0 ? t : (any ? "Nothing playing" : ""), title, tb, new RectangleF(pad, y, W - pad * 2, Theme.S(26)), c); y += Theme.S(26); using (SolidBrush ab = new SolidBrush(Theme.Soft)) g.DrawString(a, artist, ab, new RectangleF(pad, y, W - pad * 2, Theme.S(20)), c); y += Theme.S(20); string app = Has ? App : FallbackApp; using (SolidBrush db = new SolidBrush(Theme.Dim)) g.DrawString(app.Length > 0 ? (Album.Length > 0 && Has ? Album + " · " + app : app) : "", small, db, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), c); y += Theme.S(26); TimeSpan pos = LivePos(); double frac = End > TimeSpan.Zero ? Math.Max(0, Math.Min(1, pos.TotalSeconds / End.TotalSeconds)) : 0; Rectangle br = new Rectangle(pad, y, W - pad * 2, Theme.S(4)); bar = new Rectangle(br.X, br.Y - Theme.S(8), br.Width, br.Height + Theme.S(16)); using (GraphicsPath bp = Round(br, Theme.S(2))) using (SolidBrush lb = new SolidBrush(Theme.Line)) g.FillPath(lb, bp); int fw = (int)(br.Width * frac); if (fw > 1) using (GraphicsPath fp = Round(new Rectangle(br.X, br.Y, fw, br.Height), Theme.S(2))) using (SolidBrush ob = new SolidBrush(hoverBar && CanSeek ? Theme.Orange : Theme.Text)) g.FillPath(ob, fp); if (Has && End > TimeSpan.Zero) using (SolidBrush kb = new SolidBrush(Theme.Bright)) g.FillEllipse(kb, br.X + fw - Theme.S(6), br.Y + br.Height / 2 - Theme.S(6), Theme.S(12), Theme.S(12)); y += Theme.S(10); using (SolidBrush db = new SolidBrush(Theme.Soft)) { g.DrawString(Has ? Clock(pos) : "", small, db, new RectangleF(pad, y, W / 2 - pad, Theme.S(18)), l); g.DrawString(Has && End > TimeSpan.Zero ? Clock(End) : "", small, db, new RectangleF(W / 2, y, W / 2 - pad, Theme.S(18)), r); } y += Theme.S(26); int bs = Theme.S(40), big = Theme.S(56); int gap = Math.Max(Theme.S(4), (W - pad * 2 - bs * 4 - big) / 4); int x = (W - (bs * 4 + big + gap * 4)) / 2; int cy = y + big / 2; bool live = Has || Found; Glyph(g, "shuffle", '', "Shuf", new Rectangle(x, cy - bs / 2, bs, bs), Shuffle, Has && CanShuffle, false); x += bs + gap; Glyph(g, "prev", '', "Prev", new Rectangle(x, cy - bs / 2, bs, bs), false, live, false); x += bs + gap; Rectangle pr = new Rectangle(x, cy - big / 2, big, big); btns["play"] = pr; using (SolidBrush pb = new SolidBrush(!live ? Theme.Line : hover == "play" ? Theme.Orange : Theme.Bright)) g.FillEllipse(pb, pr); StringFormat mm = new StringFormat(); mm.Alignment = StringAlignment.Center; mm.LineAlignment = StringAlignment.Center; using (SolidBrush ib = new SolidBrush(Theme.Back)) { if (iconsBig != null) g.DrawString(Playing ? "" : "", iconsBig, ib, pr, mm); else g.DrawString(Playing ? "II" : ">", jam, ib, pr, mm); } x += big + gap; Glyph(g, "next", '', "Next", new Rectangle(x, cy - bs / 2, bs, bs), false, live, false); x += bs + gap; Glyph(g, "repeat", Repeat == 1 ? '' : '', "Rep", new Rectangle(x, cy - bs / 2, bs, bs), Repeat != 0, Has && CanRepeat, false); y += big + Theme.S(14); int vb = Theme.S(34); int vx = (W - vb * 3 - Theme.S(8) * 2) / 2; Glyph(g, "voldown", '', "Vol-", new Rectangle(vx, y, vb, vb), false, true, false); vx += vb + Theme.S(8); Glyph(g, "mute", '', "Mute", new Rectangle(vx, y, vb, vb), false, true, false); vx += vb + Theme.S(8); Glyph(g, "volup", '', "Vol+", new Rectangle(vx, y, vb, vb), false, true, false); y += vb + Theme.S(6); using (SolidBrush fb = new SolidBrush(Theme.Faint)) g.DrawString("Volume is your PC's volume", small, fb, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), c); } public int Wanted() { return Theme.S(12 + 24 + 40) + Math.Min(Width - Theme.S(32), Theme.S(190)) + Theme.S(14 + 26 + 20 + 26 + 10 + 26 + 56 + 14 + 34 + 6 + 26); } protected override void OnMouseMove(MouseEventArgs e) { string h = null; foreach (KeyValuePair kv in btns) if (kv.Value.Contains(e.Location)) h = kv.Key; bool hb = Has && CanSeek && bar.Contains(e.Location); if (h != hover || hb != hoverBar) { hover = h; hoverBar = hb; Invalidate(); } Cursor = h != null || hb ? Cursors.Hand : Cursors.Default; } protected override void OnMouseLeave(EventArgs e) { hover = null; hoverBar = false; Invalidate(); } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; if (Has && CanSeek && bar.Contains(e.Location) && bar.Width > 0) { if (Seek != null) Seek(Math.Max(0, Math.Min(1, (e.X - bar.X) / (double)bar.Width))); return; } foreach (KeyValuePair kv in btns) if (kv.Value.Contains(e.Location) && Command != null) { Command(kv.Key); return; } } } internal partial class MainForm { private readonly NowPlayingCard np = new NowPlayingCard(); private readonly System.Windows.Forms.Timer npTimer = new System.Windows.Forms.Timer(); private GlobalSystemMediaTransportControlsSessionManager smtc; private GlobalSystemMediaTransportControlsSession smtcSession; private bool smtcBusy; private int smtcFails, npTicks; private string thumbKey; private void SetupNowPlaying() { np.Visible = false; np.Command += MediaCommand; np.Seek += MediaSeek; view.Controls.Add(np); SetupLyrics(); view.Resize += delegate { PlaceNowPlaying(); }; npTimer.Interval = 250; npTimer.Tick += delegate { if (!np.Visible) return; np.Invalidate(); lyr.Invalidate(); if (++npTicks % 4 == 0) { PollMedia(); LyricsCheck(); } }; npTimer.Start(); } private void PlaceNowPlaying() { Rectangle r = view.ColumnBounds(0); np.Bounds = new Rectangle(r.X, r.Y, r.Width, Math.Min(r.Height, np.Wanted())); int ly = np.Bottom + Theme.S(12); lyr.Bounds = new Rectangle(r.X, ly, r.Width, Math.Max(Theme.S(220), r.Bottom - ly)); } private void ShowNowPlaying(bool on) { np.Visible = on; lyr.Visible = on; if (on) { PlaceNowPlaying(); PollMedia(); LyricsCheck(); } } private static string AppOf(string id) { string l = (id ?? "").ToLowerInvariant(); if (l.Contains("spotify")) return "Spotify"; if (l.Contains("youtube") || l.Contains("ytm")) return "YouTube Music Desktop"; return null; } private async void PollMedia() { if (smtcBusy || smtcFails > 5) return; smtcBusy = true; try { if (smtc == null) smtc = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync().AsTask(); GlobalSystemMediaTransportControlsSession pick = null; int best = -1; foreach (GlobalSystemMediaTransportControlsSession s in smtc.GetSessions()) { if (AppOf(s.SourceAppUserModelId) == null) continue; int score = s.GetPlaybackInfo().PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing ? 2 : 1; if (score > best) { best = score; pick = s; } } smtcSession = pick; if (pick == null) { np.Clear(); thumbKey = null; } else { GlobalSystemMediaTransportControlsSessionMediaProperties pr = await pick.TryGetMediaPropertiesAsync().AsTask(); GlobalSystemMediaTransportControlsSessionTimelineProperties tl = pick.GetTimelineProperties(); GlobalSystemMediaTransportControlsSessionPlaybackInfo pb = pick.GetPlaybackInfo(); np.Has = true; np.App = AppOf(pick.SourceAppUserModelId); np.Title = pr.Title ?? ""; np.Artist = pr.Artist ?? ""; np.Album = pr.AlbumTitle ?? ""; np.Pos = tl.Position - tl.StartTime; np.End = tl.EndTime - tl.StartTime; np.Stamp = tl.LastUpdatedTime; np.Playing = pb.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing; np.Shuffle = pb.IsShuffleActive.HasValue && pb.IsShuffleActive.Value; np.Repeat = pb.AutoRepeatMode.HasValue ? (int)pb.AutoRepeatMode.Value : 0; np.CanShuffle = pb.Controls.IsShuffleEnabled; np.CanRepeat = pb.Controls.IsRepeatEnabled; np.CanSeek = pb.Controls.IsPlaybackPositionEnabled; string key = np.Title + "\u0001" + np.Artist + "\u0001" + np.Album; if (key != thumbKey) { thumbKey = key; Image img = null; if (pr.Thumbnail != null) { try { Windows.Storage.Streams.IRandomAccessStreamWithContentType st = await pr.Thumbnail.OpenReadAsync().AsTask(); using (Stream s = st.AsStreamForRead()) using (MemoryStream ms = new MemoryStream()) { s.CopyTo(ms); ms.Position = 0; using (Image raw = Image.FromStream(ms)) img = new Bitmap(raw); } } catch (Exception) { img = null; } } np.SetThumb(img); } if (!np.Found && !jamShown) { jamShown = true; SetMessage("Jamming? Control your media here! (Music tab)", false); } } smtcFails = 0; } catch (Exception) { smtcFails++; smtc = null; } finally { smtcBusy = false; np.Invalidate(); } } private async void MediaCommand(string c) { GlobalSystemMediaTransportControlsSession s = smtcSession; try { switch (c) { case "play": if (s != null) await s.TryTogglePlayPauseAsync().AsTask(); else MediaKey(179); break; case "next": if (s != null) await s.TrySkipNextAsync().AsTask(); else MediaKey(176); break; case "prev": if (s != null) await s.TrySkipPreviousAsync().AsTask(); else MediaKey(177); break; case "shuffle": if (s != null) await s.TryChangeShuffleActiveAsync(!np.Shuffle).AsTask(); break; case "repeat": if (s != null) { MediaPlaybackAutoRepeatMode next = np.Repeat == 0 ? MediaPlaybackAutoRepeatMode.List : np.Repeat == 2 ? MediaPlaybackAutoRepeatMode.Track : MediaPlaybackAutoRepeatMode.None; await s.TryChangeAutoRepeatModeAsync(next).AsTask(); } break; case "voldown": MediaKey(174); break; case "volup": MediaKey(175); break; case "mute": MediaKey(173); break; } } catch (Exception) { } npTicks = 3; PollMedia(); } private async void MediaSeek(double f) { GlobalSystemMediaTransportControlsSession s = smtcSession; if (s == null || np.End <= TimeSpan.Zero) return; try { TimeSpan to = TimeSpan.FromTicks((long)(np.End.Ticks * f)); np.Pos = to; np.Stamp = DateTimeOffset.Now; np.Invalidate(); await s.TryChangePlaybackPositionAsync(to.Ticks).AsTask(); } catch (Exception) { } PollMedia(); } private static void MediaKey(byte vk) { keybd_event(vk, 0, 1, UIntPtr.Zero); keybd_event(vk, 0, 3, UIntPtr.Zero); } } }