XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

HaloPixelToolBox

【WinUI3】基于USB HID通讯的花再音响工具箱

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/HaloPixelToolBox

新增主页及重构歌词同步与解析架构

本次更新引入全新 MainPage 主页,优化导航与默认启动页面,支持主页、网易云、Spotify 三种启动选项。重构网易云歌词同步,新增 CloudMusicOnlineLyricsReader,优先在线同步,内存读取兜底。歌词解析与模型结构调整,LyricLine、LrcParser 独立,提升 LRC 兼容性并增加单元测试。底层抽象 SynchronizedLyricsReader,支持多平台歌词同步与主色提取。设置与界面细节全面升级,统一风格,提升易用性。默认启动页改为 MainPage,代码风格与注释优化。

c3474d8
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

14 个文件 +694 -245
Modified Client/HaloPixelToolBox.Client.Test/Program.cs +11 -1
@@ -12,4 +12,14 @@ internal class Program
12 12 var device = new HaloPixelDevice();
13 13 device.Initialize();
14 14 }
15 }
15
16 [SMTest]
17 public static void ParseLrcLyrics()
18 {
19 var lines = LrcParser.Parse("[00:02.50]第二句\n[00:01.005]第一句\n[00:03.5]第三句");
20 XFECode.Assert(lines.Count == 3, "应解析出三行歌词");
21 XFECode.Assert(lines[0].Text == "第一句" && lines[0].Timestamp.TotalMilliseconds == 1005, "三位毫秒时间戳解析错误");
22 XFECode.Assert(lines[1].Text == "第二句" && lines[1].Timestamp.TotalMilliseconds == 2500, "两位百分秒时间戳解析错误");
23 XFECode.Assert(lines[2].Text == "第三句" && lines[2].Timestamp.TotalMilliseconds == 3500, "一位十分秒时间戳解析错误");
24 }
25 }
Modified Client/HaloPixelToolBox.Client/Profiles/CrossVersionProfiles/SystemProfile.cs +1 -1
@@ -47,7 +47,7 @@ public partial class SystemProfile : XFEProfile
47 47 /// 默认启动页面
48 48 /// </summary>
49 49 [ProfileProperty]
50 private string defaultPage = "CloudMusicLyricsToolPage";
50 private string defaultPage = "MainPage";
51 51
52 52 static partial void SetThemeProperty(ref ElementTheme value) => AppThemeHelper.ChangeTheme(value);
53 53 }
Modified Client/HaloPixelToolBox.Client/Utilities/SpotifyLyricsReader.cs +129 -130
@@ -9,65 +9,13 @@ using System.Text.Json.Serialization;
9 9 using System.Text.RegularExpressions;
10 10 using System.Threading;
11 11 using System.Threading.Tasks;
12 using HaloPixelToolBox.Core.Models.Lyrics;
13 using HaloPixelToolBox.Core.Utilities;
12 14 using Windows.Media.Control;
13 15 using XFEExtension.NetCore.WinUIHelper.Utilities.Helper;
14 16
15 17 namespace HaloPixelToolBox.Client.Utilities;
16 18
17 public class LyricLine
18 {
19 public TimeSpan Timestamp { get; set; }
20 public string Text { get; set; } = string.Empty;
21 }
22
23 public static class LrcParser
24 {
25 private static readonly Regex LrcTimeRegex = new Regex(@"\[(\d+):(\d+)(?:[:\.](\d+))?\]", RegexOptions.Compiled);
26 private static readonly Regex CleanTimecodeRegex = new Regex(@"\[\d+:\d+(?:[:\.]\d+)?\]", RegexOptions.Compiled);
27
28 public static List<LyricLine> Parse(string lrcContent)
29 {
30 var lines = new List<LyricLine>();
31 if (string.IsNullOrWhiteSpace(lrcContent))
32 return lines;
33
34 var rawLines = lrcContent.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
35 foreach (var line in rawLines)
36 {
37 var match = LrcTimeRegex.Match(line);
38 if (match.Success)
39 {
40 var minutes = int.Parse(match.Groups[1].Value);
41 var seconds = int.Parse(match.Groups[2].Value);
42 var fractionStr = match.Groups[3].Value;
43 var milliseconds = 0;
44 if (!string.IsNullOrEmpty(fractionStr))
45 {
46 if (fractionStr.Length == 2)
47 milliseconds = int.Parse(fractionStr) * 10;
48 else if (fractionStr.Length == 3)
49 milliseconds = int.Parse(fractionStr);
50 else
51 milliseconds = int.Parse(fractionStr.Substring(0, 3));
52 }
53
54 var timestamp = new TimeSpan(0, 0, minutes, seconds, milliseconds);
55 var text = line.Substring(match.Length).Trim();
56
57 // Strip any remaining timecodes from the lyric text (e.g. "[00:00.00]" or "[00:00:000]")
58 text = CleanTimecodeRegex.Replace(text, "").Trim();
59
60 if (!string.IsNullOrEmpty(text))
61 {
62 lines.Add(new LyricLine { Timestamp = timestamp, Text = text });
63 }
64 }
65 }
66 lines.Sort((a, b) => a.Timestamp.CompareTo(b.Timestamp));
67 return lines;
68 }
69 }
70
71 19 public class LrclibResponse
72 20 {
73 21 [JsonPropertyName("plainLyrics")]
@@ -81,12 +29,24 @@ public class LrclibResponse
81 29
82 30 [JsonPropertyName("artistName")]
83 31 public string? ArtistName { get; set; }
32
33 [JsonPropertyName("albumName")]
34 public string? AlbumName { get; set; }
84 35 }
85 36
86 public class SpotifyLyricsReader
37 /// <summary>
38 /// 通过 Windows SMTC 获取播放信息,并从 LRCLIB 获取和同步逐行歌词。
39 /// </summary>
40 public class SynchronizedLyricsReader
87 41 {
42 private readonly string _sourceName;
43 private readonly string _sessionAppId;
44 private readonly string _processName;
45 private readonly bool _useWindowTitleMetadata;
88 46 private static HttpClient? _httpClient;
89 47 private static readonly object HttpLock = new object();
48 private static readonly SemaphoreSlim LrclibRequestLock = new(1, 1);
49 private static DateTimeOffset _lastLrclibRequestTime = DateTimeOffset.MinValue;
90 50
91 51 private static HttpClient HttpClient
92 52 {
@@ -113,8 +73,9 @@ public class SpotifyLyricsReader
113 73
114 74 private string _currentTitle = string.Empty;
115 75 private string _currentArtist = string.Empty;
76 private string _currentAlbum = string.Empty;
116 77 private double _currentDuration = 0;
117 private List<LyricLine> _lyricLines = new();
78 private IReadOnlyList<LyricLine> _lyricLines = [];
118 79
119 80 private DateTimeOffset _songStartTime = DateTimeOffset.Now;
120 81 private bool _isSmtcSynced = false;
@@ -122,6 +83,18 @@ public class SpotifyLyricsReader
122 83
123 84 public (byte R, byte G, byte B)? CurrentAlbumColor { get; private set; }
124 85
86 public bool HasSynchronizedLyrics => _lyricLines.Count > 0;
87
88 public bool IsSessionAvailable => _currentSession is not null;
89
90 protected SynchronizedLyricsReader(string sourceName, string sessionAppId, string processName, bool useWindowTitleMetadata)
91 {
92 _sourceName = sourceName;
93 _sessionAppId = sessionAppId;
94 _processName = processName;
95 _useWindowTitleMetadata = useWindowTitleMetadata;
96 }
97
125 98 public bool IsPlaying
126 99 {
127 100 get
@@ -184,11 +157,7 @@ public class SpotifyLyricsReader
184 157
185 158 private static HttpClient CreateHttpClient()
186 159 {
187 var handler = new HttpClientHandler
188 {
189 // Ignore certificate errors to bypass any MITM issues caused by local proxy clients decrypting HTTPS
190 ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
191 };
160 var handler = new HttpClientHandler();
192 161
193 162 // List of common local proxy ports in China:
194 163 // 7890: Clash / Mihomo
@@ -211,7 +180,7 @@ public class SpotifyLyricsReader
211 180
212 181 var client = new HttpClient(handler);
213 182 client.DefaultRequestHeaders.UserAgent.Clear();
214 client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
183 client.DefaultRequestHeaders.UserAgent.ParseAdd("HaloPixelToolBox/1.3.0 (https://github.com/XFEstudio/HaloPixelToolBox)");
215 184
216 185 if (proxyConfigured)
217 186 {
@@ -240,6 +209,39 @@ public class SpotifyLyricsReader
240 209 return false;
241 210 }
242 211
212 private static async Task<HttpResponseMessage> GetFromLrclibAsync(string requestUri, CancellationToken token)
213 {
214 await LrclibRequestLock.WaitAsync(token);
215 try
216 {
217 var delay = TimeSpan.FromMilliseconds(300) - (DateTimeOffset.UtcNow - _lastLrclibRequestTime);
218 if (delay > TimeSpan.Zero)
219 await Task.Delay(delay, token);
220
221 var response = await HttpClient.GetAsync(requestUri, token);
222 _lastLrclibRequestTime = DateTimeOffset.UtcNow;
223 if (response.StatusCode != HttpStatusCode.TooManyRequests)
224 return response;
225
226 var retryDelay = response.Headers.RetryAfter?.Delta ??
227 response.Headers.RetryAfter?.Date - DateTimeOffset.UtcNow ??
228 TimeSpan.FromSeconds(5);
229 response.Dispose();
230 if (retryDelay < TimeSpan.Zero)
231 retryDelay = TimeSpan.Zero;
232
233 Console.WriteLine($"LRCLIB rate limit reached; retrying after {retryDelay.TotalSeconds:F0} seconds.");
234 await Task.Delay(retryDelay, token);
235 var retryResponse = await HttpClient.GetAsync(requestUri, token);
236 _lastLrclibRequestTime = DateTimeOffset.UtcNow;
237 return retryResponse;
238 }
239 finally
240 {
241 LrclibRequestLock.Release();
242 }
243 }
244
243 245 private static async Task<T?> RunWithTimeout<T>(Windows.Foundation.IAsyncOperation<T> asyncOp, int timeoutMs)
244 246 {
245 247 using var cts = new CancellationTokenSource();
@@ -267,11 +269,11 @@ public class SpotifyLyricsReader
267 269
268 270 public bool Initialize()
269 271 {
270 Console.WriteLine($"Initialize called. isInitialized={_isInitialized}");
272 Console.WriteLine($"{_sourceName} lyrics initialize called. isInitialized={_isInitialized}");
271 273 if (_isInitialized)
272 274 {
273 275 UpdateCurrentSession();
274 return _currentSession != null || Process.GetProcessesByName("Spotify").Length > 0;
276 return _currentSession != null || Process.GetProcessesByName(_processName).Length > 0;
275 277 }
276 278
277 279 try
@@ -283,13 +285,13 @@ public class SpotifyLyricsReader
283 285 _isInitialized = true;
284 286 UpdateCurrentSession();
285 287 StartWindowTitlePolling();
286 return _currentSession != null || Process.GetProcessesByName("Spotify").Length > 0;
288 return _currentSession != null || Process.GetProcessesByName(_processName).Length > 0;
287 289 });
288 290 return task.Result;
289 291 }
290 292 catch (Exception ex)
291 293 {
292 Console.WriteLine($"SpotifyLyricsReader Initialize failed: {ex.Message}");
294 Console.WriteLine($"{_sourceName} lyrics reader initialize failed: {ex.Message}");
293 295 return false;
294 296 }
295 297 }
@@ -305,19 +307,19 @@ public class SpotifyLyricsReader
305 307 if (_manager == null) return;
306 308
307 309 var sessions = _manager.GetSessions();
308 GlobalSystemMediaTransportControlsSession? spotifySession = null;
310 GlobalSystemMediaTransportControlsSession? targetSession = null;
309 311 foreach (var s in sessions)
310 312 {
311 if (s.SourceAppUserModelId.Contains("Spotify", StringComparison.OrdinalIgnoreCase))
313 if (s.SourceAppUserModelId.Contains(_sessionAppId, StringComparison.OrdinalIgnoreCase))
312 314 {
313 spotifySession = s;
315 targetSession = s;
314 316 break;
315 317 }
316 318 }
317 319
318 if (spotifySession != _currentSession)
320 if (targetSession != _currentSession)
319 321 {
320 Console.WriteLine($"Active session changed. Old: {_currentSession?.SourceAppUserModelId ?? "null"}, New: {spotifySession?.SourceAppUserModelId ?? "null"}");
322 Console.WriteLine($"{_sourceName} session changed. Old: {_currentSession?.SourceAppUserModelId ?? "null"}, New: {targetSession?.SourceAppUserModelId ?? "null"}");
321 323 if (_currentSession != null)
322 324 {
323 325 _currentSession.MediaPropertiesChanged -= OnMediaPropertiesChanged;
@@ -325,7 +327,7 @@ public class SpotifyLyricsReader
325 327 _currentSession.TimelinePropertiesChanged -= OnTimelinePropertiesChanged;
326 328 }
327 329
328 _currentSession = spotifySession;
330 _currentSession = targetSession;
329 331
330 332 if (_currentSession != null)
331 333 {
@@ -370,6 +372,7 @@ public class SpotifyLyricsReader
370 372 {
371 373 var timeline = _currentSession.GetTimelineProperties();
372 374 _currentDuration = timeline?.EndTime.TotalSeconds ?? 0;
375 _currentAlbum = media.AlbumTitle ?? string.Empty;
373 376 _isSmtcSynced = true;
374 377 Console.WriteLine($"SMTC Sync Achieved for: {_currentArtist} - {_currentTitle} (Duration: {_currentDuration}s)");
375 378
@@ -423,7 +426,7 @@ public class SpotifyLyricsReader
423 426 if (trackInfo.Artist != _currentArtist || trackInfo.Title != _currentTitle)
424 427 {
425 428 Console.WriteLine($"Track change detected via polling: {trackInfo.Artist} - {trackInfo.Title}");
426 _ = HandleTrackChangeAsync(trackInfo.Artist, trackInfo.Title);
429 _ = HandleTrackChangeAsync(trackInfo.Artist, trackInfo.Title, trackInfo.Album);
427 430 }
428 431 }
429 432 else
@@ -433,7 +436,9 @@ public class SpotifyLyricsReader
433 436 Console.WriteLine("No active track detected, clearing lyrics.");
434 437 _currentTitle = string.Empty;
435 438 _currentArtist = string.Empty;
436 _lyricLines.Clear();
439 _currentAlbum = string.Empty;
440 CurrentAlbumColor = null;
441 _lyricLines = [];
437 442 }
438 443 }
439 444 }
@@ -446,9 +451,9 @@ public class SpotifyLyricsReader
446 451 });
447 452 }
448 453
449 private static string GetSpotifyWindowTitle()
454 private string GetApplicationWindowTitle()
450 455 {
451 var processes = Process.GetProcessesByName("Spotify");
456 var processes = Process.GetProcessesByName(_processName);
452 457 foreach (var p in processes)
453 458 {
454 459 try
@@ -463,14 +468,18 @@ public class SpotifyLyricsReader
463 468 return string.Empty;
464 469 }
465 470
466 private async Task<(string Artist, string Title)> GetTrackInfoAsync()
471 private async Task<(string Artist, string Title, string Album)> GetTrackInfoAsync()
467 472 {
468 473 string artist = string.Empty;
469 474 string title = string.Empty;
475 string album = string.Empty;
470 476
471 477 // 1. Try Window Title for instant song metadata
472 string winTitle = GetSpotifyWindowTitle();
473 if (!string.IsNullOrEmpty(winTitle) && winTitle != "Spotify" && winTitle != "Spotify Premium" && winTitle != "Spotify Free")
478 string winTitle = _useWindowTitleMetadata ? GetApplicationWindowTitle() : string.Empty;
479 if (!string.IsNullOrEmpty(winTitle) &&
480 !winTitle.Equals(_sourceName, StringComparison.OrdinalIgnoreCase) &&
481 !winTitle.Equals($"{_sourceName} Premium", StringComparison.OrdinalIgnoreCase) &&
482 !winTitle.Equals($"{_sourceName} Free", StringComparison.OrdinalIgnoreCase))
474 483 {
475 484 int dashIndex = winTitle.IndexOf(" - ");
476 485 if (dashIndex > 0)
@@ -480,22 +489,26 @@ public class SpotifyLyricsReader
480 489 }
481 490 }
482 491
483 // 2. Fallback to SMTC metadata if window title is empty (e.g. minimized to tray)
484 if (string.IsNullOrEmpty(title) && _currentSession != null)
492 // 2. 使用 SMTC 补充专辑信息,并在窗口标题不可用时提供歌名和歌手。
493 if (_currentSession != null)
485 494 {
486 495 try
487 496 {
488 497 var media = await RunWithTimeout(_currentSession.TryGetMediaPropertiesAsync(), 500);
489 498 if (media != null && !string.IsNullOrEmpty(media.Title))
490 499 {
491 artist = media.Artist;
492 title = media.Title;
500 album = media.AlbumTitle ?? string.Empty;
501 if (string.IsNullOrEmpty(title))
502 {
503 artist = media.Artist;
504 title = media.Title;
505 }
493 506 }
494 507 }
495 508 catch { }
496 509 }
497 510
498 return (artist, title);
511 return (artist, title, album);
499 512 }
500 513
501 514 private static string SanitizeFileName(string name)
@@ -505,7 +518,7 @@ public class SpotifyLyricsReader
505 518 return cleanName;
506 519 }
507 520
508 private async Task HandleTrackChangeAsync(string artist, string track)
521 private async Task HandleTrackChangeAsync(string artist, string track, string album)
509 522 {
510 523 Console.WriteLine($"HandleTrackChangeAsync started. Target: {artist} - {track}");
511 524 _cts?.Cancel();
@@ -516,10 +529,12 @@ public class SpotifyLyricsReader
516 529 {
517 530 _currentTitle = track;
518 531 _currentArtist = artist;
532 _currentAlbum = album;
533 CurrentAlbumColor = null;
519 534 _songStartTime = DateTimeOffset.Now;
520 535 _currentDuration = 0;
521 536 _isSmtcSynced = false;
522 _lyricLines.Clear();
537 _lyricLines = [];
523 538
524 539 // Await SMTC synchronization to get the duration before requesting lyrics
525 540 await SyncWithSmtcAsync();
@@ -553,7 +568,7 @@ public class SpotifyLyricsReader
553 568 }
554 569
555 570 // 2. Local cache miss: query LRCLIB database (with local proxy acceleration enabled)
556 var lyricsRes = await FetchLyricsAsync(_currentTitle, _currentArtist, _currentDuration, token);
571 var lyricsRes = await FetchLyricsAsync(_currentTitle, _currentArtist, _currentAlbum, _currentDuration, token);
557 572
558 573 if (token.IsCancellationRequested)
559 574 {
@@ -675,25 +690,25 @@ public class SpotifyLyricsReader
675 690 return match;
676 691 }
677 692
678 private async Task<LrclibResponse?> FetchLyricsAsync(string title, string artist, double duration, CancellationToken token)
693 private async Task<LrclibResponse?> FetchLyricsAsync(string title, string artist, string album, double duration, CancellationToken token)
679 694 {
680 695 // LRCLIB is the fallback open-source database.
681 696 // We query each endpoint with a separate 15-second timeout to handle high-latency connections robustly.
682 697 try
683 698 {
684 // 1. Try real-time get API first if duration is available
685 if (duration > 0)
699 // 1. 精确接口要求歌名、歌手、专辑和时长全部存在。
700 if (duration > 0 && !string.IsNullOrWhiteSpace(album))
686 701 {
687 702 using var getCts = CancellationTokenSource.CreateLinkedTokenSource(token);
688 703 getCts.CancelAfter(TimeSpan.FromSeconds(15));
689 704
690 705 int durationSeconds = (int)Math.Round(duration);
691 string getUrl = $"https://lrclib.net/api/get?track_name={Uri.EscapeDataString(title)}&artist_name={Uri.EscapeDataString(artist)}&duration={durationSeconds}";
706 string getUrl = $"https://lrclib.net/api/get?track_name={Uri.EscapeDataString(title)}&artist_name={Uri.EscapeDataString(artist)}&album_name={Uri.EscapeDataString(album)}&duration={durationSeconds}";
692 707 Console.WriteLine($"LRCLIB /api/get lookup URL: '{getUrl}'");
693 708
694 709 try
695 710 {
696 var getResponse = await HttpClient.GetAsync(getUrl, getCts.Token);
711 using var getResponse = await GetFromLrclibAsync(getUrl, getCts.Token);
697 712 if (getResponse.IsSuccessStatusCode)
698 713 {
699 714 var getRes = await getResponse.Content.ReadFromJsonAsync<LrclibResponse>(cancellationToken: getCts.Token);
@@ -716,40 +731,7 @@ public class SpotifyLyricsReader
716 731
717 732 if (token.IsCancellationRequested) return null;
718 733
719 // 2. Try get-cached (precise cache lookup)
720 {
721 using var cachedCts = CancellationTokenSource.CreateLinkedTokenSource(token);
722 cachedCts.CancelAfter(TimeSpan.FromSeconds(15));
723
724 string cachedUrl = $"https://lrclib.net/api/get-cached?track_name={Uri.EscapeDataString(title)}&artist_name={Uri.EscapeDataString(artist)}";
725 Console.WriteLine($"LRCLIB cached lookup URL: '{cachedUrl}'");
726
727 try
728 {
729 var response = await HttpClient.GetAsync(cachedUrl, cachedCts.Token);
730 if (response.IsSuccessStatusCode)
731 {
732 var cachedRes = await response.Content.ReadFromJsonAsync<LrclibResponse>(cancellationToken: cachedCts.Token);
733 if (cachedRes != null && (!string.IsNullOrEmpty(cachedRes.SyncedLyrics) || !string.IsNullOrEmpty(cachedRes.PlainLyrics)))
734 {
735 Console.WriteLine("LRCLIB cached lyrics retrieved successfully.");
736 return cachedRes;
737 }
738 }
739 else
740 {
741 Console.WriteLine($"LRCLIB cached API returned status code: {response.StatusCode}");
742 }
743 }
744 catch (Exception ex)
745 {
746 Console.WriteLine($"LRCLIB cached API failed: {ex.Message}");
747 }
748 }
749
750 if (token.IsCancellationRequested) return null;
751
752 // 3. Try precise search endpoint (exact metadata match)
734 // 2. 精确搜索接口不要求专辑和时长,作为通用回退。
753 735 {
754 736 using var searchCts = CancellationTokenSource.CreateLinkedTokenSource(token);
755 737 searchCts.CancelAfter(TimeSpan.FromSeconds(15));
@@ -759,7 +741,7 @@ public class SpotifyLyricsReader
759 741
760 742 try
761 743 {
762 var searchResponse = await HttpClient.GetAsync(searchUrl, searchCts.Token);
744 using var searchResponse = await GetFromLrclibAsync(searchUrl, searchCts.Token);
763 745 if (searchResponse.IsSuccessStatusCode)
764 746 {
765 747 var searchResults = await searchResponse.Content.ReadFromJsonAsync<List<LrclibResponse>>(cancellationToken: searchCts.Token);
@@ -789,7 +771,7 @@ public class SpotifyLyricsReader
789 771
790 772 if (token.IsCancellationRequested) return null;
791 773
792 // 4. Fallback to cleaned metadata search
774 // 3. 最后使用清洗后的歌曲信息搜索。
793 775 string cleanTitle = Regex.Replace(title, @"\s*[\(\[][^\)\]]*[\)\]]", "");
794 776 cleanTitle = Regex.Replace(cleanTitle, @"\s*-\s*.*?(?:radio|edit|remaster|remix|mix|acoustic|live|version|sped|slowed|instrumental).*", "", RegexOptions.IgnoreCase);
795 777 cleanTitle = Regex.Replace(cleanTitle, @"\s+(?:feat|ft)\.?\s+.*", "", RegexOptions.IgnoreCase);
@@ -814,7 +796,7 @@ public class SpotifyLyricsReader
814 796
815 797 try
816 798 {
817 var fallbackResponse = await HttpClient.GetAsync(fallbackUrl, fallbackCts.Token);
799 using var fallbackResponse = await GetFromLrclibAsync(fallbackUrl, fallbackCts.Token);
818 800 if (fallbackResponse.IsSuccessStatusCode)
819 801 {
820 802 var fallbackResults = await fallbackResponse.Content.ReadFromJsonAsync<List<LrclibResponse>>(cancellationToken: fallbackCts.Token);
@@ -903,7 +885,8 @@ public class SpotifyLyricsReader
903 885 }
904 886
905 887 string currentText = string.Empty;
906 foreach (var line in _lyricLines)
888 var lyricLines = _lyricLines;
889 foreach (var line in lyricLines)
907 890 {
908 891 if (line.Timestamp <= currentPosition)
909 892 {
@@ -927,3 +910,19 @@ public class SpotifyLyricsReader
927 910 return true;
928 911 }
929 912 }
913
914 /// <summary>
915 /// Spotify 同步歌词读取器,保留原有公开类型以兼容现有页面。
916 /// </summary>
917 public sealed class SpotifyLyricsReader : SynchronizedLyricsReader
918 {
919 public SpotifyLyricsReader() : base("Spotify", "Spotify", "Spotify", useWindowTitleMetadata: true) { }
920 }
921
922 /// <summary>
923 /// 网易云音乐同步歌词读取器。网易云窗口标题不稳定,因此只使用 SMTC 元数据。
924 /// </summary>
925 public sealed class CloudMusicOnlineLyricsReader : SynchronizedLyricsReader
926 {
927 public CloudMusicOnlineLyricsReader() : base("网易云音乐", "cloudmusic", "cloudmusic", useWindowTitleMetadata: false) { }
928 }
Modified Client/HaloPixelToolBox.Client/ViewModels/CloudMusicLyricsToolPageViewModel.cs +21 -92
@@ -3,7 +3,6 @@ using HaloPixelToolBox.Client.Profiles.CrossVersionProfiles;
3 3 using HaloPixelToolBox.Client.Utilities;
4 4 using HaloPixelToolBox.Core.Models.Bar;
5 5 using HaloPixelToolBox.Core.Utilities;
6 using System.Diagnostics;
7 6 using XFEExtension.NetCore.StringExtension;
8 7 using XFEExtension.NetCore.WinUIHelper.Implements;
9 8 using XFEExtension.NetCore.WinUIHelper.Interface.Services;
@@ -29,6 +28,7 @@ public partial class CloudMusicLyricsToolPageViewModel : ServiceBaseViewModelBas
29 28 [ObservableProperty] public partial string SupportedVersion { get; set; } = "等待检测";
30 29 public HaloPixelDevice Device { get; set; } = new();
31 30 public CloudMusicLyricsReader Reader { get; set; }
31 public CloudMusicOnlineLyricsReader OnlineReader { get; } = new();
32 32
33 33 public ISettingService SettingService { get; } = ServiceManager.GetService<ISettingService>();
34 34
@@ -167,99 +167,16 @@ public partial class CloudMusicLyricsToolPageViewModel : ServiceBaseViewModelBas
167 167 _forceRefresh = true;
168 168 }
169 169
170 private Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager? _smtcManager;
171 private Windows.Media.Control.GlobalSystemMediaTransportControlsSession? _cloudMusicSession;
172 public (byte R, byte G, byte B)? CurrentAlbumColor { get; private set; }
173 private string _currentTitle = string.Empty;
174 private string _currentArtist = string.Empty;
170 public bool IsPlaying => OnlineReader.IsPlaying;
175 171
176 public bool IsPlaying
177 {
178 get
179 {
180 if (_cloudMusicSession == null) return false;
181 try
182 {
183 var playbackInfo = _cloudMusicSession.GetPlaybackInfo();
184 return playbackInfo?.PlaybackStatus == Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing;
185 }
186 catch {}
187 return false;
188 }
189 }
172 public string CurrentTitle => OnlineReader.CurrentTitle;
190 173
191 public string CurrentTitle => _currentTitle;
192 public string CurrentArtist => _currentArtist;
174 public string CurrentArtist => OnlineReader.CurrentArtist;
193 175
194 private async Task InitSmtcAsync()
195 {
196 try
197 {
198 _smtcManager = await Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
199 UpdateCloudMusicSession();
200 _smtcManager.SessionsChanged += (s, e) => UpdateCloudMusicSession();
201 }
202 catch (Exception ex)
203 {
204 Console.WriteLine($"SMTC init failed: {ex.Message}");
205 }
206 }
207
208 private void UpdateCloudMusicSession()
209 {
210 if (_smtcManager == null) return;
211 var sessions = _smtcManager.GetSessions();
212 var targetSession = sessions.FirstOrDefault(x => x.SourceAppUserModelId.Contains("cloudmusic", StringComparison.OrdinalIgnoreCase));
213 if (targetSession != _cloudMusicSession)
214 {
215 if (_cloudMusicSession != null)
216 {
217 _cloudMusicSession.MediaPropertiesChanged -= OnSmtcMediaPropertiesChanged;
218 }
219 _cloudMusicSession = targetSession;
220 if (_cloudMusicSession != null)
221 {
222 _cloudMusicSession.MediaPropertiesChanged += OnSmtcMediaPropertiesChanged;
223 _ = UpdateAlbumColorAsync();
224 }
225 }
226 }
227
228 private void OnSmtcMediaPropertiesChanged(Windows.Media.Control.GlobalSystemMediaTransportControlsSession sender, Windows.Media.Control.MediaPropertiesChangedEventArgs args)
229 {
230 _ = UpdateAlbumColorAsync();
231 }
232
233 private async Task UpdateAlbumColorAsync()
234 {
235 if (_cloudMusicSession == null) return;
236 try
237 {
238 var media = await _cloudMusicSession.TryGetMediaPropertiesAsync();
239 if (media != null)
240 {
241 _currentTitle = media.Title ?? string.Empty;
242 _currentArtist = media.Artist ?? string.Empty;
243 if (media.Thumbnail != null)
244 {
245 var color = await SpotifyLyricsReader.GetDominantColorAsync(media.Thumbnail);
246 if (color.HasValue)
247 {
248 CurrentAlbumColor = color.Value;
249 Console.WriteLine($"CloudMusic extracted album color: RGB({color.Value.R}, {color.Value.G}, {color.Value.B})");
250 }
251 }
252 }
253 }
254 catch (Exception ex)
255 {
256 Console.WriteLine($"Failed to update CloudMusic album color: {ex.Message}");
257 }
258 }
176 public (byte R, byte G, byte B)? CurrentAlbumColor => OnlineReader.CurrentAlbumColor;
259 177
260 178 public CloudMusicLyricsToolPageViewModel()
261 179 {
262 _ = InitSmtcAsync();
263 180 Console.WriteLine("初始化网易云歌词读取器");
264 181 AddressResolverProvider.LoadCachedResolvers();
265 182 SupportedVersion = CloudMusicLyricsReader.VersionResolverDictionary.Keys
@@ -301,13 +218,19 @@ public partial class CloudMusicLyricsToolPageViewModel : ServiceBaseViewModelBas
301 218 Console.WriteLine("正在搜索云音乐...");
302 219 while (!CloudMusicReady)
303 220 {
304 var ready = Reader.Initialize();
305 if (!ready && !UseInputedAddress)
306 ready = await TryUpdateAddressResolverAsync();
221 OnlineReader.Initialize();
222 var onlineReady = OnlineReader.IsSessionAvailable;
223 var memoryReady = Reader.Initialize();
224 if (!memoryReady && !UseInputedAddress)
225 memoryReady = await TryUpdateAddressResolverAsync();
226 var ready = onlineReady || memoryReady;
307 227 AutoNavigationParameterService.CurrentPage?.DispatcherQueue.TryEnqueue(() =>
308 228 {
309 229 CloudMusicReady = ready;
310 230 CloudMusicVersion = Reader.VersionInfo is not null ? $"{Reader.VersionInfo.FileVersion}" : "未检测到云音乐";
231 SupportedVersion = onlineReady
232 ? (memoryReady ? "SMTC 在线歌词(内存兜底可用)" : "SMTC 在线歌词(无需解析地址)")
233 : (memoryReady ? $"内存解析({Reader.Version.ToString(3)})" : SupportedVersion);
311 234 });
312 235 await Task.Delay(500);
313 236 }
@@ -375,7 +298,13 @@ public partial class CloudMusicLyricsToolPageViewModel : ServiceBaseViewModelBas
375 298
376 299 bool isPlaying = IsPlaying;
377 300 bool trackChanged = lastTrackTitle != CurrentTitle || lastTrackArtist != CurrentArtist;
378 bool lyricsChanged = Reader.TryReadLyrics(out var lyrics) && lastRead != lyrics;
301 var lyricsRead = OnlineReader.TryReadLyrics(out var lyrics);
302 if (!OnlineReader.HasSynchronizedLyrics && Reader.TryReadLyrics(out var memoryLyrics))
303 {
304 lyrics = memoryLyrics;
305 lyricsRead = true;
306 }
307 bool lyricsChanged = lyricsRead && lastRead != lyrics;
379 308
380 309 if (isPlaying && (_isClockUI || trackChanged))
381 310 {
Modified Client/HaloPixelToolBox.Client/ViewModels/MainPageViewModel.cs +49 -4
@@ -1,13 +1,18 @@
1 using XFEExtension.NetCore.WinUIHelper.Interface.Services;
1 using CommunityToolkit.Mvvm.Input;
2 using HaloPixelToolBox.Client.Profiles.CrossVersionProfiles;
3 using HaloPixelToolBox.Client.Views;
4 using System.Reflection;
5 using XFEExtension.NetCore.WinUIHelper.Interface.Services;
2 6 using XFEExtension.NetCore.WinUIHelper.Utilities;
3 7
4 8 namespace HaloPixelToolBox.Client.ViewModels;
5 9
6 10 public partial class MainPageViewModel : ViewModelBase
7 11 {
8 public IAutoNavigationParameterService<string> AutoNavigationParameterService { get; set; } = ServiceManager.GetService<IAutoNavigationParameterService<string>>();
9 public INavigationService? NavigationService { get; } = ServiceManager.GetGlobalService<INavigationService>();
10 public IMessageService? MessageService { get; } = ServiceManager.GetGlobalService<IMessageService>();
12 public IAutoNavigationParameterService<string> AutoNavigationParameterService { get; } = ServiceManager.GetService<IAutoNavigationParameterService<string>>();
13 public INavigationViewService NavigationViewService { get; } = ServiceManager.GetService<INavigationViewService>();
14 public string Greeting { get; } = GetGreeting();
15 public string VersionLabel { get; } = $"HaloPixelToolBox · v{GetVersion()}";
11 16
12 17 public MainPageViewModel()
13 18 {
@@ -17,4 +22,44 @@ public partial class MainPageViewModel : ViewModelBase
17 22 private void AutoNavigationParameterService_ParameterChange(object? sender, string? e)
18 23 {
19 24 }
25
26 private static string GetGreeting()
27 {
28 var greeting = DateTime.Now.Hour switch
29 {
30 < 6 => "夜深了",
31 < 11 => "早上好",
32 < 14 => "中午好",
33 < 18 => "下午好",
34 _ => "晚上好"
35 };
36
37 return $"{greeting},{Environment.UserName}";
38 }
39
40 private static string GetVersion() =>
41 Assembly.GetEntryAssembly()?.GetName().Version is Version version
42 ? version.ToString(3)
43 : "1.0.0";
44
45 [RelayCommand]
46 private void OpenPreferredLyrics()
47 {
48 if (SystemProfile.DefaultPage == nameof(SpotifyLyricsToolPage))
49 NavigationViewService.NavigateTo<SpotifyLyricsToolPage>();
50 else
51 NavigationViewService.NavigateTo<CloudMusicLyricsToolPage>();
52 }
53
54 [RelayCommand]
55 private void OpenCloudMusic() => NavigationViewService.NavigateTo<CloudMusicLyricsToolPage>();
56
57 [RelayCommand]
58 private void OpenSpotify() => NavigationViewService.NavigateTo<SpotifyLyricsToolPage>();
59
60 [RelayCommand]
61 private void OpenDefaultSettings() => NavigationViewService.NavigateTo<DefaultSettingsPage>();
62
63 [RelayCommand]
64 private void OpenSettings() => NavigationViewService.NavigateTo<SettingPage>();
20 65 }
Modified Client/HaloPixelToolBox.Client/ViewModels/SettingPageViewModel.cs +12 -2
@@ -18,7 +18,12 @@ namespace HaloPixelToolBox.Client.ViewModels;
18 18 public partial class SettingPageViewModel : ViewModelBase
19 19 {
20 20 [ObservableProperty] public partial int CloseButtonActionIndex { get; set; } = SystemProfile.MinimizeWhenClose ? 0 : 1;
21 [ObservableProperty] public partial int DefaultTabPageIndex { get; set; } = SystemProfile.DefaultPage == "SpotifyLyricsToolPage" ? 1 : 0;
21 [ObservableProperty] public partial int DefaultTabPageIndex { get; set; } = SystemProfile.DefaultPage switch
22 {
23 "CloudMusicLyricsToolPage" => 1,
24 "SpotifyLyricsToolPage" => 2,
25 _ => 0
26 };
22 27 [ObservableProperty] public partial bool IsAutoStartEnable { get; set; } = SystemProfile.AutoStart;
23 28 [ObservableProperty] public partial bool MinimizeWhenOpen { get; set; } = SystemProfile.MinimizeWhenOpen;
24 29 [ObservableProperty] public partial string AppCacheDirectory { get; set; } = AppPathHelper.AppCache;
@@ -35,7 +40,12 @@ public partial class SettingPageViewModel : ViewModelBase
35 40
36 41 partial void OnCloseButtonActionIndexChanged(int value) => SystemProfile.MinimizeWhenClose = value == 0;
37 42
38 partial void OnDefaultTabPageIndexChanged(int value) => SystemProfile.DefaultPage = value == 1 ? "SpotifyLyricsToolPage" : "CloudMusicLyricsToolPage";
43 partial void OnDefaultTabPageIndexChanged(int value) => SystemProfile.DefaultPage = value switch
44 {
45 1 => "CloudMusicLyricsToolPage",
46 2 => "SpotifyLyricsToolPage",
47 _ => "MainPage"
48 };
39 49
40 50 partial void OnIsAutoStartEnableChanged(bool value)
41 51 {
Modified Client/HaloPixelToolBox.Client/ViewModels/TrayMenuPageViewModel.cs +1 -1
@@ -83,7 +83,7 @@ public partial class TrayMenuPageViewModel : ServiceBaseViewModelBase<string>
83 83 void Show()
84 84 {
85 85 ServiceManager.GetGlobalService<ITrayIconService>()?.ShowWindow();
86 NavigationViewService?.NavigateTo<CloudMusicLyricsToolPage>();
86 NavigationViewService?.NavigateTo<MainPage>();
87 87 MenuWindow.Close();
88 88 }
89 89
Modified Client/HaloPixelToolBox.Client/Views/AppShellPage.xaml +5 -0
@@ -44,6 +44,11 @@
44 44 </Grid>
45 45 <NavigationView x:Name="navigationView" IsBackButtonVisible="Collapsed" Canvas.ZIndex="0" IsBackEnabled="{x:Bind ViewModel.CanGoBack, Mode=OneWay}" IsSettingsVisible="False" DisplayModeChanged="NavigationView_DisplayModeChanged" PaneOpening="NavigationView_PaneOpening" PaneOpened="NavigationView_PaneOpened" PaneClosing="NavigationView_PaneClosing" PaneClosed="NavigationView_PaneClosed">
46 46 <NavigationView.MenuItems>
47 <NavigationViewItem Content="主页" add:NavigationAddition.NavigateTo="HaloPixelToolBox.Client.Views.MainPage">
48 <NavigationViewItem.Icon>
49 <FontIcon Glyph="&#xE80F;"/>
50 </NavigationViewItem.Icon>
51 </NavigationViewItem>
47 52 <NavigationViewItem Content="网易云歌词" add:NavigationAddition.NavigateTo="HaloPixelToolBox.Client.Views.CloudMusicLyricsToolPage">
48 53 <NavigationViewItem.Icon>
49 54 <FontIcon Glyph="&#xE8D6;"/>
Modified Client/HaloPixelToolBox.Client/Views/AppShellPage.xaml.cs +12 -4
@@ -22,10 +22,18 @@ public sealed partial class AppShellPage : Page
22 22 ViewModel.DialogService.RegisterDialog(closeDialog);
23 23 ViewModel.PageService.Initialize(this);
24 24 ViewModel.LoadingService.Initialize(loadingGrid, globalLoadingGrid, globalLoadingTextBlock, DispatcherQueue, ViewModel.NavigationViewService.NavigationService);
25 if (SystemProfile.DefaultPage == "SpotifyLyricsToolPage")
26 ViewModel.NavigationViewService.NavigateTo<SpotifyLyricsToolPage>();
27 else
28 ViewModel.NavigationViewService.NavigateTo<CloudMusicLyricsToolPage>();
25 switch (SystemProfile.DefaultPage)
26 {
27 case nameof(SpotifyLyricsToolPage):
28 ViewModel.NavigationViewService.NavigateTo<SpotifyLyricsToolPage>();
29 break;
30 case nameof(CloudMusicLyricsToolPage):
31 ViewModel.NavigationViewService.NavigateTo<CloudMusicLyricsToolPage>();
32 break;
33 default:
34 ViewModel.NavigationViewService.NavigateTo<MainPage>();
35 break;
36 }
29 37 }
30 38
31 39 private void NavigationView_DisplayModeChanged(NavigationView sender, NavigationViewDisplayModeChangedEventArgs args)
Modified Client/HaloPixelToolBox.Client/Views/CloudMusicLyricsToolPage.xaml +3 -3
@@ -42,10 +42,10 @@
42 42 <Border CornerRadius="90" Height="25" Width="25" Visibility="{x:Bind ViewModel.CloudMusicReady, Mode=OneWay}" Background="{ThemeResource SystemFillColorSuccessBrush}"/>
43 43 </Grid>
44 44 </Grid>
45 <TextBlock Text="{x:Bind ViewModel.SupportedVersion, Mode=OneWay, Converter={StaticResource StringFormatConverter}, ConverterParameter='网易云版本 (当前支持版本 (0) )'}" Style="{StaticResource SettingsSectionHeaderTextBlockStyle}"/>
45 <TextBlock Text="{x:Bind ViewModel.SupportedVersion, Mode=OneWay, Converter={StaticResource StringFormatConverter}, ConverterParameter='歌词来源:(0)'}" Style="{StaticResource SettingsSectionHeaderTextBlockStyle}"/>
46 46 <TextBlock Text="{x:Bind ViewModel.CloudMusicVersion, Mode=OneWay}" Style="{StaticResource BodyTextBlockStyle}"/>
47 47 <TextBlock Text="功能" Style="{StaticResource SettingsSectionHeaderTextBlockStyle}"/>
48 <controls:SettingsCard Header="启用歌词同步" Description="启用后,网易云的歌词会实时显示在花再 Halo Pixel 音响上">
48 <controls:SettingsCard Header="启用歌词同步" Description="通过系统媒体会话识别歌曲并联网获取同步歌词,随后实时显示在花再 Halo Pixel 音响上">
49 49 <ToggleSwitch IsOn="{x:Bind ViewModel.EnableCloudMusicLyrics, Mode=TwoWay}"/>
50 50 </controls:SettingsCard>
51 51 <controls:SettingsCard Header="开启屏幕颜色同步" Description="自动提取当前歌曲专辑封面主色并应用到像素屏歌词文本颜色">
@@ -72,7 +72,7 @@
72 72 </controls:SettingsCard>
73 73 </controls:SettingsExpander.Items>
74 74 </controls:SettingsExpander>
75 <controls:SettingsExpander Header="手动输入内存地址" Description="解析使用手动输入的内存地址">
75 <controls:SettingsExpander Header="高级:内存读取兜底" Description="仅在在线同步歌词不可用时手动指定内存地址">
76 76 <ToggleSwitch x:Name="useInputedAddressToggleSwitch" IsOn="{x:Bind ViewModel.UseInputedAddress, Mode=TwoWay}"/>
77 77 <controls:SettingsExpander.Items>
78 78 <controls:SettingsCard Header="内存地址" Description="设置要解析的内存地址" IsEnabled="{x:Bind useInputedAddressToggleSwitch.IsOn, Mode=OneWay}">
Modified Client/HaloPixelToolBox.Client/Views/MainPage.xaml +379 -6
@@ -3,18 +3,391 @@
3 3 x:Class="HaloPixelToolBox.Client.Views.MainPage"
4 4 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5 5 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
6 xmlns:converter="using:XFEExtension.NetCore.WinUIHelper.Utilities.Converter"
7 xmlns:local="using:HaloPixelToolBox.Client.View"
8 6 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
9 7 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
10 8 mc:Ignorable="d">
9
11 10 <Page.Resources>
12 <converter:StringFormatConverter x:Key="StringFormatConverter"/>
11 <Style x:Key="DashboardCardButtonStyle" TargetType="Button">
12 <Setter Property="Background" Value="{ThemeResource CardBackgroundFillColorDefaultBrush}"/>
13 <Setter Property="BorderBrush" Value="{ThemeResource CardStrokeColorDefaultBrush}"/>
14 <Setter Property="BorderThickness" Value="1"/>
15 <Setter Property="CornerRadius" Value="16"/>
16 <Setter Property="Padding" Value="24"/>
17 <Setter Property="HorizontalAlignment" Value="Stretch"/>
18 <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
19 <Setter Property="VerticalContentAlignment" Value="Stretch"/>
20 </Style>
21 <Style x:Key="FeatureIconBorderStyle" TargetType="Border">
22 <Setter Property="Width" Value="44"/>
23 <Setter Property="Height" Value="44"/>
24 <Setter Property="CornerRadius" Value="12"/>
25 <Setter Property="Background" Value="{ThemeResource AccentFillColorSecondaryBrush}"/>
26 </Style>
13 27 </Page.Resources>
14 28
15 29 <Grid>
16 <StackPanel Orientation="Vertical" Spacing="20">
17 <TextBlock Text="Welcome to the Main Page!" FontSize="24" HorizontalAlignment="Center" Margin="20"/>
18 </StackPanel>
30 <VisualStateManager.VisualStateGroups>
31 <VisualStateGroup>
32 <VisualState x:Name="WideLayout">
33 <VisualState.StateTriggers>
34 <AdaptiveTrigger MinWindowWidth="900"/>
35 </VisualState.StateTriggers>
36 </VisualState>
37 <VisualState x:Name="NarrowLayout">
38 <VisualState.StateTriggers>
39 <AdaptiveTrigger MinWindowWidth="0"/>
40 </VisualState.StateTriggers>
41 <VisualState.Setters>
42 <Setter Target="HeroArtwork.Visibility" Value="Collapsed"/>
43 <Setter Target="HeroArtworkColumn.Width" Value="0"/>
44 <Setter Target="HeroBorder.Padding" Value="24"/>
45 <Setter Target="HeroTitle.FontSize" Value="30"/>
46 <Setter Target="HeroActions.Orientation" Value="Vertical"/>
47 <Setter Target="HeroActions.HorizontalAlignment" Value="Stretch"/>
48 <Setter Target="PrimaryAction.HorizontalAlignment" Value="Stretch"/>
49 <Setter Target="SecondaryAction.HorizontalAlignment" Value="Stretch"/>
50 <Setter Target="SecondActionColumn.Width" Value="0"/>
51 <Setter Target="SpotifyAction.(Grid.Row)" Value="1"/>
52 <Setter Target="SpotifyAction.(Grid.Column)" Value="0"/>
53 <Setter Target="QuickActionsGrid.RowSpacing" Value="12"/>
54 <Setter Target="SecondUtilityColumn.Width" Value="0"/>
55 <Setter Target="SettingsAction.(Grid.Row)" Value="1"/>
56 <Setter Target="SettingsAction.(Grid.Column)" Value="0"/>
57 <Setter Target="UtilityGrid.RowSpacing" Value="12"/>
58 <Setter Target="CapabilitySecondColumn.Width" Value="0"/>
59 <Setter Target="CapabilityThirdColumn.Width" Value="0"/>
60 <Setter Target="ColorCapability.(Grid.Row)" Value="1"/>
61 <Setter Target="ColorCapability.(Grid.Column)" Value="0"/>
62 <Setter Target="LightCapability.(Grid.Row)" Value="2"/>
63 <Setter Target="LightCapability.(Grid.Column)" Value="0"/>
64 <Setter Target="CapabilityGrid.RowSpacing" Value="20"/>
65 </VisualState.Setters>
66 </VisualState>
67 </VisualStateGroup>
68 </VisualStateManager.VisualStateGroups>
69
70 <ScrollView VerticalScrollBarVisibility="Auto">
71 <StackPanel MaxWidth="1280"
72 HorizontalAlignment="Stretch"
73 Spacing="28"
74 Margin="0,0,0,40">
75 <Border x:Name="HeroBorder"
76 MinHeight="270"
77 Padding="36,32"
78 CornerRadius="22">
79 <Border.Background>
80 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
81 <GradientStop Color="#FF075A9E" Offset="0"/>
82 <GradientStop Color="#FF0B86C8" Offset="0.56"/>
83 <GradientStop Color="#FF36A8E6" Offset="1"/>
84 </LinearGradientBrush>
85 </Border.Background>
86 <Grid ColumnSpacing="28">
87 <Grid.ColumnDefinitions>
88 <ColumnDefinition Width="*"/>
89 <ColumnDefinition x:Name="HeroArtworkColumn" Width="260"/>
90 </Grid.ColumnDefinitions>
91
92 <StackPanel VerticalAlignment="Center" Spacing="14">
93 <Border HorizontalAlignment="Left"
94 Padding="10,5"
95 Background="#22FFFFFF"
96 CornerRadius="99">
97 <StackPanel Orientation="Horizontal" Spacing="7">
98 <Ellipse Width="7" Height="7" Fill="#FF8EE8FF"/>
99 <TextBlock Text="{x:Bind ViewModel.VersionLabel, Mode=OneWay}"
100 Foreground="White"
101 FontSize="12"
102 VerticalAlignment="Center"/>
103 </StackPanel>
104 </Border>
105 <TextBlock Text="{x:Bind ViewModel.Greeting, Mode=OneWay}"
106 Foreground="White"
107 FontSize="15"
108 Opacity="0.86"/>
109 <TextBlock x:Name="HeroTitle"
110 Text="让音乐,在像素屏上发光"
111 Foreground="White"
112 FontSize="38"
113 FontWeight="SemiBold"
114 TextWrapping="Wrap"/>
115 <TextBlock MaxWidth="650"
116 HorizontalAlignment="Left"
117 Text="连接花再 Halo Pixel,将正在播放的歌词、专辑色彩与氛围灯效果实时同步到桌面。"
118 Foreground="White"
119 FontSize="15"
120 LineHeight="24"
121 Opacity="0.82"
122 TextWrapping="Wrap"/>
123 <StackPanel x:Name="HeroActions"
124 Margin="0,8,0,0"
125 Orientation="Horizontal"
126 HorizontalAlignment="Left"
127 Spacing="10">
128 <Button x:Name="PrimaryAction"
129 Command="{x:Bind ViewModel.OpenPreferredLyricsCommand}"
130 Background="White"
131 Foreground="#FF075A9E"
132 BorderThickness="0"
133 CornerRadius="9"
134 Padding="18,10">
135 <StackPanel Orientation="Horizontal" Spacing="9">
136 <FontIcon Glyph="&#xE768;" FontSize="14"/>
137 <TextBlock Text="打开首选歌词源" FontWeight="SemiBold"/>
138 </StackPanel>
139 </Button>
140 <Button x:Name="SecondaryAction"
141 Command="{x:Bind ViewModel.OpenDefaultSettingsCommand}"
142 Background="#1FFFFFFF"
143 Foreground="White"
144 BorderBrush="#55FFFFFF"
145 BorderThickness="1"
146 CornerRadius="9"
147 Padding="18,10">
148 <StackPanel Orientation="Horizontal" Spacing="9">
149 <FontIcon Glyph="&#xE7F4;" FontSize="14"/>
150 <TextBlock Text="自定义默认界面"/>
151 </StackPanel>
152 </Button>
153 </StackPanel>
154 </StackPanel>
155
156 <Grid x:Name="HeroArtwork" Grid.Column="1">
157 <Ellipse Width="220" Height="220"
158 HorizontalAlignment="Center"
159 VerticalAlignment="Center"
160 Stroke="#26FFFFFF"
161 StrokeThickness="1"/>
162 <Ellipse Width="174" Height="174"
163 HorizontalAlignment="Center"
164 VerticalAlignment="Center"
165 Fill="#12FFFFFF"
166 Stroke="#35FFFFFF"
167 StrokeThickness="1"/>
168 <Border Width="126" Height="126"
169 HorizontalAlignment="Center"
170 VerticalAlignment="Center"
171 Background="#EFFFFFFF"
172 CornerRadius="32">
173 <Image Source="/Assets/icon.png"
174 Width="92"
175 Height="92"
176 Stretch="Uniform"/>
177 </Border>
178 <Border Width="38" Height="38"
179 Margin="21,30,0,0"
180 HorizontalAlignment="Left"
181 VerticalAlignment="Top"
182 Background="#32FFFFFF"
183 CornerRadius="19">
184 <FontIcon Glyph="&#xE8D6;" Foreground="White" FontSize="17"/>
185 </Border>
186 <Border Width="32" Height="32"
187 Margin="0,0,23,38"
188 HorizontalAlignment="Right"
189 VerticalAlignment="Bottom"
190 Background="#32FFFFFF"
191 CornerRadius="16">
192 <FontIcon Glyph="&#xE706;" Foreground="White" FontSize="15"/>
193 </Border>
194 </Grid>
195 </Grid>
196 </Border>
197
198 <StackPanel Spacing="5">
199 <TextBlock Text="快捷功能" FontSize="22" FontWeight="SemiBold"/>
200 <TextBlock Text="选择音乐来源,立即开始同步歌词。"
201 Foreground="{ThemeResource TextFillColorSecondaryBrush}"/>
202 </StackPanel>
203
204 <Grid x:Name="QuickActionsGrid" ColumnSpacing="14">
205 <Grid.ColumnDefinitions>
206 <ColumnDefinition Width="*"/>
207 <ColumnDefinition x:Name="SecondActionColumn" Width="*"/>
208 </Grid.ColumnDefinitions>
209 <Grid.RowDefinitions>
210 <RowDefinition Height="Auto"/>
211 <RowDefinition Height="Auto"/>
212 </Grid.RowDefinitions>
213
214 <Button Command="{x:Bind ViewModel.OpenCloudMusicCommand}"
215 Style="{StaticResource DashboardCardButtonStyle}">
216 <Grid MinHeight="118" ColumnSpacing="18">
217 <Grid.ColumnDefinitions>
218 <ColumnDefinition Width="Auto"/>
219 <ColumnDefinition Width="*"/>
220 </Grid.ColumnDefinitions>
221 <Border Width="54" Height="54" CornerRadius="16" Background="#1AE5484D">
222 <FontIcon Glyph="&#xE8D6;" FontSize="25" Foreground="#FFE5484D"/>
223 </Border>
224 <StackPanel Grid.Column="1" VerticalAlignment="Center" Spacing="7">
225 <Grid>
226 <TextBlock Text="网易云音乐" FontSize="19" FontWeight="SemiBold"/>
227 <FontIcon Glyph="&#xE72A;"
228 HorizontalAlignment="Right"
229 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
230 FontSize="14"/>
231 </Grid>
232 <TextBlock Text="同步歌词、专辑主色和动态氛围灯效果"
233 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
234 TextWrapping="Wrap"/>
235 <TextBlock Text="进入网易云歌词工具"
236 Foreground="{ThemeResource AccentTextFillColorPrimaryBrush}"
237 FontSize="13"/>
238 </StackPanel>
239 </Grid>
240 </Button>
241
242 <Button x:Name="SpotifyAction"
243 Grid.Column="1"
244 Command="{x:Bind ViewModel.OpenSpotifyCommand}"
245 Style="{StaticResource DashboardCardButtonStyle}">
246 <Grid MinHeight="118" ColumnSpacing="18">
247 <Grid.ColumnDefinitions>
248 <ColumnDefinition Width="Auto"/>
249 <ColumnDefinition Width="*"/>
250 </Grid.ColumnDefinitions>
251 <Border Width="54" Height="54" CornerRadius="16" Background="#1A1ED760">
252 <FontIcon Glyph="&#xE189;" FontSize="25" Foreground="#FF1DB954"/>
253 </Border>
254 <StackPanel Grid.Column="1" VerticalAlignment="Center" Spacing="7">
255 <Grid>
256 <TextBlock Text="Spotify" FontSize="19" FontWeight="SemiBold"/>
257 <FontIcon Glyph="&#xE72A;"
258 HorizontalAlignment="Right"
259 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
260 FontSize="14"/>
261 </Grid>
262 <TextBlock Text="识别当前曲目,让海外音乐也点亮像素屏"
263 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
264 TextWrapping="Wrap"/>
265 <TextBlock Text="进入 Spotify 歌词工具"
266 Foreground="{ThemeResource AccentTextFillColorPrimaryBrush}"
267 FontSize="13"/>
268 </StackPanel>
269 </Grid>
270 </Button>
271 </Grid>
272
273 <Grid x:Name="UtilityGrid" ColumnSpacing="14">
274 <Grid.ColumnDefinitions>
275 <ColumnDefinition Width="*"/>
276 <ColumnDefinition x:Name="SecondUtilityColumn" Width="*"/>
277 </Grid.ColumnDefinitions>
278 <Grid.RowDefinitions>
279 <RowDefinition Height="Auto"/>
280 <RowDefinition Height="Auto"/>
281 </Grid.RowDefinitions>
282
283 <Button Command="{x:Bind ViewModel.OpenDefaultSettingsCommand}"
284 Style="{StaticResource DashboardCardButtonStyle}"
285 Padding="20">
286 <Grid ColumnSpacing="14">
287 <Grid.ColumnDefinitions>
288 <ColumnDefinition Width="Auto"/>
289 <ColumnDefinition Width="*"/>
290 <ColumnDefinition Width="Auto"/>
291 </Grid.ColumnDefinitions>
292 <Border Style="{StaticResource FeatureIconBorderStyle}">
293 <FontIcon Glyph="&#xE7F4;" FontSize="19"/>
294 </Border>
295 <StackPanel Grid.Column="1" VerticalAlignment="Center" Spacing="3">
296 <TextBlock Text="默认界面" FontWeight="SemiBold"/>
297 <TextBlock Text="设置暂停后的屏幕与灯效"
298 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
299 FontSize="13"
300 TextWrapping="Wrap"/>
301 </StackPanel>
302 <FontIcon Grid.Column="2" Glyph="&#xE72A;" FontSize="13"/>
303 </Grid>
304 </Button>
305
306 <Button x:Name="SettingsAction"
307 Grid.Column="1"
308 Command="{x:Bind ViewModel.OpenSettingsCommand}"
309 Style="{StaticResource DashboardCardButtonStyle}"
310 Padding="20">
311 <Grid ColumnSpacing="14">
312 <Grid.ColumnDefinitions>
313 <ColumnDefinition Width="Auto"/>
314 <ColumnDefinition Width="*"/>
315 <ColumnDefinition Width="Auto"/>
316 </Grid.ColumnDefinitions>
317 <Border Style="{StaticResource FeatureIconBorderStyle}">
318 <FontIcon Glyph="&#xE713;" FontSize="19"/>
319 </Border>
320 <StackPanel Grid.Column="1" VerticalAlignment="Center" Spacing="3">
321 <TextBlock Text="应用设置" FontWeight="SemiBold"/>
322 <TextBlock Text="外观、启动行为与更新管理"
323 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
324 FontSize="13"
325 TextWrapping="Wrap"/>
326 </StackPanel>
327 <FontIcon Grid.Column="2" Glyph="&#xE72A;" FontSize="13"/>
328 </Grid>
329 </Button>
330 </Grid>
331
332 <Border Padding="26,22"
333 Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
334 BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
335 BorderThickness="1"
336 CornerRadius="16">
337 <StackPanel Spacing="18">
338 <StackPanel Spacing="4">
339 <TextBlock Text="一站式同步体验" FontSize="18" FontWeight="SemiBold"/>
340 <TextBlock Text="从歌词到灯光,让桌面上的每一拍都看得见。"
341 Foreground="{ThemeResource TextFillColorSecondaryBrush}"/>
342 </StackPanel>
343 <Grid x:Name="CapabilityGrid" ColumnSpacing="20">
344 <Grid.ColumnDefinitions>
345 <ColumnDefinition Width="*"/>
346 <ColumnDefinition x:Name="CapabilitySecondColumn" Width="*"/>
347 <ColumnDefinition x:Name="CapabilityThirdColumn" Width="*"/>
348 </Grid.ColumnDefinitions>
349 <Grid.RowDefinitions>
350 <RowDefinition Height="Auto"/>
351 <RowDefinition Height="Auto"/>
352 <RowDefinition Height="Auto"/>
353 </Grid.RowDefinitions>
354 <StackPanel Orientation="Horizontal" Spacing="12">
355 <Border Style="{StaticResource FeatureIconBorderStyle}">
356 <FontIcon Glyph="&#xE8D6;" FontSize="18"/>
357 </Border>
358 <StackPanel VerticalAlignment="Center" Spacing="2">
359 <TextBlock Text="实时歌词" FontWeight="SemiBold"/>
360 <TextBlock Text="紧跟当前播放进度"
361 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
362 FontSize="12"/>
363 </StackPanel>
364 </StackPanel>
365 <StackPanel x:Name="ColorCapability" Grid.Column="1" Orientation="Horizontal" Spacing="12">
366 <Border Style="{StaticResource FeatureIconBorderStyle}">
367 <FontIcon Glyph="&#xE790;" FontSize="18"/>
368 </Border>
369 <StackPanel VerticalAlignment="Center" Spacing="2">
370 <TextBlock Text="智能取色" FontWeight="SemiBold"/>
371 <TextBlock Text="自动提取专辑主色"
372 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
373 FontSize="12"/>
374 </StackPanel>
375 </StackPanel>
376 <StackPanel x:Name="LightCapability" Grid.Column="2" Orientation="Horizontal" Spacing="12">
377 <Border Style="{StaticResource FeatureIconBorderStyle}">
378 <FontIcon Glyph="&#xE706;" FontSize="18"/>
379 </Border>
380 <StackPanel VerticalAlignment="Center" Spacing="2">
381 <TextBlock Text="灯效联动" FontWeight="SemiBold"/>
382 <TextBlock Text="同步屏幕与底座氛围灯"
383 Foreground="{ThemeResource TextFillColorSecondaryBrush}"
384 FontSize="12"/>
385 </StackPanel>
386 </StackPanel>
387 </Grid>
388 </StackPanel>
389 </Border>
390 </StackPanel>
391 </ScrollView>
19 392 </Grid>
20 393 </Page>
Modified Client/HaloPixelToolBox.Client/Views/SettingPage.xaml +2 -1
@@ -35,11 +35,12 @@
35 35 <ComboBoxItem Content="跟随系统" Tag="Default"/>
36 36 </ComboBox>
37 37 </controls:SettingsCard>
38 <controls:SettingsCard Header="默认启动页面" Description="软件启动时默认显示的歌词源页面">
38 <controls:SettingsCard Header="默认启动页面" Description="选择软件启动后首先显示的页面">
39 39 <controls:SettingsCard.HeaderIcon>
40 40 <FontIcon Glyph="&#xE8F4;"/>
41 41 </controls:SettingsCard.HeaderIcon>
42 42 <ComboBox SelectedIndex="{x:Bind ViewModel.DefaultTabPageIndex, Mode=TwoWay}">
43 <ComboBoxItem Content="主页"/>
43 44 <ComboBoxItem Content="网易云歌词"/>
44 45 <ComboBoxItem Content="Spotify歌词"/>
45 46 </ComboBox>
Added Core/HaloPixelToolBox.Core/Models/Lyrics/LyricLine.cs +11 -0
Added Core/HaloPixelToolBox.Core/Utilities/LrcParser.cs +58 -0