Repository navigation
Expand file tree
/
Copy pathWebLibraryForm.cs
More file actions
1191 lines (1011 loc) · 37.5 KB
/
Copy pathWebLibraryForm.cs
File metadata and controls
1191 lines (1011 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using MINWallPaper.Music;
using MINWallPaper.Native;
using MINWallPaper.Playback;
using MINWallPaper.Storage;
using MINWallPaper.Widgets;
namespace MINWallPaper;
/// <summary>
/// 用 WebView2 承载界面:HTML/CSS 负责布局,天然适配窗口缩放;
/// C# 只负责壁纸、组件、音乐这些系统能力,两边用 JSON 消息通信。
/// </summary>
internal sealed class WebLibraryForm : Form
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
private readonly WebView2 _web = new();
private readonly System.Windows.Forms.Timer _playerTimer;
private readonly System.Windows.Forms.Timer _resizeTimer;
private bool _ready;
private bool _disposed;
private bool? _lastMaximized;
private bool _moving;
private string _resizeEdge = "";
private Point _resizeCursorStart;
private Rectangle _resizeBoundsStart;
public WebLibraryForm()
{
Text = "MINWallPaper";
Icon = AppIcon.Value;
FormBorderStyle = FormBorderStyle.None;
ClientSize = new Size(1180, 740);
MinimumSize = new Size(880, 600);
StartPosition = FormStartPosition.CenterScreen;
BackColor = Color.FromArgb(10, 10, 12);
DoubleBuffered = true;
_web.Dock = DockStyle.Fill;
_web.DefaultBackgroundColor = Color.FromArgb(10, 10, 12);
Controls.Add(_web);
Load += async (_, _) => await InitializeAsync();
WallpaperLibrary.Instance.Changed += OnDataChanged;
WallpaperLibrary.Instance.Status += OnStatus;
MusicLibrary.Instance.Changed += OnDataChanged;
MusicLibrary.Instance.Scanned += OnDataChanged;
WallpaperHost.Instance.StateChanged += OnDataChanged;
PreviewFrames.Ready += OnPreviewReady;
MusicPlayer.Instance.StateChanged += OnPlayerChanged;
MusicArtwork.Ready += OnPlayerChanged;
WidgetService.Instance.Changed += OnWidgetsChanged;
// 歌词高亮和进度条按 250ms 跟随播放;暂停时降到 1s,避免无意义刷新。
_playerTimer = new System.Windows.Forms.Timer { Interval = 250 };
_playerTimer.Tick += (_, _) =>
{
if (!_ready || _disposed || MusicPlayer.Instance.CurrentPath == null)
{
if (_playerTimer.Interval != 1000)
{
_playerTimer.Interval = 1000;
}
return;
}
Post(new { type = "player", player = BuildPlayer() });
int interval = MusicPlayer.Instance.IsPlaying ? 250 : 1000;
if (_playerTimer.Interval != interval)
{
_playerTimer.Interval = interval;
}
};
_playerTimer.Start();
// 自己处理贴边缩放:窗口不带系统可缩放边框,顶部就不会出现一条白边。
_resizeTimer = new System.Windows.Forms.Timer { Interval = 15 };
_resizeTimer.Tick += (_, _) => ResizeStep();
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
try
{
int preference = NativeMethods.DWMWCP_ROUND;
NativeMethods.DwmSetWindowAttribute(
Handle, NativeMethods.DWMWA_WINDOW_CORNER_PREFERENCE, ref preference, sizeof(int));
// 系统会给可缩放的无边框窗口描一圈浅色边,改成和背景一样的深色,顶部就不会有白线。
int darkBorder = 0x00101010; // COLORREF: 0x00BBGGRR
NativeMethods.DwmSetWindowAttribute(
Handle, NativeMethods.DWMWA_BORDER_COLOR, ref darkBorder, sizeof(int));
}
catch
{
// 旧系统没有这个属性,保持直角即可。
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
PostWindowState();
}
private async Task InitializeAsync()
{
for (int attempt = 0; attempt < 2; attempt++)
{
try
{
await InitializeOnceAsync();
return;
}
catch (Exception ex)
{
Log.Write($"WebView2 初始化失败({attempt + 1}/2): " + ex);
if (attempt == 1)
{
MessageBox.Show(this,
"界面组件初始化失败,请确认系统已安装 WebView2 Runtime。\n\n" + ex.Message,
"MINWallPaper", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
await Task.Delay(800);
}
}
}
}
private async Task InitializeOnceAsync()
{
string cache = Path.Combine(AppPaths.DataDir, "webview2");
Directory.CreateDirectory(cache);
var options = new CoreWebView2EnvironmentOptions
{
// 关掉后台联网、组件更新、扩展这些用不到的能力,减少常驻内存和磁盘活动。
// 预览视频强制走软解,把显卡硬解会话留给桌面动态壁纸,避免两边抢解码器。
// 整个界面用软件渲染,避免和桌面动态壁纸抢显卡资源导致黑闪。
AdditionalBrowserArguments =
"--disable-background-networking --disable-component-update --disable-sync " +
"--no-first-run --disable-extensions --disable-gpu"
};
CoreWebView2Environment environment =
await CoreWebView2Environment.CreateAsync(null, cache, options);
await _web.EnsureCoreWebView2Async(environment);
CoreWebView2 core = _web.CoreWebView2;
core.SetVirtualHostNameToFolderMapping(
"minwall.local", AppPaths.BaseDir, CoreWebView2HostResourceAccessKind.Allow);
core.Settings.AreDefaultContextMenusEnabled = false;
core.Settings.IsStatusBarEnabled = false;
core.Settings.AreDevToolsEnabled = false;
core.Settings.IsZoomControlEnabled = false;
core.Settings.IsPinchZoomEnabled = false;
core.WebMessageReceived += OnWebMessage;
core.NavigationCompleted += (_, _) =>
{
_ready = true;
PushState();
};
core.Navigate("https://minwall.local/Web/index.html");
Log.Write("Web UI 已加载");
}
private void OnDataChanged()
{
if (_disposed)
{
return;
}
PushState();
}
private void OnStatus(string text)
{
if (_disposed || !_ready)
{
return;
}
Post(new { type = "status", text });
}
private void Post(object payload)
{
if (_disposed)
{
return;
}
if (InvokeRequired)
{
try
{
BeginInvoke((Action)(() => Post(payload)));
}
catch (InvalidOperationException)
{
}
return;
}
try
{
_web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(payload, JsonOptions));
}
catch (Exception ex)
{
Log.Write("推送界面消息失败: " + ex.Message);
}
}
private void PushState(string? reason = null)
{
if (!_ready || _disposed)
{
return;
}
if (InvokeRequired)
{
try
{
BeginInvoke((Action)(() => PushState(reason)));
}
catch (InvalidOperationException)
{
}
return;
}
WallpaperHost host = WallpaperHost.Instance;
WallpaperLibrary library = WallpaperLibrary.Instance;
object? assignment = null;
MusicAssignment? saved = MusicAssignments.Get(host.CurrentPath);
if (saved != null)
{
assignment = new { kind = saved.Kind, value = saved.Value };
}
var payload = new
{
type = "state",
reason,
status = (string?)null,
current = new
{
path = host.CurrentPath,
kind = host.CurrentKind == WallpaperKind.Video ? "video"
: host.CurrentKind == WallpaperKind.Image ? "image" : null,
volume = host.Volume,
muted = host.Muted
},
wallpapers = library.Items.Select(item => new
{
path = item.Path,
name = item.Name,
kind = item.Kind == WallpaperKind.Video ? "video" : "image",
sizeBytes = item.SizeBytes,
favorite = item.Favorite,
thumb = item.ThumbnailPath == null ? null : ToUrl(item.ThumbnailPath),
media = ToUrl(item.Path)
}).ToList(),
widgets = BuildWidgets(),
rain = WidgetService.Instance.RainEnabled, music = new
{
scanning = MusicLibrary.Instance.IsScanning,
files = MusicLibrary.Instance.Files.Select(file => new
{
path = file.Path,
title = file.Title,
artist = ArtistOf(file.Path),
pinned = MusicPins.Contains(file.Path),
sizeBytes = file.SizeBytes,
duration = file.Duration.TotalSeconds,
url = ToUrl(file.Path)
}).ToList(),
categories = MusicLibrary.Instance.Categories,
playlists = MusicLibrary.Instance.Playlists.Select(playlist => new
{
id = playlist.Id,
name = playlist.Name,
tracks = playlist.Tracks.Select(track => new
{
path = track.Path,
title = track.Title,
url = ToUrl(track.Path)
}).ToList()
}).ToList()
},
player = BuildPlayer(),
window = new
{
maximized = WindowState == FormWindowState.Maximized
},
assignment
};
Post(payload);
}
private static List<object> BuildWidgets()
{
var list = new List<object>();
foreach (WidgetConfig config in WidgetService.Instance.Configs)
{
string? preview = null;
string? file = WidgetPreview.Ensure(config);
if (file != null)
{
preview = ToUrl(file) + "?v=" + File.GetLastWriteTimeUtc(file).Ticks;
}
list.Add(new
{
id = config.Id,
type = config.Type,
name = config.Name,
enabled = config.Enabled,
style = config.Style,
styleName = WidgetConfig.StyleName(config.Type, config.Style),
anchor = config.Anchor,
offsetX = config.OffsetX,
offsetY = config.OffsetY,
posX = config.PosX,
posY = config.PosY,
width = config.Width,
height = config.Height,
radius = config.Radius,
textColor = config.TextColor,
accentColor = config.AccentColor,
accentColor2 = config.AccentColor2,
bgColor = config.BgColor,
bgAlpha = config.BgAlpha,
fontFamily = config.FontFamily,
fontSize = config.FontSize,
textAlpha = config.TextAlpha,
goldText = config.GoldText,
signatureColor = config.SignatureColor,
signatureAlpha = config.SignatureAlpha,
clockFormat = config.ClockFormat,
dateFormat = config.DateFormat,
showWeek = config.ShowWeek,
content = config.Content,
images = config.Images,
carouselSeconds = config.CarouselSeconds,
sensitivity = config.Sensitivity,
barCount = config.BarCount,
preview
});
}
return list;
}
/// <summary>只推组件数据,编辑时免得整份壁纸/音乐状态一起重发。</summary>
private void PostWidgets()
{
Post(new
{
type = "widgets",
widgets = BuildWidgets(),
rain = WidgetService.Instance.RainEnabled
});
}
private static object BuildPlayer()
{
MusicPlayer player = MusicPlayer.Instance;
string? art = null;
string? lyrics = null;
if (player.CurrentPath != null)
{
if (MusicArtwork.Get(player.CurrentPath) is string artwork)
{
art = ToUrl(artwork);
}
string lrc = Path.ChangeExtension(player.CurrentPath, ".lrc");
if (File.Exists(lrc))
{
lyrics = ToUrl(lrc);
}
}
return new
{
path = player.CurrentPath,
title = player.CurrentTitle,
playing = player.IsPlaying,
position = player.Position,
duration = player.Duration,
mode = ModeName(player.Mode),
volume = player.Volume,
muted = player.Muted,
queueName = player.QueueName,
art,
lyrics
};
}
private void PostWindowState(bool force = false)
{
if (_disposed || !_ready)
{
return;
}
bool maximized = WindowState == FormWindowState.Maximized;
if (!force && _lastMaximized == maximized)
{
return;
}
_lastMaximized = maximized;
Post(new { type = "window", maximized });
}
private void DragWindow()
{
if (WindowState != FormWindowState.Normal)
{
return;
}
_moving = true;
_resizeEdge = "";
_resizeCursorStart = Cursor.Position;
_resizeBoundsStart = Bounds;
_resizeTimer.Start();
}
private void StartResize(string edge)
{
if (WindowState != FormWindowState.Normal || string.IsNullOrEmpty(edge))
{
return;
}
_resizeEdge = edge;
_moving = false;
_resizeCursorStart = Cursor.Position;
_resizeBoundsStart = Bounds;
_resizeTimer.Start();
}
private void ResizeStep()
{
if ((Control.MouseButtons & MouseButtons.Left) == 0)
{
_resizeTimer.Stop();
_moving = false;
_resizeEdge = "";
return;
}
Point cursor = Cursor.Position;
int dx = cursor.X - _resizeCursorStart.X;
int dy = cursor.Y - _resizeCursorStart.Y;
if (_moving)
{
Bounds = new Rectangle(
_resizeBoundsStart.Left + dx,
_resizeBoundsStart.Top + dy,
_resizeBoundsStart.Width,
_resizeBoundsStart.Height);
return;
}
int left = _resizeBoundsStart.Left;
int top = _resizeBoundsStart.Top;
int right = _resizeBoundsStart.Right;
int bottom = _resizeBoundsStart.Bottom;
if (_resizeEdge.Contains("left")) left += dx;
if (_resizeEdge.Contains("right")) right += dx;
if (_resizeEdge.Contains("top")) top += dy;
if (_resizeEdge.Contains("bottom")) bottom += dy;
int minWidth = MinimumSize.Width;
int minHeight = MinimumSize.Height;
if (right - left < minWidth)
{
if (_resizeEdge.Contains("left")) left = right - minWidth;
else right = left + minWidth;
}
if (bottom - top < minHeight)
{
if (_resizeEdge.Contains("top")) top = bottom - minHeight;
else bottom = top + minHeight;
}
Bounds = new Rectangle(left, top, right - left, bottom - top);
}
private void ToggleMaximize()
{
if (WindowState == FormWindowState.Maximized)
{
WindowState = FormWindowState.Normal;
}
else
{
// 无边框窗口最大化时默认会盖住任务栏,限制在工作区内。
MaximizedBounds = Screen.FromControl(this).WorkingArea;
WindowState = FormWindowState.Maximized;
}
PostWindowState(true);
}
private static string ModeName(MusicLoopMode mode) => mode switch
{
MusicLoopMode.Single => "single",
MusicLoopMode.Shuffle => "shuffle",
_ => "list"
};
private static MusicLoopMode ParseMode(string value) => value switch
{
"single" => MusicLoopMode.Single,
"shuffle" => MusicLoopMode.Shuffle,
_ => MusicLoopMode.List
};
private void OnPlayerChanged()
{
if (_disposed || !_ready)
{
return;
}
Post(new { type = "player", player = BuildPlayer() });
}
private void OnWidgetsChanged()
{
if (_disposed || !_ready)
{
return;
}
PostWidgets();
}
private static string ToUrl(string fullPath)
{
string relative = Path.GetRelativePath(AppPaths.BaseDir, fullPath).Replace('\\', '/');
return "https://minwall.local/" +
string.Join("/", relative.Split('/').Select(Uri.EscapeDataString));
}
private void OnWebMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
try
{
using JsonDocument document = JsonDocument.Parse(e.WebMessageAsJson);
JsonElement root = document.RootElement;
string cmd = GetString(root, "cmd");
switch (cmd)
{
case "init":
PushState();
break;
case "play":
PlayWallpaper(GetString(root, "path"));
break;
case "getPreview":
RequestPreview(GetString(root, "path"));
break;
case "favorite":
ToggleFavorite(GetString(root, "path"));
break;
case "playerToggle":
MusicPlayer.Instance.Toggle();
break;
case "playerNext":
MusicPlayer.Instance.Next();
break;
case "playerPrev":
MusicPlayer.Instance.Previous();
break;
case "playerMode":
MusicPlayer.Instance.SetMode(ParseMode(GetString(root, "mode")));
break;
case "playerSeek":
MusicPlayer.Instance.Seek(GetDouble(root, "value"));
break;
case "playerVolume":
MusicPlayer.Instance.SetVolume(GetDouble(root, "value"));
break;
case "playerMute":
MusicPlayer.Instance.SetMuted(
root.TryGetProperty("value", out JsonElement playerMute) &&
playerMute.ValueKind == JsonValueKind.True);
break;
case "winDrag":
DragWindow();
break;
case "winMin":
WindowState = FormWindowState.Minimized;
break;
case "winMax":
ToggleMaximize();
break;
case "winClose":
Close();
break;
case "winResize":
StartResize(GetString(root, "edge"));
break;
case "playLocal":
PlayLocal(GetInt(root, "index"));
break;
case "playArtist":
PlayArtist(GetString(root, "artist"), GetString(root, "path"));
break;
case "pinTrack":
{
string path = GetString(root, "path");
bool pinned = MusicPins.Toggle(path);
Post(new { type = "toast", text = pinned ? "已置顶" : "已取消置顶" });
PushState();
break;
}
case "moveTrackCategory":
{
string path = GetString(root, "path");
string category = GetString(root, "category");
if (string.Equals(MusicPlayer.Instance.CurrentPath, path,
StringComparison.OrdinalIgnoreCase))
{
Post(new { type = "toast", text = "正在播放这首歌,切换后再分类" });
break;
}
string? moved = MusicLibrary.Instance.MoveToCategory(path, category);
if (moved == null)
{
Post(new { type = "toast", text = "分类失败,请稍后再试" });
break;
}
MusicPins.ReplacePath(path, moved);
MusicPlayer.Instance.ReplacePath(path, moved);
Post(new { type = "toast", text = "已移到「" + category + "」" });
PushState();
break;
}
case "createCategory":
{
string categoryName = GetString(root, "name");
if (MusicLibrary.Instance.CreateCategory(categoryName))
{
Post(new { type = "toast", text = "已新建分类「" + categoryName + "」" });
PushState();
}
else
{
Post(new { type = "toast", text = "分类名重复或包含非法字符" });
}
break;
}
case "renameCategory":
{
string oldName = GetString(root, "oldName");
string newName = GetString(root, "newName");
string oldDir = Path.Combine(MusicLibrary.Instance.FilesDir, oldName);
string separator = Path.DirectorySeparatorChar.ToString();
if (MusicPlayer.Instance.CurrentPath is string current &&
current.StartsWith(oldDir + separator, StringComparison.OrdinalIgnoreCase))
{
Post(new { type = "toast", text = "正在播放这个分类的歌,先切换再改名" });
break;
}
if (MusicLibrary.Instance.RenameCategory(oldName, newName))
{
string newDir = Path.Combine(MusicLibrary.Instance.FilesDir, newName);
MusicPins.ReplacePrefix(oldDir, newDir);
MusicPlayer.Instance.ReplacePrefix(oldDir, newDir);
Post(new { type = "toast", text = "已改名为「" + newName + "」" });
PushState();
}
else
{
Post(new { type = "toast", text = "改名失败,可能重名或包含非法字符" });
}
break;
}
case "playPlaylist":
PlayPlaylist(GetString(root, "id"));
break;
case "assignPlaylist":
AssignPlaylist(GetString(root, "id"));
break;
case "assignTrack":
AssignTrack(GetString(root, "path"));
break;
case "addWidget":
WidgetService.Instance.Add(GetString(root, "kind"));
PostWidgets();
break;
case "updateWidget":
if (root.TryGetProperty("widget", out JsonElement widgetElement))
{
WidgetService.Instance.Update(WidgetConfig.FromJson(widgetElement.GetRawText()));
}
PostWidgets();
break;
case "beginWidgetDrag":
WidgetService.Instance.SetDragMode(GetString(root, "id"));
break;
case "endWidgetDrag":
WidgetService.Instance.SetDragMode(null);
break;
case "deleteWidget":
WidgetService.Instance.Remove(GetString(root, "id"));
PostWidgets();
break;
case "setWidgetEnabled":
WidgetService.Instance.SetEnabled(
GetString(root, "id"),
root.TryGetProperty("enabled", out JsonElement widgetEnabled) && widgetEnabled.GetBoolean());
PostWidgets();
break;
case "setRain":
WidgetService.Instance.SetRainEnabled(
root.TryGetProperty("enabled", out JsonElement rainEnabled) && rainEnabled.GetBoolean());
PostWidgets();
break;
case "pickWidgetImages":
PickWidgetImages(GetString(root, "id"));
break;
case "clearWidgetImages":
WidgetService.Instance.SetImages(GetString(root, "id"), Array.Empty<string>());
break;
case "rescanWallpapers":
WallpaperLibrary.Instance.Rescan();
break;
case "openWallpaperFolder":
OpenFolder(WallpaperLibrary.Instance.Root);
break;
case "createPlaylist":
string name = GetString(root, "name");
if (!string.IsNullOrWhiteSpace(name))
{
MusicLibrary.Instance.CreatePlaylist(name.Trim());
}
break;
case "deletePlaylist":
MusicPlaylist? playlist = MusicLibrary.Instance.Playlists
.FirstOrDefault(p => p.Id == GetString(root, "id"));
if (playlist != null)
{
MusicLibrary.Instance.RemovePlaylist(playlist);
}
break;
case "addTrack":
AddTrack(GetString(root, "playlistId"), GetString(root, "path"));
break;
case "removeTrack":
RemoveTrack(GetString(root, "playlistId"), GetString(root, "path"));
break;
case "moveTrack":
MoveTrack(GetString(root, "playlistId"), GetInt(root, "from"), GetInt(root, "to"));
break;
case "rescanMusic":
MusicLibrary.Instance.Rescan();
break;
case "openMusicFolder":
OpenFolder(MusicLibrary.Instance.Root);
break;
}
}
catch (Exception ex)
{
Log.Write("处理界面消息失败: " + ex);
}
}
private static void PlayLocal(int index)
{
IReadOnlyList<MusicFile> files = MusicLibrary.Instance.Files;
if (index < 0 || index >= files.Count)
{
return;
}
MusicPlayer.Instance.PlayQueue(
files.Select(f => f.Path).ToList(), index,
MusicPlayer.Instance.Mode, "本地音乐");
}
/// <summary>不像歌手名的文件夹名,遇到这些再去看文件名。</summary>
private static readonly HashSet<string> NonArtistFolders = new(StringComparer.OrdinalIgnoreCase)
{
"files", "music", "songs", "audio", "download", "downloads",
"english", "other", "others", "unknown", "various artists", "va",
"音乐", "歌曲", "我的音乐", "未分类", "其他", "群星", "合集", "精选"
};
/// <summary>
/// 自动识别歌手:优先用歌曲所在的歌手文件夹(周杰伦、许嵩这种),
/// 文件夹不像歌手名时,再从文件名尾部的“- 歌手”里取。
/// </summary>
private static string ArtistOf(string path)
{
string folder = Path.GetFileName(Path.GetDirectoryName(path) ?? "").Trim();
// 这些是固定分类,不再从文件名里拆歌手。
if (folder is "其他" or "日语" or "狐妖" or "动漫")
{
return folder;
}
if (!string.IsNullOrEmpty(folder) && !NonArtistFolders.Contains(folder))
{
return folder;
}
string artist = ArtistFromFileName(Path.GetFileNameWithoutExtension(path));
return string.IsNullOrWhiteSpace(artist) ? "其他" : artist;
}
private static string ArtistFromFileName(string fileName)
{
// 去掉开头的音轨号,例如 “01. ”、“02 - ”。
string name = Regex.Replace(fileName, @"^\s*\d{1,3}\s*[\.\-_、]\s*", "");
// “歌名 - 歌手” 带空格的横线最可靠。
string[] parts = name.Split(" - ", StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2)
{
return CleanArtist(parts[^1]);
}
// “歌名-歌手” 或 “歌手A-歌名-歌手B” 这种没有空格的,默认取最后一段。
parts = name.Split('-', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2)
{
return CleanArtist(parts[^1]);
}
return "";
}
private static string CleanArtist(string value)
{
// 去掉尾部括号里的版本说明,例如 “周杰伦 (Live)”。
string artist = Regex.Replace(value.Trim(), @"\s*[\(\[(【].*?[\)\])】]\s*$", "").Trim();
if (artist.Length == 0 || artist.Length > 24 || artist.All(char.IsDigit))
{
return "";
}
return artist;
}
private static void PlayArtist(string artist, string? path)
{
var files = MusicLibrary.Instance.Files
.Where(f => ArtistOf(f.Path) == artist)
.ToList();
if (files.Count == 0)
{
return;
}
int index = 0;
if (!string.IsNullOrEmpty(path))
{
int hit = files.FindIndex(f => string.Equals(f.Path, path, StringComparison.OrdinalIgnoreCase));
if (hit >= 0)
{
index = hit;
}
}
MusicPlayer.Instance.PlayQueue(
files.Select(f => f.Path).ToList(), index,
MusicPlayer.Instance.Mode, artist);
}
private static void PlayPlaylist(string playlistId)
{
MusicPlaylist? playlist = MusicLibrary.Instance.Playlists.FirstOrDefault(p => p.Id == playlistId);
if (playlist is { Tracks.Count: > 0 })
{
MusicPlayer.Instance.PlayQueue(
playlist.Tracks.Select(t => t.Path).ToList(), 0,
MusicPlayer.Instance.Mode, playlist.Name);
}
}
private void AssignPlaylist(string playlistId)
{
string? wallpaper = WallpaperHost.Instance.CurrentPath;
MusicPlaylist? playlist = MusicLibrary.Instance.Playlists.FirstOrDefault(p => p.Id == playlistId);
if (wallpaper == null || playlist == null)
{
return;
}
MusicAssignments.Set(wallpaper, "playlist", playlist.Id);
if (playlist.Tracks.Count > 0)
{
MusicPlayer.Instance.PlayQueue(
playlist.Tracks.Select(t => t.Path).ToList(), 0,