cu-trainer/Ultra Paradise Application/src/Lyrics.cs
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Drawing; |
| 4 | using System.Drawing.Drawing2D; |
| 5 | using System.Drawing.Text; |
| 6 | using System.Globalization; |
| 7 | using System.IO; |
| 8 | using System.Net; |
| 9 | using System.Security.Cryptography; |
| 10 | using System.Text; |
| 11 | using System.Text.RegularExpressions; |
| 12 | using System.Threading.Tasks; |
| 13 | using System.Windows.Forms; |
| 14 | |
| 15 | namespace UltraParadise |
| 16 | { |
| 17 | internal sealed class LyricsResult |
| 18 | { |
| 19 | public List<KeyValuePair<double, string>> Synced; |
| 20 | public string[] Plain; |
| 21 | public bool Instrumental; |
| 22 | public bool Failed; |
| 23 | } |
| 24 | |
| 25 | internal static class LyricsSource |
| 26 | { |
| 27 | private static string Dir |
| 28 | { |
| 29 | get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UltraParadise"), "lyrics"); } |
| 30 | } |
| 31 | |
| 32 | private static string CacheFile(string artist, string title) |
| 33 | { |
| 34 | using (SHA1 sha = SHA1.Create()) |
| 35 | { |
| 36 | byte[] h = sha.ComputeHash(Encoding.UTF8.GetBytes(artist.ToLowerInvariant() + "\n" + title.ToLowerInvariant())); |
| 37 | StringBuilder sb = new StringBuilder(); |
| 38 | foreach (byte b in h) sb.Append(b.ToString("x2", CultureInfo.InvariantCulture)); |
| 39 | return Path.Combine(Dir, sb.ToString() + ".txt"); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | public static LyricsResult Find(string artist, string title, string album, double len) |
| 44 | { |
| 45 | string file = CacheFile(artist, title); |
| 46 | LyricsResult cached = ReadCache(file); |
| 47 | if (cached != null) return cached; |
| 48 | LyricsResult r; |
| 49 | try |
| 50 | { |
| 51 | r = Search(title, artist, len); |
| 52 | if (r == null) |
| 53 | { |
| 54 | string ct = CleanTitle(title); |
| 55 | string ca = CleanArtist(artist); |
| 56 | if (ct != title || ca != artist) r = Search(ct, ca, len); |
| 57 | } |
| 58 | } |
| 59 | catch (Exception) { return new LyricsResult { Failed = true }; } |
| 60 | WriteCache(file, r); |
| 61 | return r ?? new LyricsResult(); |
| 62 | } |
| 63 | |
| 64 | public static string CleanTitle(string t) |
| 65 | { |
| 66 | string s = Regex.Replace(t, "\\s*[\\(\\[](feat\\.?|ft\\.?|with|official|lyric|lyrics|audio|video|visuali[sz]er|remaster|hd|hq|4k|mv|explicit)[^\\)\\]]*[\\)\\]]", "", RegexOptions.IgnoreCase); |
| 67 | s = Regex.Replace(s, "\\s+-\\s+(\\d{4}\\s+)?remaster(ed)?.*$", "", RegexOptions.IgnoreCase); |
| 68 | s = Regex.Replace(s, "\\s+(feat\\.?|ft\\.?)\\s+.*$", "", RegexOptions.IgnoreCase); |
| 69 | return s.Trim().Length > 0 ? s.Trim() : t; |
| 70 | } |
| 71 | |
| 72 | public static string CleanArtist(string a) |
| 73 | { |
| 74 | string s = Regex.Replace(a, "\\s*-\\s*Topic$", "", RegexOptions.IgnoreCase); |
| 75 | s = Regex.Replace(s, "VEVO$", "", RegexOptions.IgnoreCase); |
| 76 | int c = s.IndexOfAny(new char[] { ',', '&' }); |
| 77 | if (c > 0) s = s.Substring(0, c); |
| 78 | s = Regex.Replace(s, "\\s+(feat\\.?|ft\\.?|x)\\s+.*$", "", RegexOptions.IgnoreCase); |
| 79 | return s.Trim().Length > 0 ? s.Trim() : a; |
| 80 | } |
| 81 | |
| 82 | private static string Norm(string s) |
| 83 | { |
| 84 | StringBuilder sb = new StringBuilder(); |
| 85 | foreach (char c in s.ToLowerInvariant()) if (char.IsLetterOrDigit(c)) sb.Append(c); |
| 86 | return sb.ToString(); |
| 87 | } |
| 88 | |
| 89 | private static LyricsResult Search(string title, string artist, double len) |
| 90 | { |
| 91 | if (title.Trim().Length == 0) return null; |
| 92 | string url = "https://lrclib.net/api/search?track_name=" + Uri.EscapeDataString(title) + (artist.Trim().Length > 0 ? "&artist_name=" + Uri.EscapeDataString(artist) : ""); |
| 93 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 94 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); |
| 95 | req.Method = "GET"; |
| 96 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version + " (https://www.nexusmods.com/scavprototype/mods/1203)"; |
| 97 | req.Timeout = 10000; |
| 98 | req.ReadWriteTimeout = 15000; |
| 99 | string json; |
| 100 | using (WebResponse res = req.GetResponse()) |
| 101 | using (StreamReader rd = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 102 | { |
| 103 | char[] buf = new char[4 * 1024 * 1024]; |
| 104 | int total = 0, n; |
| 105 | while (total < buf.Length && (n = rd.Read(buf, total, buf.Length - total)) > 0) total += n; |
| 106 | json = new string(buf, 0, total); |
| 107 | } |
| 108 | System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); |
| 109 | js.MaxJsonLength = 8 * 1024 * 1024; |
| 110 | object[] arr = js.DeserializeObject(json) as object[]; |
| 111 | if (arr == null) return null; |
| 112 | string na = Norm(artist), nt = Norm(CleanTitle(title)); |
| 113 | Dictionary<string, object> best = null; |
| 114 | int bestScore = int.MinValue; |
| 115 | foreach (object o in arr) |
| 116 | { |
| 117 | Dictionary<string, object> d = o as Dictionary<string, object>; |
| 118 | if (d == null) continue; |
| 119 | string ra = Str(d, "artistName"), rt = Str(d, "trackName"); |
| 120 | string nra = Norm(ra), nrt = Norm(CleanTitle(rt)); |
| 121 | if (na.Length > 0 && !(nra.Contains(na) || na.Contains(nra))) continue; |
| 122 | if (nt.Length > 0 && !(nrt.Contains(nt) || nt.Contains(nrt))) continue; |
| 123 | double dur = Num(d, "duration"); |
| 124 | if (len > 0 && dur > 0 && Math.Abs(dur - len) > 6) continue; |
| 125 | int score = 0; |
| 126 | if (Str(d, "syncedLyrics").Length > 0) score += 100; |
| 127 | else if (Str(d, "plainLyrics").Length > 0) score += 40; |
| 128 | else if (Bool(d, "instrumental")) score += 20; |
| 129 | else continue; |
| 130 | if (nrt == nt) score += 10; |
| 131 | if (nra == na) score += 10; |
| 132 | if (len > 0 && dur > 0) score -= (int)Math.Abs(dur - len); |
| 133 | if (score > bestScore) { bestScore = score; best = d; } |
| 134 | } |
| 135 | if (best == null) return null; |
| 136 | LyricsResult r = new LyricsResult(); |
| 137 | r.Instrumental = Bool(best, "instrumental"); |
| 138 | string synced = Str(best, "syncedLyrics"); |
| 139 | if (synced.Length > 0) r.Synced = ParseLrc(synced); |
| 140 | string plain = Str(best, "plainLyrics"); |
| 141 | if (plain.Length > 0) r.Plain = plain.Replace("\r", "").Split('\n'); |
| 142 | if ((r.Synced == null || r.Synced.Count == 0) && r.Plain == null && !r.Instrumental) return null; |
| 143 | return r; |
| 144 | } |
| 145 | |
| 146 | private static string Str(Dictionary<string, object> d, string k) |
| 147 | { |
| 148 | object v; |
| 149 | return d.TryGetValue(k, out v) && v != null ? v.ToString() : ""; |
| 150 | } |
| 151 | |
| 152 | private static double Num(Dictionary<string, object> d, string k) |
| 153 | { |
| 154 | object v; |
| 155 | if (!d.TryGetValue(k, out v) || v == null) return 0; |
| 156 | double x; |
| 157 | return double.TryParse(Convert.ToString(v, CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out x) ? x : 0; |
| 158 | } |
| 159 | |
| 160 | private static bool Bool(Dictionary<string, object> d, string k) |
| 161 | { |
| 162 | object v; |
| 163 | return d.TryGetValue(k, out v) && v is bool && (bool)v; |
| 164 | } |
| 165 | |
| 166 | public static List<KeyValuePair<double, string>> ParseLrc(string lrc) |
| 167 | { |
| 168 | List<KeyValuePair<double, string>> list = new List<KeyValuePair<double, string>>(); |
| 169 | Regex tag = new Regex("\\[(\\d+):(\\d+(?:[\\.:]\\d+)?)\\]"); |
| 170 | foreach (string raw in lrc.Replace("\r", "").Split('\n')) |
| 171 | { |
| 172 | MatchCollection ms = tag.Matches(raw); |
| 173 | if (ms.Count == 0) continue; |
| 174 | Match last = ms[ms.Count - 1]; |
| 175 | string text = raw.Substring(last.Index + last.Length).Trim(); |
| 176 | foreach (Match m in ms) |
| 177 | { |
| 178 | double min = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); |
| 179 | double sec; |
| 180 | if (!double.TryParse(m.Groups[2].Value.Replace(':', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out sec)) continue; |
| 181 | list.Add(new KeyValuePair<double, string>(min * 60 + sec, text)); |
| 182 | } |
| 183 | } |
| 184 | list.Sort(delegate (KeyValuePair<double, string> a, KeyValuePair<double, string> b) { return a.Key.CompareTo(b.Key); }); |
| 185 | return list; |
| 186 | } |
| 187 | |
| 188 | private static LyricsResult ReadCache(string file) |
| 189 | { |
| 190 | try |
| 191 | { |
| 192 | if (!File.Exists(file)) return null; |
| 193 | string[] lines = File.ReadAllText(file, Encoding.UTF8).Replace("\r", "").Split('\n'); |
| 194 | if (lines.Length < 2 || lines[0] != "UPLYRICS 1") return null; |
| 195 | LyricsResult r = new LyricsResult(); |
| 196 | string body = string.Join("\n", lines, 2, lines.Length - 2); |
| 197 | switch (lines[1]) |
| 198 | { |
| 199 | case "S": r.Synced = ParseLrc(body); break; |
| 200 | case "P": r.Plain = body.Split('\n'); break; |
| 201 | case "I": r.Instrumental = true; break; |
| 202 | case "N": |
| 203 | if ((DateTime.UtcNow - File.GetLastWriteTimeUtc(file)).TotalDays > 3) return null; |
| 204 | break; |
| 205 | default: return null; |
| 206 | } |
| 207 | return r; |
| 208 | } |
| 209 | catch (Exception) { return null; } |
| 210 | } |
| 211 | |
| 212 | private static void WriteCache(string file, LyricsResult r) |
| 213 | { |
| 214 | try |
| 215 | { |
| 216 | Directory.CreateDirectory(Dir); |
| 217 | StringBuilder sb = new StringBuilder("UPLYRICS 1\n"); |
| 218 | if (r != null && r.Synced != null && r.Synced.Count > 0) |
| 219 | { |
| 220 | sb.Append("S\n"); |
| 221 | foreach (KeyValuePair<double, string> kv in r.Synced) |
| 222 | { |
| 223 | int cs = (int)Math.Round(kv.Key * 100); |
| 224 | sb.Append('[').Append((cs / 6000).ToString("00", CultureInfo.InvariantCulture)).Append(':') |
| 225 | .Append((cs / 100 % 60).ToString("00", CultureInfo.InvariantCulture)).Append('.') |
| 226 | .Append((cs % 100).ToString("00", CultureInfo.InvariantCulture)).Append(']').Append(kv.Value).Append('\n'); |
| 227 | } |
| 228 | } |
| 229 | else if (r != null && r.Plain != null) sb.Append("P\n").Append(string.Join("\n", r.Plain)); |
| 230 | else if (r != null && r.Instrumental) sb.Append("I\n"); |
| 231 | else sb.Append("N\n"); |
| 232 | File.WriteAllText(file, sb.ToString(), new UTF8Encoding(false)); |
| 233 | } |
| 234 | catch (Exception) { } |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | internal class LyricsCard : Control |
| 239 | { |
| 240 | public LyricsResult Result; |
| 241 | public string State = ""; |
| 242 | public string Song = ""; |
| 243 | public bool On = true; |
| 244 | public Func<double> Position; |
| 245 | public Func<double> Length; |
| 246 | public event Action Toggle; |
| 247 | |
| 248 | private Rectangle toggleRect; |
| 249 | private bool hoverToggle; |
| 250 | private readonly Font head = Theme.F("Segoe UI Semibold", 8f); |
| 251 | private readonly Font cur = Theme.F("Segoe UI Semibold", 12.5f); |
| 252 | private readonly Font line = Theme.F("Segoe UI", 10.5f); |
| 253 | private readonly Font small = Theme.F("Segoe UI", 8.5f); |
| 254 | |
| 255 | public LyricsCard() |
| 256 | { |
| 257 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); |
| 258 | } |
| 259 | |
| 260 | private static GraphicsPath Round(Rectangle r, int rad) |
| 261 | { |
| 262 | int d = Math.Max(1, rad * 2); |
| 263 | GraphicsPath p = new GraphicsPath(); |
| 264 | p.AddArc(r.X, r.Y, d, d, 180, 90); |
| 265 | p.AddArc(r.Right - d, r.Y, d, d, 270, 90); |
| 266 | p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90); |
| 267 | p.AddArc(r.X, r.Bottom - d, d, d, 90, 90); |
| 268 | p.CloseFigure(); |
| 269 | return p; |
| 270 | } |
| 271 | |
| 272 | public int CurrentIndex() |
| 273 | { |
| 274 | if (Result == null || Result.Synced == null || Result.Synced.Count == 0 || Position == null) return -1; |
| 275 | double pos = Position() + 0.2; |
| 276 | int i = -1; |
| 277 | for (int k = 0; k < Result.Synced.Count; k++) |
| 278 | { |
| 279 | if (Result.Synced[k].Key <= pos) i = k; |
| 280 | else break; |
| 281 | } |
| 282 | return i; |
| 283 | } |
| 284 | |
| 285 | public string CurrentLine() |
| 286 | { |
| 287 | int i = CurrentIndex(); |
| 288 | return i >= 0 ? Result.Synced[i].Value : null; |
| 289 | } |
| 290 | |
| 291 | protected override void OnPaint(PaintEventArgs e) |
| 292 | { |
| 293 | Graphics g = e.Graphics; |
| 294 | g.SmoothingMode = SmoothingMode.AntiAlias; |
| 295 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 296 | g.Clear(Theme.Back); |
| 297 | int W = Width, H = Height, pad = Theme.S(16); |
| 298 | using (GraphicsPath p = Round(new Rectangle(0, 0, W - 1, H - 1), Theme.S(10))) |
| 299 | { |
| 300 | using (SolidBrush b = new SolidBrush(Theme.Panel)) g.FillPath(b, p); |
| 301 | using (Pen pe = new Pen(Theme.Line)) g.DrawPath(pe, p); |
| 302 | } |
| 303 | StringFormat l = new StringFormat(); l.LineAlignment = StringAlignment.Center; l.Trimming = StringTrimming.EllipsisCharacter; l.FormatFlags = StringFormatFlags.NoWrap; |
| 304 | StringFormat c = new StringFormat(l); c.Alignment = StringAlignment.Center; |
| 305 | StringFormat r = new StringFormat(l); r.Alignment = StringAlignment.Far; |
| 306 | int y = Theme.S(12); |
| 307 | using (SolidBrush o = new SolidBrush(Theme.Orange)) g.DrawString(Theme.Spaced("LYRICS"), head, o, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), l); |
| 308 | string tg = On ? "Hide" : "Show"; |
| 309 | SizeF ts = g.MeasureString(tg, small); |
| 310 | toggleRect = new Rectangle(W - pad - (int)ts.Width - Theme.S(8), y - Theme.S(2), (int)ts.Width + Theme.S(8), Theme.S(22)); |
| 311 | using (SolidBrush tb = new SolidBrush(hoverToggle ? Theme.Orange : Theme.Soft)) g.DrawString(tg, small, tb, toggleRect, c); |
| 312 | y += Theme.S(22); |
| 313 | if (On && Song.Length > 0) |
| 314 | using (SolidBrush sb = new SolidBrush(Theme.Dim)) g.DrawString(Song, small, sb, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), l); |
| 315 | y += Theme.S(22); |
| 316 | int footH = Theme.S(22); |
| 317 | Rectangle body = new Rectangle(pad, y, W - pad * 2, Math.Max(Theme.S(30), H - y - footH)); |
| 318 | |
| 319 | if (!On) Message(g, body, "Lyrics are off. Click Show to turn them back on."); |
| 320 | else if (Result != null && Result.Synced != null && Result.Synced.Count > 0) DrawSynced(g, body, c); |
| 321 | else if (Result != null && Result.Plain != null) DrawPlain(g, body, c); |
| 322 | else if (Result != null && Result.Instrumental) Message(g, body, "Instrumental. No lyrics to show."); |
| 323 | else Message(g, body, State); |
| 324 | |
| 325 | using (SolidBrush fb = new SolidBrush(Theme.Faint)) |
| 326 | g.DrawString(On ? "Lyrics from LRCLIB (lrclib.net)" : "", small, fb, new RectangleF(pad, H - footH - Theme.S(4), W - pad * 2, footH), c); |
| 327 | } |
| 328 | |
| 329 | private void Message(Graphics g, Rectangle body, string text) |
| 330 | { |
| 331 | StringFormat m = new StringFormat(); m.Alignment = StringAlignment.Center; m.LineAlignment = StringAlignment.Center; |
| 332 | using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString(text ?? "", line, b, body, m); |
| 333 | } |
| 334 | |
| 335 | private double animFrom = double.NaN, animTo = double.NaN, center; |
| 336 | private DateTime animAt = DateTime.MinValue; |
| 337 | private object animFor; |
| 338 | |
| 339 | public bool Animating |
| 340 | { |
| 341 | get { return On && Visible && Result != null && Result.Synced != null && Result.Synced.Count > 0; } |
| 342 | } |
| 343 | |
| 344 | private static double Ease(double t) |
| 345 | { |
| 346 | t = Math.Max(0, Math.Min(1, t)); |
| 347 | return 1 - Math.Pow(1 - t, 3); |
| 348 | } |
| 349 | |
| 350 | private static Color Mix(Color a, Color b, double t) |
| 351 | { |
| 352 | t = Math.Max(0, Math.Min(1, t)); |
| 353 | return Color.FromArgb((int)(a.A + (b.A - a.A) * t), (int)(a.R + (b.R - a.R) * t), (int)(a.G + (b.G - a.G) * t), (int)(a.B + (b.B - a.B) * t)); |
| 354 | } |
| 355 | |
| 356 | private static Color Fade(Color c, double a) |
| 357 | { |
| 358 | return Color.FromArgb(Math.Max(0, Math.Min(255, (int)(255 * a))), c); |
| 359 | } |
| 360 | |
| 361 | private void DrawSynced(Graphics g, Rectangle body, StringFormat c) |
| 362 | { |
| 363 | List<KeyValuePair<double, string>> s = Result.Synced; |
| 364 | int i = CurrentIndex(); |
| 365 | DateTime now = DateTime.UtcNow; |
| 366 | if (animFor != Result || double.IsNaN(animTo)) |
| 367 | { |
| 368 | animFor = Result; |
| 369 | animFrom = animTo = center = i; |
| 370 | animAt = DateTime.MinValue; |
| 371 | } |
| 372 | else if (i != animTo) |
| 373 | { |
| 374 | animFrom = Math.Abs(i - center) > 3 ? i : center; |
| 375 | animTo = i; |
| 376 | animAt = now; |
| 377 | } |
| 378 | double e = Ease((now - animAt).TotalMilliseconds / 380.0); |
| 379 | center = animFrom + (animTo - animFrom) * e; |
| 380 | |
| 381 | int lh = Theme.S(30); |
| 382 | int half = Math.Max(1, body.Height / lh / 2); |
| 383 | float mid = body.Y + body.Height / 2f; |
| 384 | GraphicsState st = g.Save(); |
| 385 | g.SetClip(body); |
| 386 | |
| 387 | if (i >= 0) |
| 388 | { |
| 389 | string ct = s[i].Value.Length > 0 ? s[i].Value : "♪"; |
| 390 | SizeF sz = g.MeasureString(ct, cur); |
| 391 | float hw = Math.Min(body.Width, sz.Width + Theme.S(40)); |
| 392 | float hy = mid + (float)((i - center) * lh) - lh / 2f; |
| 393 | Rectangle hr = Rectangle.Round(new RectangleF(body.X + (body.Width - hw) / 2f, hy + Theme.S(1), hw, lh - Theme.S(2))); |
| 394 | double fade = 0.45 + 0.55 * e; |
| 395 | if (hr.Width > 2 && hr.Height > 2) |
| 396 | using (GraphicsPath hp = Round(hr, hr.Height / 2)) |
| 397 | { |
| 398 | using (LinearGradientBrush lg = new LinearGradientBrush(hr, Color.Black, Color.Black, LinearGradientMode.Horizontal)) |
| 399 | { |
| 400 | ColorBlend cb = new ColorBlend(3); |
| 401 | cb.Colors = new Color[] { Fade(Theme.Orange, 0.06 * fade), Fade(Theme.Orange, 0.34 * fade), Fade(Theme.Orange, 0.06 * fade) }; |
| 402 | cb.Positions = new float[] { 0f, 0.5f, 1f }; |
| 403 | lg.InterpolationColors = cb; |
| 404 | g.FillPath(lg, hp); |
| 405 | } |
| 406 | double start = s[i].Key; |
| 407 | double end = i + 1 < s.Count ? s[i + 1].Key : start + 4; |
| 408 | double prog = Position != null ? Math.Max(0, Math.Min(1, (Position() - start) / Math.Max(0.3, end - start))) : 0; |
| 409 | int pw = (int)(hr.Width * prog); |
| 410 | if (pw > 2) |
| 411 | { |
| 412 | Rectangle pr = new Rectangle(hr.X, hr.Y, pw, hr.Height); |
| 413 | GraphicsState ps = g.Save(); |
| 414 | g.SetClip(hp, CombineMode.Intersect); |
| 415 | using (LinearGradientBrush sweep = new LinearGradientBrush(new Rectangle(pr.X - 1, pr.Y, pr.Width + 2, pr.Height), Fade(Theme.Orange, 0.04 * fade), Fade(Theme.Orange, 0.42 * fade), LinearGradientMode.Horizontal)) |
| 416 | g.FillRectangle(sweep, pr); |
| 417 | g.Restore(ps); |
| 418 | } |
| 419 | using (Pen pe = new Pen(Fade(Theme.Orange, 0.55 * fade), Math.Max(1f, Theme.S(1)))) |
| 420 | g.DrawPath(pe, hp); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | int from = (int)Math.Floor(center) - half - 1, to = (int)Math.Ceiling(center) + half + 1; |
| 425 | for (int idx = Math.Max(0, from); idx <= to && idx < s.Count; idx++) |
| 426 | { |
| 427 | double d = Math.Abs(idx - center); |
| 428 | float y = mid + (float)((idx - center) * lh) - lh / 2f; |
| 429 | string t = s[idx].Value.Length > 0 ? s[idx].Value : "♪"; |
| 430 | Color col = idx == i ? Mix(Theme.Bright, Theme.Text, d) : d <= 1 ? Mix(Theme.Text, Theme.Soft, d * 0.6) : d <= 2 ? Mix(Theme.Soft, Theme.Faint, d - 1) : Theme.Faint; |
| 431 | using (SolidBrush b = new SolidBrush(col)) |
| 432 | g.DrawString(t, idx == i ? cur : line, b, new RectangleF(body.X, y, body.Width, lh), c); |
| 433 | } |
| 434 | if (i < 0) |
| 435 | using (SolidBrush b = new SolidBrush(Theme.Dim)) |
| 436 | g.DrawString("♪", cur, b, new RectangleF(body.X, mid - lh / 2f, body.Width, lh), c); |
| 437 | g.Restore(st); |
| 438 | } |
| 439 | |
| 440 | private void DrawPlain(Graphics g, Rectangle body, StringFormat c) |
| 441 | { |
| 442 | List<string> lines = new List<string>(); |
| 443 | foreach (string s in Result.Plain) if (s.Trim().Length > 0) lines.Add(s.Trim()); |
| 444 | if (lines.Count == 0) { Message(g, body, "No lyrics found for this song."); return; } |
| 445 | double len = Length != null ? Length() : 0, pos = Position != null ? Position() : 0; |
| 446 | int lh = Theme.S(24); |
| 447 | int rows = Math.Max(1, (body.Height - Theme.S(20)) / lh); |
| 448 | int at = len > 0 ? (int)(lines.Count * Math.Max(0, Math.Min(1, pos / len))) : 0; |
| 449 | int first = Math.Max(0, Math.Min(lines.Count - rows, at - rows / 2)); |
| 450 | using (SolidBrush nb = new SolidBrush(Theme.Faint)) |
| 451 | g.DrawString("Not synced: these lyrics have no timings", Theme.F("Segoe UI", 8f), nb, new RectangleF(body.X, body.Y, body.Width, Theme.S(18)), c); |
| 452 | for (int k = 0; k < rows && first + k < lines.Count; k++) |
| 453 | using (SolidBrush b = new SolidBrush(Theme.Text)) |
| 454 | g.DrawString(lines[first + k], line, b, new RectangleF(body.X, body.Y + Theme.S(20) + k * lh, body.Width, lh), c); |
| 455 | } |
| 456 | |
| 457 | protected override void OnMouseMove(MouseEventArgs e) |
| 458 | { |
| 459 | bool h = toggleRect.Contains(e.Location); |
| 460 | if (h != hoverToggle) { hoverToggle = h; Invalidate(); } |
| 461 | Cursor = h ? Cursors.Hand : Cursors.Default; |
| 462 | } |
| 463 | |
| 464 | protected override void OnMouseLeave(EventArgs e) |
| 465 | { |
| 466 | if (hoverToggle) { hoverToggle = false; Invalidate(); } |
| 467 | } |
| 468 | |
| 469 | protected override void OnMouseDown(MouseEventArgs e) |
| 470 | { |
| 471 | if (e.Button == MouseButtons.Left && toggleRect.Contains(e.Location) && Toggle != null) Toggle(); |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | internal partial class MainForm |
| 476 | { |
| 477 | private readonly LyricsCard lyr = new LyricsCard(); |
| 478 | private string lyrKey; |
| 479 | private int lyrReq, lyrSource; |
| 480 | private DateTime lyrRetry = DateTime.MaxValue; |
| 481 | private DateTime gmStamp = DateTime.UtcNow; |
| 482 | |
| 483 | private void SetupLyrics() |
| 484 | { |
| 485 | lyr.Visible = false; |
| 486 | lyr.On = Get("lyrics", "1") == "1"; |
| 487 | lyr.State = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here."; |
| 488 | lyr.Position = LyricsPos; |
| 489 | lyr.Length = delegate { return lyrSource == 2 ? gmLen : np.End.TotalSeconds; }; |
| 490 | lyr.Toggle += delegate |
| 491 | { |
| 492 | lyr.On = !lyr.On; |
| 493 | settings["lyrics"] = lyr.On ? "1" : "0"; |
| 494 | Settings.Save(settings); |
| 495 | lyrKey = null; |
| 496 | LyricsCheck(); |
| 497 | lyr.Invalidate(); |
| 498 | }; |
| 499 | view.Controls.Add(lyr); |
| 500 | System.Windows.Forms.Timer anim = new System.Windows.Forms.Timer(); |
| 501 | anim.Interval = 16; |
| 502 | anim.Tick += delegate { if (lyr.Animating) lyr.Invalidate(); }; |
| 503 | anim.Start(); |
| 504 | } |
| 505 | |
| 506 | private double LyricsPos() |
| 507 | { |
| 508 | if (lyrSource == 2) |
| 509 | { |
| 510 | double p = gmPos; |
| 511 | if (gmPlaying) p += Math.Max(0, Math.Min(2, (DateTime.UtcNow - gmStamp).TotalSeconds)); |
| 512 | return p; |
| 513 | } |
| 514 | return np.LivePos().TotalSeconds; |
| 515 | } |
| 516 | |
| 517 | private static bool SplitFileSong(string file, out string artist, out string title) |
| 518 | { |
| 519 | artist = title = ""; |
| 520 | string n = Path.GetFileNameWithoutExtension(file ?? ""); |
| 521 | n = Regex.Replace(n, "^\\d{1,3}[\\s\\.\\-_]+", ""); |
| 522 | int d = n.IndexOf(" - ", StringComparison.Ordinal); |
| 523 | if (d <= 0 || d >= n.Length - 3) return false; |
| 524 | artist = n.Substring(0, d).Trim(); |
| 525 | title = n.Substring(d + 3).Trim(); |
| 526 | return artist.Length > 0 && title.Length > 0; |
| 527 | } |
| 528 | |
| 529 | private void LyricsCheck() |
| 530 | { |
| 531 | if (!lyr.On) { lyr.Result = null; lyr.Song = ""; return; } |
| 532 | string title = "", artist = "", album = ""; |
| 533 | double len = 0; |
| 534 | int src = 0; |
| 535 | if (np.Has && np.Title.Length > 0 && (np.Playing || !(gmRun && gmPlaying))) |
| 536 | { |
| 537 | title = np.Title; artist = np.Artist; album = np.Album; len = np.End.TotalSeconds; src = 1; |
| 538 | } |
| 539 | else if (gmRun && gmPlaying && gmSong.Length > 0) |
| 540 | { |
| 541 | src = 2; |
| 542 | len = gmLen; |
| 543 | if (!SplitFileSong(gmSong, out artist, out title)) |
| 544 | { |
| 545 | lyrSource = 2; |
| 546 | if (lyrKey != "file:" + gmSong) |
| 547 | { |
| 548 | lyrKey = "file:" + gmSong; |
| 549 | lyr.Result = null; |
| 550 | lyr.Song = gmSong; |
| 551 | lyr.State = "To get lyrics for songs in the game's MP3 player, name the file \"Artist - Title\" (for example \"Daft Punk - One More Time.mp3\")."; |
| 552 | lyr.Invalidate(); |
| 553 | } |
| 554 | return; |
| 555 | } |
| 556 | } |
| 557 | if (src == 0) |
| 558 | { |
| 559 | if (lyrKey != null) |
| 560 | { |
| 561 | lyrKey = null; |
| 562 | lyr.Result = null; |
| 563 | lyr.Song = ""; |
| 564 | lyr.State = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here."; |
| 565 | lyr.Invalidate(); |
| 566 | } |
| 567 | return; |
| 568 | } |
| 569 | lyrSource = src; |
| 570 | string key = artist + "\u0001" + title; |
| 571 | if (key == lyrKey && DateTime.UtcNow < lyrRetry) return; |
| 572 | lyrKey = key; |
| 573 | lyrRetry = DateTime.MaxValue; |
| 574 | lyr.Result = null; |
| 575 | lyr.Song = (artist.Length > 0 ? artist + " - " : "") + title; |
| 576 | lyr.State = "Looking up the lyrics..."; |
| 577 | lyr.Invalidate(); |
| 578 | int req = ++lyrReq; |
| 579 | string a = artist, t = title, al = album; |
| 580 | double ln = len; |
| 581 | Task.Run(delegate |
| 582 | { |
| 583 | LyricsResult r = LyricsSource.Find(a, t, al, ln); |
| 584 | try |
| 585 | { |
| 586 | BeginInvoke((Action)delegate |
| 587 | { |
| 588 | if (req != lyrReq) return; |
| 589 | if (r.Failed) |
| 590 | { |
| 591 | lyr.State = "Couldn't reach the lyrics service. Trying again in a minute."; |
| 592 | lyrRetry = DateTime.UtcNow.AddMinutes(1); |
| 593 | } |
| 594 | else if (r.Synced == null && r.Plain == null && !r.Instrumental) lyr.State = "No lyrics found for this song."; |
| 595 | lyr.Result = r.Failed ? null : r; |
| 596 | lyr.Invalidate(); |
| 597 | }); |
| 598 | } |
| 599 | catch (Exception) { } |
| 600 | }); |
| 601 | } |
| 602 | } |
| 603 | } |