casualexpiesource

cu-trainer/Ultra Paradise Linux/app/MusicPage.cs

339 lines · 16.4 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Globalization;
5using System.IO;
6using System.Linq;
7using System.Text.RegularExpressions;
8using System.Threading.Tasks;
9using Avalonia;
10using Avalonia.Controls;
11using Avalonia.Layout;
12using Avalonia.Platform.Storage;
13using Path = System.IO.Path;
14
15namespace UltraParadise.Linux
16{
17 internal sealed partial class MainWindow
18 {
19 private const char MUSEP = '\u001c';
20 private readonly TextBlock jamText = T("", 17, Ui.B(Ui.Orange), true, true);
21 private readonly TextBlock extPlayerText = T("", 13, Ui.B(Ui.Soft), false, true);
22 private readonly TextBlock extTrackText = T("", 14, Ui.B(Ui.Text), true, true);
23 private readonly WrapPanel extButtons = new();
24 private readonly TextBlock gmStatusText = T("", 13.5, Ui.B(Ui.Text), true, true);
25 private readonly TextBlock gmSongText = T("", 13, Ui.B(Ui.Soft), false, true);
26 private readonly Button gmGive = Btn("Give Me an MP3 Player", () => { }, false);
27 private readonly StackPanel songList = new() { Spacing = 4 };
28 private readonly StackPanel gameSongList = new() { Spacing = 4 };
29 private readonly List<string> gameSongs = new();
30 private bool extFound, extScanning, jamShown, gameSongsAsked;
31 private string extApp = "", extTitle = "", extBus;
32 private DateTime extNext = DateTime.MinValue;
33 private bool gmRun, gmHas, gmHeld, gmPlaying;
34 private string gmSong = "", gmLoading = "";
35 private int gmPos, gmLen;
36
37 private bool MusicVisible => page == "Music";
38
39 private string MusicFolder() => game == null ? null : Path.Combine(game, "CasualtiesUnknown_Data", "custommusic");
40
41 private static WrapPanel Row(params Button[] bs)
42 {
43 WrapPanel w = new();
44 foreach (Button b in bs) { b.Margin = new Thickness(0, 4, 6, 0); w.Children.Add(b); }
45 return w;
46 }
47
48 private Control MusicPage()
49 {
50 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
51
52 Border a = Section("NOW PLAYING", out StackPanel ab);
53 BuildNowPlaying(ab);
54 StackPanel c0 = new() { Margin = new Thickness(0, 0, 7, 0) };
55 c0.Children.Add(a);
56 c0.Children.Add(BuildLyrics());
57 g.Children.Add(c0);
58
59 Border b = Section("GAME MP3 PLAYER", out StackPanel bb);
60 bb.Children.Add(gmStatusText);
61 bb.Children.Add(gmSongText);
62 bb.Children.Add(Row(Btn("Stop", () => GameMusic("MUSICSTOP")), Btn("-10s", () => GameMusic("MUSICSEEK -10")), Btn("+10s", () => GameMusic("MUSICSEEK 10")), Btn("Layer Song", () => GameMusic("MUSICNEXT"))));
63 gmGive.Click += (_, _) => GameMusic("SPAWN mp3player 1");
64 bb.Children.Add(Row(gmGive));
65 bb.Children.Add(T("Songs you play here go through the game's own music player, the same one the MP3 player uses, so they follow the game's sound settings. You don't need the MP3 player to play them from the trainer.", 12, Ui.B(Ui.Dim), false, true));
66 StackPanel c1 = new() { Margin = new Thickness(7, 0, 7, 0) };
67 c1.Children.Add(b);
68 Grid.SetColumn(c1, 1);
69 g.Children.Add(c1);
70
71 Border s = Section("YOUR SONGS", out StackPanel sb);
72 sb.Children.Add(Row(Btn("Open Folder", OpenMusicFolder), Btn("Add Songs...", () => _ = AddSongs()), Btn("Refresh", () => { gameSongsAsked = false; MusicShown(); RebuildSongs(); })));
73 sb.Children.Add(songList);
74 Border gs = Section("GAME SONGS", out StackPanel gsb);
75 gsb.Children.Add(gameSongList);
76 StackPanel c2 = new() { Margin = new Thickness(7, 0, 0, 0) };
77 c2.Children.Add(s);
78 c2.Children.Add(gs);
79 Grid.SetColumn(c2, 2);
80 g.Children.Add(c2);
81
82 RefreshMusic();
83 RebuildSongs();
84 return Scroll(g);
85 }
86
87 private void GameMusic(string cmd)
88 {
89 if (!Linked()) { Message("Attach to the game first.", true); return; }
90 link.Send(cmd);
91 }
92
93 private void RefreshMusic()
94 {
95 RefreshNowPlaying();
96
97 bool live = link.IsConnected;
98 gmStatusText.Text = !live ? "Not attached to the game." : !gmRun ? "Start a run to use the game's music player." : gmHeld ? "You're holding the MP3 player." : gmHas ? "The MP3 player is in your inventory." : "You don't have an MP3 player.";
99 gmSongText.Text = !live || !gmRun ? "" : gmLoading.Length > 0 ? "Loading " + gmLoading + "..." : gmPlaying ? "Now playing: " + gmSong + " " + Clock(gmPos) + " / " + Clock(gmLen) : "Nothing playing";
100 gmSongText.IsVisible = gmSongText.Text.Length > 0;
101 gmGive.IsVisible = live && gmRun && !gmHas;
102 }
103
104 private static string Clock(int s) => (s / 60).ToString(CultureInfo.InvariantCulture) + ":" + (s % 60).ToString("00", CultureInfo.InvariantCulture);
105
106 private void RebuildSongs()
107 {
108 songList.Children.Clear();
109 string dir = MusicFolder();
110 List<string> files = new();
111 if (dir != null && Directory.Exists(dir))
112 {
113 try { files = Directory.GetFiles(dir).Where(f => Path.GetExtension(f).ToLowerInvariant() is ".mp3" or ".ogg" or ".wav").Select(Path.GetFileName).OrderBy(f => f, StringComparer.OrdinalIgnoreCase).ToList(); }
114 catch (Exception) { }
115 }
116 if (dir == null) songList.Children.Add(T("Pick the game in Game Setup first.", 13, Ui.B(Ui.Dim), false, true));
117 else if (files.Count == 0) songList.Children.Add(T("No songs yet. Click Add Songs (mp3, ogg or wav), or drop them in the game's custommusic folder. The MP3 player in the game picks them up too.", 13, Ui.B(Ui.Dim), false, true));
118 foreach (string f in files) songList.Children.Add(SongRow(f, "MUSICPLAY f " + f));
119
120 gameSongList.Children.Clear();
121 if (gameSongs.Count == 0) gameSongList.Children.Add(T(link.IsConnected ? "Loading the game's songs..." : "Attach to the game to see its songs.", 13, Ui.B(Ui.Dim), false, true));
122 foreach (string s in gameSongs) gameSongList.Children.Add(SongRow(s, "MUSICPLAY b " + s));
123 }
124
125 private Control SongRow(string name, string cmd)
126 {
127 Grid r = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
128 TextBlock t = T(name, 13, Ui.B(Ui.Text));
129 t.TextTrimming = Avalonia.Media.TextTrimming.CharacterEllipsis;
130 t.VerticalAlignment = VerticalAlignment.Center;
131 r.Children.Add(t);
132 Button p = Btn("Play", () => GameMusic(cmd));
133 p.MinHeight = 28;
134 p.Padding = new Thickness(12, 3);
135 Grid.SetColumn(p, 1);
136 r.Children.Add(p);
137 return r;
138 }
139
140 private void OpenMusicFolder()
141 {
142 string d = MusicFolder();
143 if (d == null) { Message("Pick the game in Game Setup first.", true); return; }
144 try { Directory.CreateDirectory(d); } catch (Exception) { }
145 Game.Open(d);
146 }
147
148 private async Task AddSongs()
149 {
150 string d = MusicFolder();
151 if (d == null) { Message("Pick the game in Game Setup first.", true); return; }
152 IReadOnlyList<IStorageFile> r = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
153 {
154 Title = "Add songs to the game",
155 AllowMultiple = true,
156 FileTypeFilter = new[] { new FilePickerFileType("Songs") { Patterns = new[] { "*.mp3", "*.ogg", "*.wav", "*.MP3", "*.OGG", "*.WAV" } } },
157 });
158 int n = 0;
159 try
160 {
161 Directory.CreateDirectory(d);
162 foreach (IStorageFile f in r)
163 {
164 string src = f.TryGetLocalPath();
165 if (src == null) continue;
166 string to = Path.Combine(d, Path.GetFileName(src));
167 if (File.Exists(to)) continue;
168 File.Copy(src, to);
169 n++;
170 }
171 }
172 catch (Exception e) { Message("Couldn't copy the songs: " + e.Message, true); }
173 if (n > 0) Message("Added " + n + " song" + (n == 1 ? "" : "s") + ". The game's own MP3 player sees them after a game restart; the trainer can play them right away.", false);
174 RebuildSongs();
175 }
176
177 private void MusicShown()
178 {
179 if (!link.IsConnected) return;
180 link.Send("MUSIC " + (MusicVisible ? "1" : "0"));
181 if (MusicVisible && !gameSongsAsked) { gameSongsAsked = true; link.Send("MUSICLIST"); }
182 }
183
184 private void MusicConnected()
185 {
186 gameSongsAsked = false;
187 MusicShown();
188 RefreshMusic();
189 }
190
191 private void MusicDisconnected()
192 {
193 gmRun = gmHas = gmHeld = gmPlaying = false;
194 gmSong = gmLoading = "";
195 RefreshMusic();
196 RebuildSongs();
197 }
198
199 private void OnMusicLine(string rest)
200 {
201 string[] f = rest.Split(MUSEP);
202 if (f.Length < 8) return;
203 gmRun = f[0] == "1";
204 gmHas = f[1] == "1";
205 gmHeld = f[2] == "1";
206 gmPlaying = f[3] == "1";
207 gmSong = f[4];
208 int.TryParse(f[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out gmPos);
209 gmStamp = DateTime.UtcNow;
210 int.TryParse(f[6], NumberStyles.Integer, CultureInfo.InvariantCulture, out gmLen);
211 gmLoading = f[7];
212 RefreshMusic();
213 }
214
215 private void OnMusicList(string rest)
216 {
217 gameSongs.Clear();
218 gameSongs.AddRange(rest.Split(MUSEP).Select(s => s.Trim()).Where(s => s.Length > 0).OrderBy(s => s, StringComparer.OrdinalIgnoreCase));
219 RebuildSongs();
220 }
221
222 private static (bool found, string app, List<int> pids) ScanProcs()
223 {
224 bool sp = false, yt = false;
225 List<int> pids = new();
226 try
227 {
228 foreach (string d in Directory.GetDirectories("/proc"))
229 {
230 string n = Path.GetFileName(d);
231 if (n.Length == 0 || !char.IsDigit(n[0])) continue;
232 string comm;
233 try { comm = File.ReadAllText(Path.Combine(d, "comm")).Trim().ToLowerInvariant(); } catch (Exception) { continue; }
234 bool s = comm.StartsWith("spotify", StringComparison.Ordinal);
235 bool y = comm.StartsWith("youtube-music", StringComparison.Ordinal) || comm.StartsWith("youtube music", StringComparison.Ordinal) || comm.StartsWith("ytmdesktop", StringComparison.Ordinal) || comm == "ytmapp" || comm == "ytmusic";
236 if (!s && !y) continue;
237 sp |= s;
238 yt |= y;
239 if (int.TryParse(n, out int pid)) pids.Add(pid);
240 }
241 }
242 catch (Exception) { }
243 return (sp || yt, sp ? "Spotify" : yt ? "YouTube Music Desktop" : "", pids);
244 }
245
246 private static async Task<string> DBus(params string[] args)
247 {
248 try
249 {
250 ProcessStartInfo si = new("dbus-send") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true };
251 si.ArgumentList.Add("--session");
252 foreach (string a in args) si.ArgumentList.Add(a);
253 using Process p = Process.Start(si);
254 if (p == null) return null;
255 Task<string> o = p.StandardOutput.ReadToEndAsync();
256 if (await Task.WhenAny(o, Task.Delay(2000)) != o) { try { p.Kill(); } catch (Exception) { } return null; }
257 await p.WaitForExitAsync();
258 return p.ExitCode == 0 ? o.Result : null;
259 }
260 catch (Exception) { return null; }
261 }
262
263 private static async Task<string> FindBus(string app, List<int> pids)
264 {
265 string names = await DBus("--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus.ListNames");
266 if (names == null) return null;
267 List<string> mpris = Regex.Matches(names, "\"(org\\.mpris\\.MediaPlayer2\\.[^\"]+)\"").Select(m => m.Groups[1].Value).ToList();
268 if (app == "Spotify") return mpris.FirstOrDefault(n => n.ToLowerInvariant().Contains("spotify"));
269 string by = mpris.FirstOrDefault(n => { string l = n.ToLowerInvariant(); return l.Contains("youtube") || l.Contains("ytm"); });
270 if (by != null) return by;
271 foreach (string n in mpris)
272 {
273 Match m = Regex.Match(n, "instance(\\d+)$");
274 if (m.Success && int.TryParse(m.Groups[1].Value, out int pid) && pids.Contains(pid)) return n;
275 }
276 return null;
277 }
278
279 private static string Unescape(string s) => s.Replace("\\\"", "\"").Replace("\\\\", "\\");
280
281 private static async Task<string> TrackOf(string bus)
282 {
283 string md = await DBus("--print-reply", "--dest=" + bus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:Metadata");
284 if (md == null) return "";
285 Match t = Regex.Match(md, "\"xesam:title\"\\s*variant\\s+string\\s+\"((?:[^\"\\\\]|\\\\.)*)\"");
286 Match a = Regex.Match(md, "\"xesam:artist\"\\s*variant\\s+array\\s*\\[\\s*string\\s+\"((?:[^\"\\\\]|\\\\.)*)\"");
287 string title = t.Success ? Unescape(t.Groups[1].Value) : "";
288 string artist = a.Success ? Unescape(a.Groups[1].Value) : "";
289 string st = await DBus("--print-reply", "--dest=" + bus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:PlaybackStatus");
290 bool paused = st != null && !st.Contains("\"Playing\"");
291 if (title.Length == 0) return "";
292 return (artist.Length > 0 ? artist + " - " : "") + title + (paused ? " (paused)" : "");
293 }
294
295 private async Task Mpris(string method)
296 {
297 if (extBus == null) return;
298 await DBus("--type=method_call", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player." + method);
299 extNext = DateTime.UtcNow.AddMilliseconds(600);
300 }
301
302 private async Task MprisVolume(double d)
303 {
304 if (extBus == null) return;
305 string v = await DBus("--print-reply", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:Volume");
306 Match m = v == null ? Match.Empty : Regex.Match(v, "double\\s+([0-9.eE+-]+)");
307 double cur = m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double x) ? x : 0.5;
308 double nv = Math.Clamp(cur + d, 0, 1);
309 await DBus("--print-reply", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Set", "string:org.mpris.MediaPlayer2.Player", "string:Volume", "variant:double:" + nv.ToString("0.##", CultureInfo.InvariantCulture));
310 Message("Volume " + (int)Math.Round(nv * 100) + "%", false);
311 }
312
313 private void MusicTick()
314 {
315 if (Mac.On || OperatingSystem.IsWindows() || extScanning || DateTime.UtcNow < extNext) return;
316 extNext = DateTime.UtcNow.AddSeconds(MusicVisible ? 1 : 3);
317 extScanning = true;
318 _ = Task.Run(async () =>
319 {
320 var (found, app, pids) = ScanProcs();
321 string bus = found ? await FindBus(app, pids) : null;
322 MprisState st = bus != null ? await StateOf(bus) : null;
323 Avalonia.Threading.Dispatcher.UIThread.Post(() =>
324 {
325 extScanning = false;
326 bool was = extFound;
327 extFound = found;
328 extApp = app;
329 extBus = bus;
330 extTitle = st?.Line ?? "";
331 ApplyMpris(st);
332 if (found && !was && !jamShown) { jamShown = true; Message("Jamming? Control your media here! (Music tab)", false); }
333 if (!found) jamShown = false;
334 RefreshMusic();
335 });
336 });
337 }
338 }
339}