using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Platform.Storage; using Path = System.IO.Path; namespace UltraParadise.Linux { internal sealed partial class MainWindow { private const char MUSEP = '\u001c'; private readonly TextBlock jamText = T("", 17, Ui.B(Ui.Orange), true, true); private readonly TextBlock extPlayerText = T("", 13, Ui.B(Ui.Soft), false, true); private readonly TextBlock extTrackText = T("", 14, Ui.B(Ui.Text), true, true); private readonly WrapPanel extButtons = new(); private readonly TextBlock gmStatusText = T("", 13.5, Ui.B(Ui.Text), true, true); private readonly TextBlock gmSongText = T("", 13, Ui.B(Ui.Soft), false, true); private readonly Button gmGive = Btn("Give Me an MP3 Player", () => { }, false); private readonly StackPanel songList = new() { Spacing = 4 }; private readonly StackPanel gameSongList = new() { Spacing = 4 }; private readonly List gameSongs = new(); private bool extFound, extScanning, jamShown, gameSongsAsked; private string extApp = "", extTitle = "", extBus; private DateTime extNext = DateTime.MinValue; private bool gmRun, gmHas, gmHeld, gmPlaying; private string gmSong = "", gmLoading = ""; private int gmPos, gmLen; private bool MusicVisible => page == "Music"; private string MusicFolder() => game == null ? null : Path.Combine(game, "CasualtiesUnknown_Data", "custommusic"); private static WrapPanel Row(params Button[] bs) { WrapPanel w = new(); foreach (Button b in bs) { b.Margin = new Thickness(0, 4, 6, 0); w.Children.Add(b); } return w; } private Control MusicPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; Border a = Section("NOW PLAYING", out StackPanel ab); BuildNowPlaying(ab); StackPanel c0 = new() { Margin = new Thickness(0, 0, 7, 0) }; c0.Children.Add(a); c0.Children.Add(BuildLyrics()); g.Children.Add(c0); Border b = Section("GAME MP3 PLAYER", out StackPanel bb); bb.Children.Add(gmStatusText); bb.Children.Add(gmSongText); bb.Children.Add(Row(Btn("Stop", () => GameMusic("MUSICSTOP")), Btn("-10s", () => GameMusic("MUSICSEEK -10")), Btn("+10s", () => GameMusic("MUSICSEEK 10")), Btn("Layer Song", () => GameMusic("MUSICNEXT")))); gmGive.Click += (_, _) => GameMusic("SPAWN mp3player 1"); bb.Children.Add(Row(gmGive)); 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)); StackPanel c1 = new() { Margin = new Thickness(7, 0, 7, 0) }; c1.Children.Add(b); Grid.SetColumn(c1, 1); g.Children.Add(c1); Border s = Section("YOUR SONGS", out StackPanel sb); sb.Children.Add(Row(Btn("Open Folder", OpenMusicFolder), Btn("Add Songs...", () => _ = AddSongs()), Btn("Refresh", () => { gameSongsAsked = false; MusicShown(); RebuildSongs(); }))); sb.Children.Add(songList); Border gs = Section("GAME SONGS", out StackPanel gsb); gsb.Children.Add(gameSongList); StackPanel c2 = new() { Margin = new Thickness(7, 0, 0, 0) }; c2.Children.Add(s); c2.Children.Add(gs); Grid.SetColumn(c2, 2); g.Children.Add(c2); RefreshMusic(); RebuildSongs(); return Scroll(g); } private void GameMusic(string cmd) { if (!Linked()) { Message("Attach to the game first.", true); return; } link.Send(cmd); } private void RefreshMusic() { RefreshNowPlaying(); bool live = link.IsConnected; 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."; gmSongText.Text = !live || !gmRun ? "" : gmLoading.Length > 0 ? "Loading " + gmLoading + "..." : gmPlaying ? "Now playing: " + gmSong + " " + Clock(gmPos) + " / " + Clock(gmLen) : "Nothing playing"; gmSongText.IsVisible = gmSongText.Text.Length > 0; gmGive.IsVisible = live && gmRun && !gmHas; } private static string Clock(int s) => (s / 60).ToString(CultureInfo.InvariantCulture) + ":" + (s % 60).ToString("00", CultureInfo.InvariantCulture); private void RebuildSongs() { songList.Children.Clear(); string dir = MusicFolder(); List files = new(); if (dir != null && Directory.Exists(dir)) { 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(); } catch (Exception) { } } if (dir == null) songList.Children.Add(T("Pick the game in Game Setup first.", 13, Ui.B(Ui.Dim), false, true)); 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)); foreach (string f in files) songList.Children.Add(SongRow(f, "MUSICPLAY f " + f)); gameSongList.Children.Clear(); 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)); foreach (string s in gameSongs) gameSongList.Children.Add(SongRow(s, "MUSICPLAY b " + s)); } private Control SongRow(string name, string cmd) { Grid r = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; TextBlock t = T(name, 13, Ui.B(Ui.Text)); t.TextTrimming = Avalonia.Media.TextTrimming.CharacterEllipsis; t.VerticalAlignment = VerticalAlignment.Center; r.Children.Add(t); Button p = Btn("Play", () => GameMusic(cmd)); p.MinHeight = 28; p.Padding = new Thickness(12, 3); Grid.SetColumn(p, 1); r.Children.Add(p); return r; } private void OpenMusicFolder() { string d = MusicFolder(); if (d == null) { Message("Pick the game in Game Setup first.", true); return; } try { Directory.CreateDirectory(d); } catch (Exception) { } Game.Open(d); } private async Task AddSongs() { string d = MusicFolder(); if (d == null) { Message("Pick the game in Game Setup first.", true); return; } IReadOnlyList r = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Add songs to the game", AllowMultiple = true, FileTypeFilter = new[] { new FilePickerFileType("Songs") { Patterns = new[] { "*.mp3", "*.ogg", "*.wav", "*.MP3", "*.OGG", "*.WAV" } } }, }); int n = 0; try { Directory.CreateDirectory(d); foreach (IStorageFile f in r) { string src = f.TryGetLocalPath(); if (src == null) continue; string to = Path.Combine(d, Path.GetFileName(src)); if (File.Exists(to)) continue; File.Copy(src, to); n++; } } catch (Exception e) { Message("Couldn't copy the songs: " + e.Message, true); } 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); RebuildSongs(); } private void MusicShown() { if (!link.IsConnected) return; link.Send("MUSIC " + (MusicVisible ? "1" : "0")); if (MusicVisible && !gameSongsAsked) { gameSongsAsked = true; link.Send("MUSICLIST"); } } private void MusicConnected() { gameSongsAsked = false; MusicShown(); RefreshMusic(); } private void MusicDisconnected() { gmRun = gmHas = gmHeld = gmPlaying = false; gmSong = gmLoading = ""; RefreshMusic(); RebuildSongs(); } private void OnMusicLine(string rest) { string[] f = rest.Split(MUSEP); if (f.Length < 8) return; gmRun = f[0] == "1"; gmHas = f[1] == "1"; gmHeld = f[2] == "1"; gmPlaying = f[3] == "1"; gmSong = f[4]; int.TryParse(f[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out gmPos); gmStamp = DateTime.UtcNow; int.TryParse(f[6], NumberStyles.Integer, CultureInfo.InvariantCulture, out gmLen); gmLoading = f[7]; RefreshMusic(); } private void OnMusicList(string rest) { gameSongs.Clear(); gameSongs.AddRange(rest.Split(MUSEP).Select(s => s.Trim()).Where(s => s.Length > 0).OrderBy(s => s, StringComparer.OrdinalIgnoreCase)); RebuildSongs(); } private static (bool found, string app, List pids) ScanProcs() { bool sp = false, yt = false; List pids = new(); try { foreach (string d in Directory.GetDirectories("/proc")) { string n = Path.GetFileName(d); if (n.Length == 0 || !char.IsDigit(n[0])) continue; string comm; try { comm = File.ReadAllText(Path.Combine(d, "comm")).Trim().ToLowerInvariant(); } catch (Exception) { continue; } bool s = comm.StartsWith("spotify", StringComparison.Ordinal); bool y = comm.StartsWith("youtube-music", StringComparison.Ordinal) || comm.StartsWith("youtube music", StringComparison.Ordinal) || comm.StartsWith("ytmdesktop", StringComparison.Ordinal) || comm == "ytmapp" || comm == "ytmusic"; if (!s && !y) continue; sp |= s; yt |= y; if (int.TryParse(n, out int pid)) pids.Add(pid); } } catch (Exception) { } return (sp || yt, sp ? "Spotify" : yt ? "YouTube Music Desktop" : "", pids); } private static async Task DBus(params string[] args) { try { ProcessStartInfo si = new("dbus-send") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; si.ArgumentList.Add("--session"); foreach (string a in args) si.ArgumentList.Add(a); using Process p = Process.Start(si); if (p == null) return null; Task o = p.StandardOutput.ReadToEndAsync(); if (await Task.WhenAny(o, Task.Delay(2000)) != o) { try { p.Kill(); } catch (Exception) { } return null; } await p.WaitForExitAsync(); return p.ExitCode == 0 ? o.Result : null; } catch (Exception) { return null; } } private static async Task FindBus(string app, List pids) { string names = await DBus("--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus.ListNames"); if (names == null) return null; List mpris = Regex.Matches(names, "\"(org\\.mpris\\.MediaPlayer2\\.[^\"]+)\"").Select(m => m.Groups[1].Value).ToList(); if (app == "Spotify") return mpris.FirstOrDefault(n => n.ToLowerInvariant().Contains("spotify")); string by = mpris.FirstOrDefault(n => { string l = n.ToLowerInvariant(); return l.Contains("youtube") || l.Contains("ytm"); }); if (by != null) return by; foreach (string n in mpris) { Match m = Regex.Match(n, "instance(\\d+)$"); if (m.Success && int.TryParse(m.Groups[1].Value, out int pid) && pids.Contains(pid)) return n; } return null; } private static string Unescape(string s) => s.Replace("\\\"", "\"").Replace("\\\\", "\\"); private static async Task TrackOf(string bus) { string md = await DBus("--print-reply", "--dest=" + bus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:Metadata"); if (md == null) return ""; Match t = Regex.Match(md, "\"xesam:title\"\\s*variant\\s+string\\s+\"((?:[^\"\\\\]|\\\\.)*)\""); Match a = Regex.Match(md, "\"xesam:artist\"\\s*variant\\s+array\\s*\\[\\s*string\\s+\"((?:[^\"\\\\]|\\\\.)*)\""); string title = t.Success ? Unescape(t.Groups[1].Value) : ""; string artist = a.Success ? Unescape(a.Groups[1].Value) : ""; string st = await DBus("--print-reply", "--dest=" + bus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:PlaybackStatus"); bool paused = st != null && !st.Contains("\"Playing\""); if (title.Length == 0) return ""; return (artist.Length > 0 ? artist + " - " : "") + title + (paused ? " (paused)" : ""); } private async Task Mpris(string method) { if (extBus == null) return; await DBus("--type=method_call", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player." + method); extNext = DateTime.UtcNow.AddMilliseconds(600); } private async Task MprisVolume(double d) { if (extBus == null) return; string v = await DBus("--print-reply", "--dest=" + extBus, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties.Get", "string:org.mpris.MediaPlayer2.Player", "string:Volume"); Match m = v == null ? Match.Empty : Regex.Match(v, "double\\s+([0-9.eE+-]+)"); double cur = m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double x) ? x : 0.5; double nv = Math.Clamp(cur + d, 0, 1); 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)); Message("Volume " + (int)Math.Round(nv * 100) + "%", false); } private void MusicTick() { if (Mac.On || OperatingSystem.IsWindows() || extScanning || DateTime.UtcNow < extNext) return; extNext = DateTime.UtcNow.AddSeconds(MusicVisible ? 1 : 3); extScanning = true; _ = Task.Run(async () => { var (found, app, pids) = ScanProcs(); string bus = found ? await FindBus(app, pids) : null; MprisState st = bus != null ? await StateOf(bus) : null; Avalonia.Threading.Dispatcher.UIThread.Post(() => { extScanning = false; bool was = extFound; extFound = found; extApp = app; extBus = bus; extTitle = st?.Line ?? ""; ApplyMpris(st); if (found && !was && !jamShown) { jamShown = true; Message("Jamming? Control your media here! (Music tab)", false); } if (!found) jamShown = false; RefreshMusic(); }); }); } } }