Skip to content

ReStreet: FIFA Street (2012) recompiled for Windows PC, with online play, a launcher with friends, chat and rooms. Bring your own game.

Add native Linux launcher

SamuelitoDaVila7fb866ce34fa
diff --git a/.github/workflows/linux-launcher.yml b/.github/workflows/linux-launcher.yml
new file mode 100644
index 0000000..4da77d6
--- /dev/null
+++ b/.github/workflows/linux-launcher.yml
@@ -0,0 +1,41 @@
+name: Build Linux launcher
+
+on:
+ workflow_dispatch:
+ push:
+ paths:
+ - "Launcher/FifaStreetLauncher.Linux/**"
+ - "Launcher/FifaStreetLauncher/ui/**"
+ - ".github/workflows/linux-launcher.yml"
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+
+ steps:
+ - name: Checkout project
+ uses: actions/checkout@v4
+
+ - name: Set up .NET 8
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: "8.0.x"
+
+ - name: Publish
+ run: |
+ dotnet publish Launcher/FifaStreetLauncher.Linux/FifaStreetLauncher.Linux.csproj -c Release --self-contained -o dist/Linux
+ rm -f dist/Linux/*.pdb
+ tar -C dist -czf ReStreet-Linux-launcher.tar.gz Linux
+ sha256sum ReStreet-Linux-launcher.tar.gz > ReStreet-Linux-launcher.tar.gz.sha256
+
+ - name: Upload
+ uses: actions/upload-artifact@v4
+ with:
+ name: ReStreet-Linux-launcher
+ path: |
+ ReStreet-Linux-launcher.tar.gz
+ ReStreet-Linux-launcher.tar.gz.sha256
diff --git a/Launcher/FifaStreetLauncher.Linux/Controls.cs b/Launcher/FifaStreetLauncher.Linux/Controls.cs
new file mode 100644
index 0000000..9324483
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/Controls.cs
@@ -0,0 +1,104 @@
+using System.Diagnostics;
+using System.Text.Json;
+
+namespace FifaStreetLauncher.Linux;
+
+// Controls page: play with the keyboard (and mouse) instead of a controller. The runtime's keyboard mode presents the
+// keys as an Xbox controller (cvars mnk_mode, mnk_mouse, mnk_sensitivity, keybind_*), so the game needs no change.
+// Saved in controls.json (shared with the Windows launcher); passed to the game as REX_* variables on PLAY.
+internal sealed partial class Launcher
+{
+ public sealed class ControlsSettings
+ {
+ public bool Keyboard { get; set; }
+ public bool MouseTricks { get; set; } = true; // the default layout is keyboard + mouse
+ public double MouseSensitivity { get; set; } = 1.0;
+ // Controller button (runtime cvar suffix, e.g. "a", "lstick_up") -> keys, "Space,Semicolon" style.
+ public Dictionary<string, string> Keys { get; set; } = new(DefaultKeys);
+ }
+
+ // Layouts made for FIFA Street (the game's own tips): LT held = Street Ball Control (and jockey), RT = sprint /
+ // panna, LB held = flair pass or shot, RB = juggle, R3 = stand on the ball, right stick = skill moves, Y = manual
+ // pass. The left hand always has WASD, Shift sprint, Space ball control, Q flair, E juggle; Enter / Backspace / Esc
+ // work in the menus.
+ // Keyboard + mouse: the mouse moves the right stick (skills) and its buttons pass / shoot / lob.
+ public static readonly IReadOnlyDictionary<string, string> MouseKeys = new Dictionary<string, string>
+ {
+ ["lstick_up"] = "W", ["lstick_down"] = "S", ["lstick_left"] = "A", ["lstick_right"] = "D", ["lstick_press"] = "C",
+ ["rstick_up"] = "Up", ["rstick_down"] = "Down", ["rstick_left"] = "Left", ["rstick_right"] = "Right", ["rstick_press"] = "F",
+ ["a"] = "LMB,Return", ["b"] = "RMB,Backspace", ["x"] = "MMB", ["y"] = "R",
+ ["left_trigger"] = "Space", ["right_trigger"] = "Shift", ["left_shoulder"] = "Q", ["right_shoulder"] = "E",
+ ["dpad_up"] = "1", ["dpad_down"] = "2", ["dpad_left"] = "3", ["dpad_right"] = "4",
+ ["start"] = "Escape", ["back"] = "Tab",
+ };
+ // Keyboard only: the right hand passes / shoots on J K L I and does skills on the arrows.
+ public static readonly IReadOnlyDictionary<string, string> KeyboardKeys = new Dictionary<string, string>(MouseKeys)
+ {
+ ["rstick_press"] = "O", ["a"] = "J,Return", ["b"] = "K,Backspace", ["x"] = "L", ["y"] = "I",
+ };
+ public static readonly IReadOnlyDictionary<string, string> DefaultKeys = MouseKeys;
+
+ private ControlsSettings? controls;
+ private string ControlsPath => Path.Combine(root, "controls.json");
+
+ private ControlsSettings InputControls()
+ {
+ if (controls != null) return controls;
+ try
+ {
+ if (File.Exists(ControlsPath)) controls = JsonSerializer.Deserialize<ControlsSettings>(File.ReadAllText(ControlsPath));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ Debug.WriteLine(ex.Message);
+ }
+ controls ??= new ControlsSettings();
+ // Buttons added in a later launcher keep their default key.
+ foreach (var (button, keys) in DefaultKeys) controls.Keys.TryAdd(button, keys);
+ return controls;
+ }
+
+ // From the page: the whole controls object. Only known buttons are kept; the page already refuses the runtime's
+ // own overlay keys and repeated keys.
+ private void SetControls(JsonElement value)
+ {
+ var current = InputControls();
+ if (value.TryGetProperty("keyboard", out var k) && k.ValueKind is JsonValueKind.True or JsonValueKind.False) current.Keyboard = k.GetBoolean();
+ if (value.TryGetProperty("mouseTricks", out var mt) && mt.ValueKind is JsonValueKind.True or JsonValueKind.False) current.MouseTricks = mt.GetBoolean();
+ if (value.TryGetProperty("sensitivity", out var s) && s.ValueKind == JsonValueKind.Number) current.MouseSensitivity = Math.Clamp(s.GetDouble(), 0.1, 5.0);
+ if (value.TryGetProperty("keys", out var keys) && keys.ValueKind == JsonValueKind.Object)
+ foreach (var p in keys.EnumerateObject())
+ if (DefaultKeys.ContainsKey(p.Name) && p.Value.ValueKind == JsonValueKind.String)
+ current.Keys[p.Name] = p.Value.GetString()!.Length <= 64 ? p.Value.GetString()! : DefaultKeys[p.Name];
+ if (value.TryGetProperty("preset", out var pr) && pr.ValueKind == JsonValueKind.String)
+ {
+ bool mouse = pr.GetString() == "mouse";
+ current.Keys = new(mouse ? MouseKeys : KeyboardKeys);
+ current.MouseTricks = mouse;
+ }
+ try
+ {
+ File.WriteAllText(ControlsPath, JsonSerializer.Serialize(current, new JsonSerializerOptions { WriteIndented = true }));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ SetStatus("Could not save the controls: " + ex.Message, false);
+ }
+ }
+
+ private object ControlsState()
+ {
+ var c = InputControls();
+ return new { keyboard = c.Keyboard, mouseTricks = c.MouseTricks, sensitivity = c.MouseSensitivity, keys = c.Keys };
+ }
+
+ private void ApplyControls(IDictionary<string, string?> env)
+ {
+ var c = InputControls();
+ env["REX_MNK_MODE"] = c.Keyboard ? "true" : "false";
+ env["REX_MNK_MOUSE"] = c.Keyboard && c.MouseTricks ? "true" : "false";
+ env["REX_MNK_SENSITIVITY"] = c.MouseSensitivity.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ foreach (var (button, keys) in c.Keys)
+ if (DefaultKeys.ContainsKey(button)) env["REX_KEYBIND_" + button.ToUpperInvariant()] = keys;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/Displays.cs b/Launcher/FifaStreetLauncher.Linux/Displays.cs
new file mode 100644
index 0000000..150ecd6
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/Displays.cs
@@ -0,0 +1,65 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace FifaStreetLauncher.Linux;
+
+// Screen sizes, refresh rates and monitors from xrandr (X11 and XWayland). Without it, the usual 16:9 sizes.
+internal static partial class Displays
+{
+ private static readonly string[] CommonSizes = { "3840x2160", "2560x1440", "1920x1080", "1600x900", "1366x768", "1280x720" };
+
+ [GeneratedRegex(@"^(\S+) connected( primary)?")]
+ private static partial Regex OutputLine();
+
+ [GeneratedRegex(@"^\s+(\d+x\d+)\s+(.*)$")]
+ private static partial Regex ModeLine();
+
+ public static (string[] Sizes, string[] Rates, string[] Monitors) Detect()
+ {
+ var sizes = new List<string>();
+ var rates = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
+ var monitors = new List<string>();
+ string current = "";
+ int currentRate = 0;
+ try
+ {
+ using var xrandr = Process.Start(new ProcessStartInfo("xrandr", "--current") { RedirectStandardOutput = true, UseShellExecute = false });
+ string text = xrandr!.StandardOutput.ReadToEnd();
+ xrandr.WaitForExit(3000);
+ bool first = true;
+ foreach (string line in text.Split('\n'))
+ {
+ var o = OutputLine().Match(line);
+ if (o.Success)
+ {
+ monitors.Add($"{monitors.Count}: {o.Groups[1].Value}{(o.Groups[2].Success ? " • Primary" : "")}");
+ first = monitors.Count == 1 || o.Groups[2].Success;
+ continue;
+ }
+ var m = ModeLine().Match(line);
+ if (!m.Success || !first) continue;
+ if (!sizes.Contains(m.Groups[1].Value)) sizes.Add(m.Groups[1].Value);
+ foreach (string r in m.Groups[2].Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (!double.TryParse(r.TrimEnd('*', '+'), NumberStyles.Float, CultureInfo.InvariantCulture, out double hz)) continue;
+ rates.Add((int)Math.Round(hz));
+ if (r.Contains('*')) { current = m.Groups[1].Value; currentRate = (int)Math.Round(hz); }
+ }
+ }
+ }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
+ {
+ Debug.WriteLine(ex.Message); // no xrandr
+ }
+ // The game wants 16:9-ish sizes it can scale; keep the screen's own size first.
+ var list = sizes.Where(s => s == current || CommonSizes.Contains(s)).ToList();
+ if (list.Count == 0) list.AddRange(CommonSizes);
+ if (current.Length > 0) { list.Remove(current); list.Insert(0, current); }
+ if (rates.Count == 0) foreach (int r in new[] { 144, 120, 60 }) rates.Add(r);
+ var rateList = rates.Select(r => r.ToString(CultureInfo.InvariantCulture)).ToList();
+ if (currentRate > 0) { rateList.Remove(currentRate.ToString(CultureInfo.InvariantCulture)); rateList.Insert(0, currentRate.ToString(CultureInfo.InvariantCulture)); }
+ if (monitors.Count == 0) monitors.Add("0: Primary");
+ return (list.ToArray(), rateList.ToArray(), monitors.ToArray());
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/FifaStreetLauncher.Linux.csproj b/Launcher/FifaStreetLauncher.Linux/FifaStreetLauncher.Linux.csproj
new file mode 100644
index 0000000..cbf87d7
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/FifaStreetLauncher.Linux.csproj
@@ -0,0 +1,21 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net8.0</TargetFramework>
+ <RuntimeIdentifier>linux-x64</RuntimeIdentifier>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <AssemblyName>restreet-launcher</AssemblyName>
+ <RootNamespace>FifaStreetLauncher.Linux</RootNamespace>
+ <Version>2.0.7</Version>
+ <InvariantGlobalization>true</InvariantGlobalization>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Photino.NET" Version="4.0.16" />
+ <!-- The same page as the Windows launcher: one ui folder for both. -->
+ <None Include="..\FifaStreetLauncher\ui\**" LinkBase="ui" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
+ <None Include="..\FifaStreetLauncher\cover.jpg" Link="restreet.jpg" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
+ </ItemGroup>
+
+</Project>
diff --git a/Launcher/FifaStreetLauncher.Linux/GameStart.cs b/Launcher/FifaStreetLauncher.Linux/GameStart.cs
new file mode 100644
index 0000000..19f5e05
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/GameStart.cs
@@ -0,0 +1,249 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Text.Json;
+
+namespace FifaStreetLauncher.Linux;
+
+// PLAY: the same files and REX_* / FIFASTREET_* variables as LauncherForm.LaunchGame, with the game started through
+// Proton. Paths the game reads are given as Wine paths (Z:\...).
+internal sealed partial class Launcher
+{
+ // The deck build is x86-64-v3 (AVX2/BMI2/FMA); older CPUs get Binaries/NoAVX2 (see DeckLaunch.cs).
+ private static readonly bool CpuHasX86_64V3 =
+ System.Runtime.Intrinsics.X86.Avx2.IsSupported && System.Runtime.Intrinsics.X86.Bmi2.IsSupported &&
+ System.Runtime.Intrinsics.X86.Fma.IsSupported && System.Runtime.Intrinsics.X86.Lzcnt.IsSupported;
+
+ public int PlayAndWait()
+ {
+ LaunchGame().Wait();
+ return statusOk ? 0 : 1;
+ }
+
+ private async Task LaunchGame()
+ {
+ if (gameRunning) return;
+ gameRunning = true;
+ try
+ {
+ ProcessStartInfo startInfo;
+ lock (sync) startInfo = BuildStartInfo();
+ SetStatus("Starting ReStreet...", true);
+ using var process = Process.Start(startInfo);
+ if (process == null)
+ {
+ SetStatus("Could not start the game", false);
+ return;
+ }
+ gameProcess = process;
+ SetStatus("Running through Proton", true);
+ await process.WaitForExitAsync();
+ SetStatus(ReadyText(), true);
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception)
+ {
+ SetStatus("Launch failed: " + ex.Message, false);
+ }
+ finally
+ {
+ gameProcess = null;
+ gameRunning = false;
+ PushState(true);
+ }
+ }
+
+ private ProcessStartInfo BuildStartInfo()
+ {
+ string exe = Path.Combine(binaries, "fifastreet.exe");
+ if (!File.Exists(exe)) throw new InvalidOperationException("fifastreet.exe was not found.");
+ if (!File.Exists(Path.Combine(gameRoot, "default.xex"))) throw new InvalidOperationException("The game folder does not contain default.xex.");
+
+ string graphicsApi = fields["api"].Index == 1 ? "Vulkan" : "D3D12";
+ string backend = Path.Combine(binaries, "Backends", graphicsApi);
+ foreach (string dll in new[] { "rexruntime.dll", "rexgpu-xenos.dll" })
+ {
+ if (!File.Exists(Path.Combine(backend, dll))) throw new InvalidOperationException($"The {graphicsApi} graphics backend is missing ({backend}).");
+ File.Copy(Path.Combine(backend, dll), Path.Combine(binaries, dll), true);
+ }
+
+ var size = fields["resolution"].Text.Split('x');
+ if (size.Length != 2 || !int.TryParse(size[0], out int width) || !int.TryParse(size[1], out int height))
+ throw new InvalidOperationException("Select a valid resolution.");
+ string refresh = fields["refresh"].Text;
+ bool fullscreen = fields["displayMode"].Index == 0;
+ int monitor = Math.Max(0, fields["monitor"].Index);
+ bool vsync = toggles["vsync"].On;
+ string postEffect = fields["post"].Index switch { 1 => "fxaa", 2 => "fxaa_extreme", _ => "none" };
+ int internalScale = Math.Max(1, fields["internal"].Index + 1);
+ string readbackResolve = ReadbackResolveModes[Math.Clamp(fields["readback"].Index, 0, ReadbackResolveModes.Length - 1)];
+
+ string logsDir = Path.Combine(binaries, "Logs");
+ Directory.CreateDirectory(logsDir);
+ string logFile = Path.Combine(logsDir, "fifastreet.log");
+
+ var startInfo = Proton.StartInfo(exe, prefix, protons.FirstOrDefault());
+ var env = startInfo.Environment;
+ string wineGameRoot = InstallFolder.WindowsPath(gameRoot);
+ // ReXGlue resolves each setting in this order, lowest priority first:
+ // built-in default -> fifastreet.toml -> REX_* environment -> command line.
+ env["REX_GAME_DATA_ROOT"] = wineGameRoot;
+ if (deck)
+ {
+ UseCpuBuild(graphicsApi);
+ // The deck port's own start-up switches (native renderer, its shader folders...), as its launcher sets them.
+ foreach (string line in File.ReadAllLines(Path.Combine(binaries, "ajustes-del-port.txt")))
+ {
+ int eq = line.IndexOf('=');
+ if (eq <= 0 || line.StartsWith('?') || line.StartsWith('#')) continue;
+ env[line[..eq].Trim()] = line[(eq + 1)..].Trim();
+ }
+ env["REX_GPU_BACKEND"] = graphicsApi == "Vulkan" ? "vulkan" : "d3d12";
+ if (graphicsApi == "Vulkan") env["REX_VULKAN_DEVICE"] = "-1";
+ SaveDeckToml();
+ ApplyGameLanguage(env);
+ env["REX_MONITOR"] = (monitor + 1).ToString(CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ env["REX_VIDEO_MODE_WIDTH"] = width.ToString(CultureInfo.InvariantCulture);
+ env["REX_VIDEO_MODE_HEIGHT"] = height.ToString(CultureInfo.InvariantCulture);
+ env["REX_DRAW_RESOLUTION_SCALE_X"] = internalScale.ToString(CultureInfo.InvariantCulture);
+ env["REX_DRAW_RESOLUTION_SCALE_Y"] = internalScale.ToString(CultureInfo.InvariantCulture);
+ env["REX_WINDOW_WIDTH"] = width.ToString(CultureInfo.InvariantCulture);
+ env["REX_WINDOW_HEIGHT"] = height.ToString(CultureInfo.InvariantCulture);
+ env["REX_VIDEO_MODE_REFRESH_RATE"] = refresh;
+ env["REX_FRAME_LIMITER_MIN_HZ"] = vsync ? "auto" : "1000";
+ env.Remove("REX_READBACK_SOME_SYNC_ADDRS");
+ env["REX_READBACK_SOME_SYNC_BELOW"] = "0";
+ ApplyGameLanguage(env);
+ env["REX_GUEST_VBLANK_UNLOCKED"] = "true";
+ env["REX_FULLSCREEN"] = fullscreen ? "true" : "false";
+ env["REX_MONITOR"] = (monitor + 1).ToString(CultureInfo.InvariantCulture);
+ env["REX_VSYNC"] = "false";
+ env["REX_TRUE_VSYNC"] = vsync ? "1" : "0";
+ env["REX_NATIVE_2X_MSAA"] = toggles["msaa"].On ? "true" : "false";
+ env["REX_SWAP_POST_EFFECT"] = postEffect;
+ if (graphicsApi == "D3D12")
+ {
+ env["REX_D3D12_ALLOW_VARIABLE_REFRESH_RATE_AND_TEARING"] = !vsync && toggles["vrr"].On ? "true" : "false";
+ env["REX_RENDER_TARGET_PATH_D3D12"] = "";
+ }
+ else
+ {
+ env["REX_VULKAN_DEVICE"] = "-1";
+ env["REX_RENDER_TARGET_PATH_VULKAN"] = "fbo";
+ env["REX_DRAW_RESOLUTION_SCALED_TEXTURE_OFFSETS"] = "false";
+ env["REX_DEPTH_FLOAT24_CONVERT_IN_PIXEL_SHADER"] = "true";
+ env["REX_GAMMA_RENDER_TARGET_AS_UNORM16"] = "false";
+ env["REX_SNORM16_RENDER_TARGET_FULL_RANGE"] = "false";
+ env["REX_VULKAN_DYNAMIC_RENDERING"] = "false";
+ env["REX_HALF_PIXEL_OFFSET"] = "false";
+ env["REX_ANISOTROPIC_OVERRIDE"] = "-1";
+ env["REX_DIRECT_HOST_RESOLVE"] = "false";
+ env["REX_VULKAN_ALLOW_PRESENT_MODE_IMMEDIATE"] = vsync ? "false" : "true";
+ env["REX_VULKAN_ALLOW_PRESENT_MODE_MAILBOX"] = vsync ? "true" : "false";
+ env["REX_VULKAN_ALLOW_PRESENT_MODE_FIFO_RELAXED"] = vsync ? "false" : "true";
+ }
+ env["REX_READBACK_RESOLVE"] = readbackResolve;
+ env["REX_D3D12_READBACK_SHORT_WAIT"] = "true";
+ env["REX_D3D12_READBACK_SPIN_US"] = "500";
+ env["REX_VULKAN_READBACK_SHORT_WAIT"] = "true";
+ env["REX_VULKAN_READBACK_SPIN_US"] = "500";
+ bool memexport = toggles["memexport"].On;
+ env["REX_READBACK_MEMEXPORT"] = memexport ? "true" : "false";
+ env[graphicsApi == "Vulkan" ? "REX_VULKAN_READBACK_MEMEXPORT" : "REX_D3D12_READBACK_MEMEXPORT"] = memexport ? "true" : "false";
+ env["REX_READBACK_MEMEXPORT_FAST"] = memexport && toggles["memexportFast"].On ? "true" : "false";
+ env["REX_CLEAR_MEMORY_PAGE_STATE"] = toggles["pageState"].On ? "true" : "false";
+ env["REX_OCCLUSION_QUERY_ENABLE"] = toggles["occlusion"].On ? "true" : "false";
+ env["REX_ASYNC_SHADER_COMPILATION"] = toggles["asyncShaders"].On ? "true" : "false";
+ }
+ ApplyControls(env);
+
+ env["REX_LOG_VERBOSE"] = "false";
+ env["REX_LOG_LEVEL"] = "info";
+ env["REX_LOG_FRAME_STATS"] = toggles["frameStats"].On ? "true" : "false";
+ env["REX_BIND_DEBUG_OVERLAY"] = "Home";
+ env["REX_LOG_FILE"] = InstallFolder.WindowsPath(logFile);
+
+ // Online play: the server and the player name come from the online patch.
+ var online = LoadOnlineConfig();
+ if (online != null && toggles["onlineMode"].On)
+ {
+ env["FIFASTREET_SERVER"] = online.Value.Server;
+ env["FIFASTREET_PLAYER_NAME"] = online.Value.Name;
+ env["FIFASTREET_PLAYER_KEY"] = online.Value.Key;
+ env["FIFASTREET_ONLINE_EXPERIMENT"] = "1";
+ env["FIFASTREET_ONLINE_ENDPOINT_PROBE"] = "1";
+ env["FIFASTREET_NET_DIAG"] = "";
+ if (!toggles["frameStats"].On) env["REX_LOG_LEVEL"] = "warn";
+ }
+ startInfo.ArgumentList.Add($"--game_data_root={wineGameRoot}");
+
+ SaveSettings();
+ try
+ {
+ File.WriteAllText(Path.Combine(logsDir, "launcher_settings.txt"),
+ $"Launcher=Linux{Environment.NewLine}Proton={protons.FirstOrDefault() ?? "UMU-Proton (default)"}{Environment.NewLine}" +
+ $"Prefix={prefix}{Environment.NewLine}Resolution={width}x{height}{Environment.NewLine}" +
+ $"InternalResolution={1280 * internalScale}x{720 * internalScale} ({internalScale}x){Environment.NewLine}" +
+ $"MonitorRefreshRate={refresh}{Environment.NewLine}GraphicsApi={graphicsApi}{Environment.NewLine}" +
+ $"Fullscreen={fullscreen}{Environment.NewLine}Monitor={monitor}{Environment.NewLine}VSync={vsync}{Environment.NewLine}" +
+ $"MSAA={toggles["msaa"].On}{Environment.NewLine}PostEffect={postEffect}{Environment.NewLine}Deck={deck}{Environment.NewLine}");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ return startInfo;
+ }
+
+ private void ApplyGameLanguage(IDictionary<string, string?> env)
+ {
+ int id = GameLanguageIds[Math.Max(0, fields["language"].Index)];
+ env["REX_USER_LANGUAGE"] = (id == PtBrLanguageId ? 1 : id).ToString(CultureInfo.InvariantCulture);
+ if (id == PtBrLanguageId) env["FIFASTREET_GAME_LANGUAGE"] = "pt-BR";
+ else env.Remove("FIFASTREET_GAME_LANGUAGE");
+ }
+
+ private void UseCpuBuild(string graphicsApi)
+ {
+ string set = Path.Combine(binaries, CpuHasX86_64V3 ? "AVX2" : "NoAVX2");
+ if (!Directory.Exists(set)) return;
+ foreach (string name in new[] { "fifastreet.exe", "fifastreet_fifadllzf_xex.dll", "fifastreet_footballcompengzf_xex.dll" })
+ CopyIfDifferent(Path.Combine(set, name), Path.Combine(binaries, name));
+ string backend = Path.Combine(set, "Backends", graphicsApi);
+ if (!CpuHasX86_64V3 && Directory.Exists(backend))
+ foreach (string dll in Directory.GetFiles(backend, "*.dll"))
+ CopyIfDifferent(dll, Path.Combine(binaries, Path.GetFileName(dll)));
+ }
+
+ private static void CopyIfDifferent(string source, string target)
+ {
+ if (!File.Exists(source)) return;
+ var s = new FileInfo(source);
+ var t = new FileInfo(target);
+ if (t.Exists && t.Length == s.Length && t.LastWriteTimeUtc == s.LastWriteTimeUtc) return;
+ File.Copy(source, target, true);
+ File.SetLastWriteTimeUtc(target, s.LastWriteTimeUtc); // on Linux File.Copy does not keep it
+ }
+
+ // ---------- Launcher rooms (RoomLaunch.cs): a full room starts the game by itself, once per room ----------
+
+ private long roomLaunchedFor;
+
+ private void OnRoomState(JsonElement? room)
+ {
+ if (room is not { ValueKind: JsonValueKind.Object } r) return;
+ long id = r.TryGetProperty("id", out var idv) && idv.ValueKind == JsonValueKind.Number ? idv.GetInt64() : 0;
+ int players = r.TryGetProperty("players", out var pv) && pv.ValueKind == JsonValueKind.Array ? pv.GetArrayLength() : 0;
+ int seats = r.TryGetProperty("seats", out var sv) && sv.ValueKind == JsonValueKind.Number ? sv.GetInt32() : 2;
+ if (players < seats || Interlocked.Exchange(ref roomLaunchedFor, id) == id || !toggles["onlineMode"].On) return;
+ _ = Task.Run(async () =>
+ {
+ // A game already open sits on a menu the room driver cannot walk from: close it and start it again.
+ if (gameRunning && gameProcess is { } running)
+ {
+ try { running.Kill(entireProcessTree: true); }
+ catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception) { Debug.WriteLine(ex.Message); }
+ for (int i = 0; i < 100 && gameRunning; ++i) await Task.Delay(100);
+ }
+ if (!gameRunning) await LaunchGame();
+ });
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/Launcher.cs b/Launcher/FifaStreetLauncher.Linux/Launcher.cs
new file mode 100644
index 0000000..7ff582f
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/Launcher.cs
@@ -0,0 +1,531 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+
+namespace FifaStreetLauncher.Linux;
+
+// The launcher state the page shows and changes: the same fields, toggles and commands as the Windows launcher
+// (GlassUi.cs), kept as plain lists instead of WinForms controls. Settings live in linux-settings.json; the graphics
+// options also go to fifastreet.toml, which the in-game menu (F5 / L3+R3) shares.
+internal sealed partial class Launcher
+{
+ private sealed class Field
+ {
+ public string[] Items = Array.Empty<string>();
+ public int Index;
+ public bool Enabled = true;
+ public string Text => Index >= 0 && Index < Items.Length ? Items[Index] : "";
+ }
+
+ private sealed class Toggle
+ {
+ public bool On;
+ public bool Enabled = true;
+ }
+
+ // Regions the online patch offers (keep in sync with GlassUi.cs).
+ private static readonly (string Name, string Address)[] Regions =
+ {
+ ("Europe", "57.129.180.15"), ("South America", "216.238.113.7"),
+ };
+
+ private static readonly string[] ProfileNames = { "Balanced (default)", "Quality (strong PCs)", "Performance (weak PCs)", "Custom" };
+ private static readonly string[] ReadbackResolveModes = { "full", "some", "fast", "none" };
+ private const int PtBrLanguageId = 1001;
+ private static readonly int[] GameLanguageIds = { 1, 5, 4, 3, 6, PtBrLanguageId };
+
+ // (label, present_effect, modo_fsr): as DeckLaunch.cs.
+ private static readonly (string Label, string Effect, string Mode)[] DeckScaling =
+ {
+ ("Bilinear", "bilinear", ""), ("FSR 1", "fsr", ""), ("FSR 1 Quality", "fsr", "calidad"),
+ ("FSR 1 Balanced", "fsr", "equilibrado"), ("FSR 1 Performance", "fsr", "rendimiento"),
+ ("FSR 1 Ultra Performance", "fsr", "ultra_rendimiento"),
+ };
+ private static readonly (string Label, double Hz)[] DeckFpsLimits =
+ {
+ ("Screen refresh rate", -1), ("No limit", 0), ("30", 30), ("60", 60), ("90", 90), ("120", 120), ("144", 144),
+ ("165", 165), ("240", 240),
+ };
+ private static readonly (string Label, int Value)[] DeckAniso =
+ {
+ ("Game default", -1), ("Off", 0), ("1x", 1), ("2x", 2), ("4x", 3), ("8x", 4), ("16x", 5),
+ };
+ private static readonly (string Label, string Value)[] DeckOcclusion = { ("Off", ""), ("SSAO", "ssao"), ("HBAO", "hbao"), ("GTAO", "gtao") };
+
+ private readonly object sync = new();
+ private readonly string root;
+ private readonly string binaries;
+ private readonly string gameRoot;
+ private readonly bool deck;
+ private readonly Dictionary<string, Field> fields = new();
+ private readonly Dictionary<string, Toggle> toggles = new();
+ private readonly List<string> protons;
+ private string prefix;
+ private bool perfShare;
+ private string status = "";
+ private bool statusOk = true;
+ private volatile bool gameRunning;
+ private Process? gameProcess;
+ private string lastState = "";
+ private volatile bool closing;
+
+ public PageServer? Page { get; set; }
+ public Action? CloseWindow { get; set; }
+
+ private string SettingsPath => Path.Combine(root, "linux-settings.json");
+ private string TomlPath => Path.Combine(binaries, "fifastreet.toml");
+
+ public Launcher(string root)
+ {
+ this.root = root;
+ binaries = Path.Combine(root, "Binaries");
+ // 1.5.5 layout: Binaries/ and Game/; older installs had Game/ + GameData/.
+ gameRoot = Path.Combine(root, Directory.Exists(Path.Combine(root, "GameData")) ? "GameData" : "Game");
+ deck = File.Exists(Path.Combine(binaries, "ajustes-del-port.txt"));
+ protons = Proton.Installed();
+ prefix = Proton.DefaultPrefix(root);
+
+ var (sizes, rates, monitors) = Displays.Detect();
+ Add("profile", ProfileNames, 0);
+ Add("language", new[] { "English", "Español", "Français", "Deutsch", "Italiano", "Português (Brasil)" }, 0);
+ Add("resolution", sizes, 0);
+ Add("refresh", rates, 0);
+ Add("displayMode", new[] { "Fullscreen", "Windowed" }, 0);
+ Add("monitor", monitors, 0);
+ Add("api", new[] { "Direct3D 12", "Vulkan" }, 0);
+ // Proton picks the GPU (DXVK_FILTER_DEVICE_NAME / MESA_VK_DEVICE_SELECT can steer it); the list shows that.
+ Add("gpu", new[] { "Automatic" }, 0).Enabled = false;
+ Add("post", new[] { "None", "FXAA", "FXAA Extreme" }, 1);
+ Add("internal", new[] { "1x - Native (1280 x 720)", "2x - 2560 x 1440", "3x - 3840 x 2160", "4x - 5120 x 2880" }, 0);
+ Add("readback", new[] { "Full (compatible)", "Some (recommended)", "Fast (more FPS, may glitch)", "None (experimental)" }, 1);
+ Add("scaling", deck ? DeckScaling.Select(s => s.Label).ToArray() : Array.Empty<string>(), 1);
+ Add("aspect", deck ? new[] { "Match screen", "16:9 (console)" } : Array.Empty<string>(), 0);
+ Add("fpsLimit", deck ? DeckFpsLimits.Select(s => s.Label).ToArray() : Array.Empty<string>(), 0);
+ Add("aniso", deck ? DeckAniso.Select(s => s.Label).ToArray() : Array.Empty<string>(), 0);
+ Add("occlusion", deck ? DeckOcclusion.Select(s => s.Label).ToArray() : Array.Empty<string>(), 0);
+ foreach (var (id, on) in new[] { ("vsync", true), ("vrr", false), ("msaa", false), ("memexport", true), ("memexportFast", true),
+ ("pageState", false), ("occlusion", false), ("asyncShaders", false), ("frameStats", false), ("onlineMode", true) })
+ toggles[id] = new Toggle { On = on };
+
+ LoadSettings();
+ if (deck) LoadDeckToml();
+ UpdateEnabled();
+ status = ReadyText();
+ }
+
+ private Field Add(string id, string[] items, int index)
+ {
+ var f = new Field { Items = items, Index = items.Length == 0 ? -1 : Math.Min(index, items.Length - 1), Enabled = items.Length > 0 };
+ fields[id] = f;
+ return f;
+ }
+
+ // ---------- Settings ----------
+
+ private void LoadSettings()
+ {
+ try
+ {
+ if (!File.Exists(SettingsPath)) return;
+ var node = JsonNode.Parse(File.ReadAllText(SettingsPath));
+ if (node?["fields"] is JsonObject fo)
+ foreach (var (id, value) in fo)
+ if (fields.TryGetValue(id, out var f) && Array.IndexOf(f.Items, value?.GetValue<string>()) is int i and >= 0) f.Index = i;
+ if (node?["toggles"] is JsonObject to)
+ foreach (var (id, value) in to)
+ if (toggles.TryGetValue(id, out var t) && value != null) t.On = value.GetValue<bool>();
+ if (node?["prefix"]?.GetValue<string>() is { Length: > 0 } p) prefix = p;
+ if (node?["proton"]?.GetValue<string>() is { Length: > 0 } pr && Directory.Exists(pr))
+ {
+ protons.Remove(pr);
+ protons.Insert(0, pr);
+ }
+ perfShare = node?["perfShare"]?.GetValue<bool>() == true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException or FormatException)
+ {
+ Debug.WriteLine(ex.Message);
+ }
+ }
+
+ private void SaveSettings()
+ {
+ var node = new JsonObject
+ {
+ ["fields"] = new JsonObject(fields.Select(f => KeyValuePair.Create(f.Key, (JsonNode?)f.Value.Text))),
+ ["toggles"] = new JsonObject(toggles.Select(t => KeyValuePair.Create(t.Key, (JsonNode?)t.Value.On))),
+ ["prefix"] = prefix,
+ ["proton"] = protons.FirstOrDefault() ?? "",
+ ["perfShare"] = perfShare,
+ };
+ try { File.WriteAllText(SettingsPath, node.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ }
+
+ // Same rules as the Windows launcher: VRR only with D3D12 and VSync off; the fast memexport needs memexport.
+ private void UpdateEnabled()
+ {
+ bool d3d12 = fields["api"].Index == 0;
+ toggles["vrr"].Enabled = d3d12 && !toggles["vsync"].On && !deck;
+ toggles["memexportFast"].Enabled = toggles["memexport"].On;
+ foreach (string id in new[] { "readback" }) fields[id].Enabled = !deck;
+ foreach (string id in new[] { "memexport", "memexportFast", "pageState", "occlusion", "asyncShaders" }) if (deck) toggles[id].Enabled = false;
+ }
+
+ private void ApplyProfile()
+ {
+ (int post, int scale, bool msaa, int readback, bool occlusion)? values = fields["profile"].Index switch
+ {
+ 0 => (1, 0, false, 1, false), // Balanced: the shipped defaults (Some readback)
+ 1 => (2, 1, true, 1, false), // Quality: 2x internal resolution, FXAA extreme, MSAA (Some readback)
+ 2 => (0, 0, false, 2, false), // Performance: native resolution, no post, faster readback
+ _ => null
+ };
+ if (values == null) return;
+ fields["post"].Index = values.Value.post;
+ fields["internal"].Index = values.Value.scale;
+ toggles["msaa"].On = values.Value.msaa;
+ fields["readback"].Index = values.Value.readback;
+ toggles["occlusion"].On = values.Value.occlusion;
+ }
+
+ // ---------- fifastreet.toml (the 2.0 "deck" base), as DeckLaunch.cs ----------
+
+ private void LoadDeckToml()
+ {
+ var toml = ReadToml(TomlPath);
+ string Str(string key) => toml.TryGetValue(key, out var v) ? v.Trim('"') : "";
+ bool? Bool(string key) => toml.TryGetValue(key, out var v) ? v == "true" : null;
+ double? Num(string key) => toml.TryGetValue(key, out var v) && double.TryParse(v.Trim('"'), NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : null;
+
+ string effect = Str("present_effect"), mode = Str("modo_fsr");
+ int scale = Array.FindIndex(DeckScaling, s => s.Effect == effect && (effect != "fsr" || s.Mode == mode));
+ if (scale >= 0) fields["scaling"].Index = scale;
+ if (Bool("proporcion_de_la_pantalla") is { } aspect) fields["aspect"].Index = aspect ? 0 : 1;
+ if (Num("ritmo_contra_pantalla_hz") is { } hz) { int i = Array.FindIndex(DeckFpsLimits, f => Math.Abs(f.Hz - hz) < 0.5); if (i >= 0) fields["fpsLimit"].Index = i; }
+ if (Num("anisotropic_override") is { } an) { int i = Array.FindIndex(DeckAniso, a => a.Value == (int)an); if (i >= 0) fields["aniso"].Index = i; }
+ string ao = Str("modo_oclusion"); { int i = Array.FindIndex(DeckOcclusion, o => o.Value == ao); if (i >= 0) fields["occlusion"].Index = i; }
+ if (Bool("sincronia_vertical") is { } vs) toggles["vsync"].On = vs;
+ if (Bool("multimuestreo_del_juego") is { } ms) toggles["msaa"].On = ms;
+ if (Bool("fullscreen") is { } fs) fields["displayMode"].Index = fs ? 0 : 1;
+ int post = Str("swap_post_effect") switch { "none" => 0, "fxaa" => 1, "fxaa_extreme" => 2, _ => -1 };
+ if (post >= 0) fields["post"].Index = post;
+ if (int.TryParse(Str("resolucion_interna"), out int ri) && ri >= 1 && ri <= fields["internal"].Items.Length) fields["internal"].Index = ri - 1;
+ if (Num("window_width") is { } ww && Num("window_height") is { } wh)
+ {
+ int i = Array.IndexOf(fields["resolution"].Items, $"{(int)ww}x{(int)wh}");
+ if (i >= 0) fields["resolution"].Index = i;
+ }
+ }
+
+ private void SaveDeckToml()
+ {
+ if (!deck) return;
+ var scaling = DeckScaling[Math.Max(0, fields["scaling"].Index)];
+ var values = new Dictionary<string, string>
+ {
+ ["fullscreen"] = fields["displayMode"].Index == 0 ? "true" : "false",
+ ["gpu_backend"] = fields["api"].Index == 1 ? "\"vulkan\"" : "\"d3d12\"",
+ ["resolucion_interna"] = "\"" + Math.Max(1, fields["internal"].Index + 1).ToString(CultureInfo.InvariantCulture) + "\"",
+ ["present_effect"] = "\"" + scaling.Effect + "\"",
+ ["modo_fsr"] = "\"" + scaling.Mode + "\"",
+ ["proporcion_de_la_pantalla"] = fields["aspect"].Index == 1 ? "false" : "true",
+ ["ritmo_contra_pantalla_hz"] = DeckFpsLimits[Math.Max(0, fields["fpsLimit"].Index)].Hz.ToString("0.000000", CultureInfo.InvariantCulture),
+ ["sincronia_vertical"] = toggles["vsync"].On ? "true" : "false",
+ ["anisotropic_override"] = DeckAniso[Math.Max(0, fields["aniso"].Index)].Value.ToString(CultureInfo.InvariantCulture),
+ ["swap_post_effect"] = "\"" + (fields["post"].Index switch { 1 => "fxaa", 2 => "fxaa_extreme", _ => "none" }) + "\"",
+ ["multimuestreo_del_juego"] = toggles["msaa"].On ? "true" : "false",
+ ["modo_oclusion"] = "\"" + DeckOcclusion[Math.Max(0, fields["occlusion"].Index)].Value + "\"",
+ };
+ var size = fields["resolution"].Text.Split('x');
+ if (size.Length == 2 && int.TryParse(size[0], out int w) && int.TryParse(size[1], out int h) && w > 0 && h > 0)
+ {
+ values["window_width"] = w.ToString(CultureInfo.InvariantCulture);
+ values["window_height"] = h.ToString(CultureInfo.InvariantCulture);
+ }
+ try { WriteToml(TomlPath, values); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ }
+
+ private static Dictionary<string, string> ReadToml(string path)
+ {
+ var map = new Dictionary<string, string>(StringComparer.Ordinal);
+ try
+ {
+ if (!File.Exists(path)) return map;
+ foreach (string line in File.ReadAllLines(path))
+ {
+ int eq = line.IndexOf('=');
+ if (eq <= 0 || line.TrimStart().StartsWith('#') || line.TrimStart().StartsWith('[')) continue;
+ map[line[..eq].Trim()] = line[(eq + 1)..].Trim();
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ return map;
+ }
+
+ private static void WriteToml(string path, IReadOnlyDictionary<string, string> values)
+ {
+ var lines = File.Exists(path) ? File.ReadAllLines(path).ToList() : new List<string> { "# Auto-generated cvar configuration" };
+ var left = new HashSet<string>(values.Keys);
+ for (int i = 0; i < lines.Count; i++)
+ {
+ int eq = lines[i].IndexOf('=');
+ if (eq <= 0 || lines[i].TrimStart().StartsWith('#')) continue;
+ string key = lines[i][..eq].Trim();
+ if (!values.TryGetValue(key, out var v)) continue;
+ lines[i] = key + " = " + v;
+ left.Remove(key);
+ }
+ // New keys go before the first [section], where the runtime keeps the plain ones.
+ int at = lines.FindIndex(l => l.TrimStart().StartsWith('['));
+ if (at < 0) at = lines.Count;
+ lines.InsertRange(at, left.Select(k => k + " = " + values[k]));
+ File.WriteAllLines(path, lines, new UTF8Encoding(false));
+ }
+
+ // ---------- Online ----------
+
+ internal (string Server, string Name, string Key)? LoadOnlineConfig()
+ {
+ try
+ {
+ string path = Path.Combine(root, "online.json");
+ if (!File.Exists(path)) return null;
+ using var doc = JsonDocument.Parse(File.ReadAllText(path));
+ string? server = doc.RootElement.TryGetProperty("server", out var s) ? s.GetString() : null;
+ string? name = doc.RootElement.TryGetProperty("name", out var n) ? n.GetString() : null;
+ string? key = doc.RootElement.TryGetProperty("key", out var k) ? k.GetString() : null;
+ return string.IsNullOrWhiteSpace(server) || string.IsNullOrWhiteSpace(name) ? null : (server.Trim(), name.Trim(), (key ?? "").Trim());
+ }
+ catch (Exception error) when (error is IOException or JsonException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
+ private string ReadyText()
+ {
+ if (Proton.UmuRun() == null) return "umu-run is missing: install umu-launcher to play";
+ var online = LoadOnlineConfig();
+ if (online != null && !toggles["onlineMode"].On) return "Ready to play offline (online is off)";
+ return online == null ? "Online is not set up. Run the online patch again" : "Ready to play online as " + online.Value.Name;
+ }
+
+ // Moves this install to another region: the same name and key, another server (online.json in both places).
+ private void SwitchServer(string address)
+ {
+ if (gameRunning || !Regions.Any(r => r.Address == address)) return;
+ foreach (string path in new[] { Path.Combine(root, "online.json"), Path.Combine(binaries, "online.json") })
+ {
+ try
+ {
+ if (!File.Exists(path)) continue;
+ var node = JsonNode.Parse(File.ReadAllText(path))!;
+ node["server"] = address;
+ File.WriteAllText(path, node.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ SetStatus("Could not change the server: " + ex.Message, false);
+ }
+ }
+ }
+
+ private readonly Dictionary<string, (int Ping, int Online)> serverInfo = new();
+
+ private async Task PollServers()
+ {
+ using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
+ while (!closing)
+ {
+ foreach (var (_, address) in Regions)
+ {
+ int ping = -1, online = -1;
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ using (var tcp = new TcpClient()) { await tcp.ConnectAsync(address, 29812).WaitAsync(TimeSpan.FromSeconds(3)); }
+ ping = (int)watch.ElapsedMilliseconds;
+ using var doc = JsonDocument.Parse(await http.GetStringAsync($"http://{address}:29812/v1/online"));
+ online = doc.RootElement.GetProperty("online").GetInt32();
+ }
+ catch (Exception) { /* offline or unreachable: shown as offline */ }
+ lock (serverInfo) serverInfo[address] = (ping, online);
+ }
+ await Task.Delay(15000);
+ }
+ }
+
+ // ---------- Page ----------
+
+ public void StartServices()
+ {
+ _ = Task.Run(PollServers);
+ _ = Task.Run(async () =>
+ {
+ while (!closing)
+ {
+ PushState(false);
+ await Task.Delay(1000);
+ }
+ });
+ }
+
+ private void SetStatus(string text, bool ok)
+ {
+ lock (sync) { status = text; statusOk = ok; }
+ PushState(false);
+ }
+
+ private void Post(object message) => Page?.Send(JsonSerializer.Serialize(message));
+
+ public void OnMessage(string json)
+ {
+ JsonElement m;
+ try { using var doc = JsonDocument.Parse(json); m = doc.RootElement.Clone(); }
+ catch (JsonException) { return; }
+ string cmd = m.TryGetProperty("cmd", out var c) ? c.GetString() ?? "" : "";
+ string id = m.TryGetProperty("id", out var i) ? i.GetString() ?? "" : "";
+ switch (cmd)
+ {
+ case "set":
+ lock (sync)
+ {
+ if (fields.TryGetValue(id, out var f) && f.Enabled && m.TryGetProperty("index", out var ix) && ix.TryGetInt32(out int index)
+ && index >= 0 && index < f.Items.Length)
+ {
+ f.Index = index;
+ if (id == "profile") ApplyProfile();
+ else if (id is "post" or "internal" or "readback") fields["profile"].Index = ProfileNames.Length - 1;
+ }
+ }
+ break;
+ case "toggle":
+ lock (sync)
+ {
+ if (toggles.TryGetValue(id, out var t) && t.Enabled && m.TryGetProperty("value", out var v) && v.ValueKind is JsonValueKind.True or JsonValueKind.False)
+ {
+ t.On = v.GetBoolean();
+ if (id is "msaa" or "occlusion") fields["profile"].Index = ProfileNames.Length - 1;
+ }
+ }
+ break;
+ case "play": if (!gameRunning) _ = LaunchGame(); break;
+ case "close": closing = true; CloseWindow?.Invoke(); return;
+ case "drag" or "minimize" or "maximize": return; // the native window has its own title bar
+ case "logs": Open(Path.Combine(binaries, "Logs")); break;
+ case "folder": Open(root); break;
+ case "shortcut": CreateDesktopEntry(); break;
+ case "perfShare": if (m.TryGetProperty("value", out var ps) && ps.ValueKind is JsonValueKind.True or JsonValueKind.False) { perfShare = ps.GetBoolean(); SaveSettings(); } return;
+ case "controls": if (m.TryGetProperty("value", out var cv) && cv.ValueKind == JsonValueKind.Object) SetControls(cv); break;
+ case "server": if (m.TryGetProperty("address", out var a)) SwitchServer(a.GetString() ?? ""); break;
+ case "social" or "chatSend" or "chatAction" or "friend" or "room":
+ _ = SocialAsync(cmd, m);
+ return;
+ case "updateGo":
+ Post(new { type = "updateError", message = "On Linux, update with the new ReStreet setup (see the README)." });
+ return;
+ }
+ if (cmd is "set" or "toggle")
+ {
+ lock (sync)
+ {
+ UpdateEnabled();
+ status = ReadyText();
+ SaveSettings();
+ SaveDeckToml();
+ }
+ }
+ PushState(true);
+ }
+
+ private void PushState(bool force)
+ {
+ if (Page == null) return;
+ string json;
+ lock (sync)
+ {
+ var fieldState = fields.ToDictionary(f => f.Key, f => (object)new { items = f.Value.Items, index = f.Value.Index, enabled = f.Value.Enabled });
+ var toggleState = toggles.ToDictionary(t => t.Key, t => (object)new { on = t.Value.On, enabled = t.Value.Enabled });
+ toggleState["perfShare"] = new { on = perfShare, enabled = true };
+ var online = LoadOnlineConfig();
+ object? onlineState = null;
+ if (online != null)
+ {
+ Dictionary<string, (int Ping, int Online)> info;
+ lock (serverInfo) info = new(serverInfo);
+ onlineState = new
+ {
+ name = online.Value.Name,
+ server = online.Value.Server,
+ status = gameRunning ? "Playing" : toggles["onlineMode"].On ? "Ready to play online" : "Online is off",
+ servers = Regions.Select(r => new
+ {
+ name = r.Name, address = r.Address,
+ ping = info.TryGetValue(r.Address, out var s) ? s.Ping : -1,
+ online = info.TryGetValue(r.Address, out var s2) ? s2.Online : -1,
+ }).ToArray(),
+ };
+ }
+ string proton = protons.Count > 0 ? Path.GetFileName(protons[0]) : "UMU-Proton";
+ json = JsonSerializer.Serialize(new
+ {
+ fields = fieldState, toggles = toggleState, online = onlineState, controls = ControlsState(),
+ exe = Path.Combine(binaries, "fifastreet.exe"), data = gameRoot,
+ summary = $"{proton} · {fields["resolution"].Text} · {fields["refresh"].Text} Hz",
+ status, statusOk, running = gameRunning, deck,
+ api = fields["api"].Text, profile = fields["profile"].Text,
+ version = "V" + typeof(Launcher).Assembly.GetName().Version!.ToString(3) + " · ONLINE BETA",
+ });
+ if (!force && json == lastState) return;
+ lastState = json;
+ }
+ Page.Send(json);
+ }
+
+ private static void Open(string path)
+ {
+ try
+ {
+ Directory.CreateDirectory(path);
+ Process.Start(new ProcessStartInfo("xdg-open") { ArgumentList = { path }, UseShellExecute = false });
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) { Debug.WriteLine(ex.Message); }
+ }
+
+ // The desktop menu entry, as the Windows launcher's "direct play" shortcut: starts the game with the saved settings.
+ private void CreateDesktopEntry()
+ {
+ try
+ {
+ string self = Environment.ProcessPath!;
+ string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local/share/applications");
+ Directory.CreateDirectory(dir);
+ string icon = Path.Combine(AppContext.BaseDirectory, "restreet.jpg");
+ string Entry(string name, string args) =>
+ $"[Desktop Entry]\nType=Application\nName={name}\nExec=\"{self}\" --root \"{root}\"{args}\nPath={AppContext.BaseDirectory}\n" +
+ $"Icon={icon}\nCategories=Game;\nComment=FIFA Street (2012) recompiled\n";
+ File.WriteAllText(Path.Combine(dir, "restreet-launcher.desktop"), Entry("ReStreet Launcher", ""));
+ File.WriteAllText(Path.Combine(dir, "restreet-play.desktop"), Entry("ReStreet (direct play)", " --play"));
+ SetStatus("Menu entries created: ReStreet Launcher and ReStreet (direct play)", true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ SetStatus("Could not create the menu entries: " + ex.Message, false);
+ }
+ }
+
+ public void WaitWhileBrowserConnected(PageServer server)
+ {
+ while (!closing && (gameRunning || DateTime.UtcNow - server.LastSeen < TimeSpan.FromSeconds(90))) Thread.Sleep(1000);
+ }
+
+ public void Shutdown()
+ {
+ closing = true;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/PageServer.cs b/Launcher/FifaStreetLauncher.Linux/PageServer.cs
new file mode 100644
index 0000000..35a805d
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/PageServer.cs
@@ -0,0 +1,131 @@
+using System.Collections.Concurrent;
+using System.Net;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace FifaStreetLauncher.Linux;
+
+// The page's link to the launcher (same protocol as BrowserUi.cs in the Windows launcher): files of ui/, POST msg and
+// a long-polled GET events, served on 127.0.0.1 only, under a random secret path.
+internal sealed class PageServer : IDisposable
+{
+ private readonly TcpListener listener = new(IPAddress.Loopback, 0);
+ private readonly string ui;
+ private readonly string secret = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
+ private readonly Launcher launcher;
+ private readonly ConcurrentQueue<string> outbox = new();
+ private readonly SemaphoreSlim signal = new(0);
+ private volatile bool running = true;
+
+ public DateTime LastSeen { get; private set; } = DateTime.UtcNow;
+ public string Url { get; }
+
+ public PageServer(string ui, Launcher launcher)
+ {
+ this.ui = ui;
+ this.launcher = launcher;
+ listener.Start();
+ Url = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/{secret}/launcher.html";
+ _ = Task.Run(AcceptClients);
+ }
+
+ public void Send(string json)
+ {
+ outbox.Enqueue(json);
+ signal.Release();
+ }
+
+ private async Task AcceptClients()
+ {
+ while (running)
+ {
+ TcpClient client;
+ try { client = await listener.AcceptTcpClientAsync(); }
+ catch (Exception ex) when (ex is SocketException or ObjectDisposedException or InvalidOperationException) { return; }
+ _ = Task.Run(() => Serve(client));
+ }
+ }
+
+ private async Task Serve(TcpClient client)
+ {
+ using var _ = client;
+ try
+ {
+ var stream = client.GetStream();
+ var (method, path, body) = await ReadRequest(stream);
+ string prefix = "/" + secret + "/";
+ if (!path.StartsWith(prefix, StringComparison.Ordinal)) { await Respond(stream, 404, "text/plain", Array.Empty<byte>()); return; }
+ string rest = path[prefix.Length..].Split('?')[0];
+ LastSeen = DateTime.UtcNow;
+ if (method == "POST" && rest == "msg")
+ {
+ launcher.OnMessage(Encoding.UTF8.GetString(body));
+ await Respond(stream, 204, "text/plain", Array.Empty<byte>());
+ }
+ else if (method == "GET" && rest == "events")
+ {
+ // Long poll: answer at once when something is queued, otherwise after 20 s with an empty list.
+ await signal.WaitAsync(TimeSpan.FromSeconds(20));
+ var items = new List<string>();
+ while (outbox.TryDequeue(out var item)) items.Add(item);
+ await Respond(stream, 200, "application/json", Encoding.UTF8.GetBytes("[" + string.Join(",", items) + "]"));
+ }
+ else if (method == "GET" && rest.Length > 0 && rest.IndexOfAny(new[] { '/', '\\' }) < 0 && !rest.Contains(".."))
+ {
+ string file = Path.Combine(ui, rest);
+ string type = Path.GetExtension(file).ToLowerInvariant() switch
+ {
+ ".html" => "text/html; charset=utf-8", ".jpg" => "image/jpeg", ".png" => "image/png",
+ ".css" => "text/css", ".js" => "text/javascript", _ => "application/octet-stream",
+ };
+ if (File.Exists(file)) await Respond(stream, 200, type, await File.ReadAllBytesAsync(file));
+ else await Respond(stream, 404, "text/plain", Array.Empty<byte>());
+ }
+ else await Respond(stream, 404, "text/plain", Array.Empty<byte>());
+ }
+ catch (Exception ex) when (ex is IOException or SocketException or ObjectDisposedException or InvalidOperationException) { }
+ }
+
+ private static async Task<(string Method, string Path, byte[] Body)> ReadRequest(NetworkStream stream)
+ {
+ var head = new List<byte>();
+ var one = new byte[1];
+ while (head.Count < 16384 && await stream.ReadAsync(one) == 1)
+ {
+ head.Add(one[0]);
+ int n = head.Count;
+ if (n >= 4 && head[n - 4] == '\r' && head[n - 3] == '\n' && head[n - 2] == '\r' && head[n - 1] == '\n') break;
+ }
+ string[] lines = Encoding.ASCII.GetString(head.ToArray()).Split("\r\n");
+ string[] first = lines[0].Split(' ');
+ if (first.Length < 2) throw new IOException("bad request");
+ int length = 0;
+ foreach (string line in lines)
+ if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) int.TryParse(line[15..].Trim(), out length);
+ length = Math.Clamp(length, 0, 65536);
+ var body = new byte[length];
+ for (int read = 0; read < length;)
+ {
+ int got = await stream.ReadAsync(body.AsMemory(read));
+ if (got == 0) break;
+ read += got;
+ }
+ return (first[0], first[1], body);
+ }
+
+ private static async Task Respond(NetworkStream stream, int status, string type, byte[] body)
+ {
+ string reason = status switch { 200 => "OK", 204 => "No Content", _ => "Not Found" };
+ string header = $"HTTP/1.1 {status} {reason}\r\nContent-Type: {type}\r\nContent-Length: {body.Length}\r\n" +
+ "Cache-Control: no-store\r\nConnection: close\r\n\r\n";
+ await stream.WriteAsync(Encoding.ASCII.GetBytes(header));
+ if (body.Length > 0) await stream.WriteAsync(body);
+ }
+
+ public void Dispose()
+ {
+ running = false;
+ listener.Stop();
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/Program.cs b/Launcher/FifaStreetLauncher.Linux/Program.cs
new file mode 100644
index 0000000..782be16
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/Program.cs
@@ -0,0 +1,61 @@
+using System.Diagnostics;
+using Photino.NET;
+
+namespace FifaStreetLauncher.Linux;
+
+// ReStreet launcher for Linux: the Windows launcher's page (ui/launcher.html) in a native WebKitGTK window, with the
+// game started through Proton (umu-run). The page talks to this process over 127.0.0.1 exactly as it does with the
+// Windows launcher under Wine (PageServer.cs), so the page needs no Linux-specific code.
+internal static class Program
+{
+ private static int Main(string[] args)
+ {
+ string? root = null;
+ bool play = false;
+ for (int i = 0; i < args.Length; i++)
+ {
+ if (args[i] == "--root" && i + 1 < args.Length) root = args[++i];
+ else if (args[i] == "--play") play = true;
+ }
+ root ??= InstallFolder.Find();
+ if (root == null)
+ {
+ Console.Error.WriteLine("ReStreet folder not found. Run from the ReStreet folder or pass --root <folder>.");
+ return 1;
+ }
+
+ var launcher = new Launcher(root);
+ // Direct play: no window, the game starts with the saved settings and the launcher exits with it.
+ if (play) return launcher.PlayAndWait();
+
+ using var server = new PageServer(Path.Combine(AppContext.BaseDirectory, "ui"), launcher);
+ launcher.Page = server;
+ launcher.StartServices();
+ try
+ {
+ PhotinoWindow? window = null;
+ window = new PhotinoWindow()
+ .SetLogVerbosity(0)
+ .SetTitle("ReStreet Launcher")
+ .SetUseOsDefaultSize(false)
+ .SetSize(1250, 760)
+ .SetMinSize(1000, 620)
+ .Center()
+ .SetIconFile(Path.Combine(AppContext.BaseDirectory, "restreet.jpg"))
+ .SetContextMenuEnabled(false)
+ .SetDevToolsEnabled(false)
+ .Load(new Uri(server.Url));
+ launcher.CloseWindow = () => window.Invoke(window.Close);
+ window.WaitForClose();
+ }
+ catch (Exception ex) when (ex is DllNotFoundException or TypeInitializationException or EntryPointNotFoundException)
+ {
+ // No WebKitGTK: the same page in the system browser, as the Windows launcher does under Wine.
+ Console.Error.WriteLine("WebKitGTK is not available (" + ex.Message + "); opening the launcher in the browser.");
+ Process.Start(new ProcessStartInfo("xdg-open") { ArgumentList = { server.Url }, UseShellExecute = false });
+ launcher.WaitWhileBrowserConnected(server);
+ }
+ launcher.Shutdown();
+ return 0;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/Proton.cs b/Launcher/FifaStreetLauncher.Linux/Proton.cs
new file mode 100644
index 0000000..0b17854
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/Proton.cs
@@ -0,0 +1,76 @@
+using System.Diagnostics;
+
+namespace FifaStreetLauncher.Linux;
+
+internal static class InstallFolder
+{
+ // The ReStreet folder holds Binaries/fifastreet.exe and Game/default.xex. The Linux launcher is published to
+ // <ReStreet>/Linux, so look beside it, then one level up, then in the current folder.
+ public static string? Find()
+ {
+ foreach (string dir in new[] { AppContext.BaseDirectory, Path.Combine(AppContext.BaseDirectory, ".."), Environment.CurrentDirectory })
+ {
+ string full = Path.GetFullPath(dir);
+ if (File.Exists(Path.Combine(full, "Binaries", "fifastreet.exe"))) return full;
+ }
+ return null;
+ }
+
+ // Wine maps the Linux root to Z:.
+ public static string WindowsPath(string linuxPath) => "Z:" + Path.GetFullPath(linuxPath).Replace('/', '\\');
+}
+
+// Proton through umu-run (umu-launcher): it runs any Proton build outside Steam, with the Steam Linux Runtime.
+internal static class Proton
+{
+ public static string? UmuRun() =>
+ new[] { "/usr/bin/umu-run", "/usr/local/bin/umu-run", Path.Combine(Home, ".local/bin/umu-run") }.FirstOrDefault(File.Exists);
+
+ private static string Home => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+
+ // Proton builds the player has installed, best first: CachyOS and GE builds, then Valve's own. An empty list
+ // leaves PROTONPATH unset and umu-run fetches its default (UMU-Proton).
+ public static List<string> Installed()
+ {
+ var found = new List<string>();
+ foreach (string dir in new[]
+ {
+ Path.Combine(Home, ".local/share/Steam/compatibilitytools.d"), Path.Combine(Home, ".steam/root/compatibilitytools.d"),
+ "/usr/share/steam/compatibilitytools.d", Path.Combine(Home, ".local/share/Steam/steamapps/common"),
+ })
+ {
+ if (!Directory.Exists(dir)) continue;
+ foreach (string tool in Directory.GetDirectories(dir))
+ if (File.Exists(Path.Combine(tool, "proton")) && !found.Any(f => Path.GetFileName(f) == Path.GetFileName(tool)))
+ found.Add(tool);
+ }
+ static int Rank(string p)
+ {
+ string n = Path.GetFileName(p).ToLowerInvariant();
+ return n.Contains("cachyos") ? 0 : n.Contains("ge-proton") || n.Contains("proton-ge") ? 1 : n.Contains("experimental") ? 2 : 3;
+ }
+ return found.OrderBy(Rank).ThenByDescending(p => Path.GetFileName(p), StringComparer.OrdinalIgnoreCase).ToList();
+ }
+
+ public static string DefaultPrefix(string root)
+ {
+ // A prefix beside the install (how the first CachyOS installs were made) is kept; otherwise one of our own.
+ string beside = Path.GetFullPath(Path.Combine(root, "..", "prefix-restreet"));
+ if (Directory.Exists(beside)) return beside;
+ return Path.Combine(Home, ".local/share/restreet/prefix");
+ }
+
+ // The game started through umu-run: umu-run waits for the game ("waitforexitandrun"), so the process ends with it.
+ public static ProcessStartInfo StartInfo(string exe, string prefix, string? protonPath)
+ {
+ string umu = UmuRun() ?? throw new InvalidOperationException("umu-run was not found. Install umu-launcher (pacman -S umu-launcher).");
+ Directory.CreateDirectory(prefix);
+ var info = new ProcessStartInfo(umu) { WorkingDirectory = Path.GetDirectoryName(exe)!, UseShellExecute = false };
+ info.ArgumentList.Add(exe);
+ info.Environment["WINEPREFIX"] = prefix;
+ info.Environment["GAMEID"] = "umu-restreet";
+ info.Environment["STORE"] = "none";
+ if (!string.IsNullOrEmpty(protonPath)) info.Environment["PROTONPATH"] = protonPath;
+ return info;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher.Linux/Social.cs b/Launcher/FifaStreetLauncher.Linux/Social.cs
new file mode 100644
index 0000000..bc4ea92
--- /dev/null
+++ b/Launcher/FifaStreetLauncher.Linux/Social.cs
@@ -0,0 +1,214 @@
+using System.Text.Json;
+
+namespace FifaStreetLauncher.Linux;
+
+// Social page (players, friends, chat, rooms): the same calls as GlassUi.cs, HTTP to the player's own server.
+internal sealed partial class Launcher
+{
+ // ---------- Social (players, friends, chat): HTTP to the player's own server with their name and key ----------
+ private static readonly HttpClient SocialHttp = new() { Timeout = TimeSpan.FromSeconds(6) };
+ private DateTime lastBackgroundSocial = DateTime.MinValue;
+
+ // One retry: a single dropped connection (a busy moment on the server, Wi-Fi) must not look like an outage.
+ private static async Task<string> SendWithRetry(Func<Task<string>> send)
+ {
+ try { return await send(); }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
+ {
+ await Task.Delay(400);
+ return await send();
+ }
+ }
+
+ private static async Task<JsonDocument?> PostJson(string server, string path, object body)
+ {
+ string json = JsonSerializer.Serialize(body);
+ string text = await SendWithRetry(async () =>
+ {
+ using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
+ using var response = await SocialHttp.PostAsync($"http://{server}:29812{path}", content);
+ return await response.Content.ReadAsStringAsync();
+ });
+ return text.StartsWith("{") ? JsonDocument.Parse(text) : null;
+ }
+
+ private static async Task<JsonDocument> GetJson(string server, string path) =>
+ JsonDocument.Parse(await SendWithRetry(() => SocialHttp.GetStringAsync($"http://{server}:29812{path}")));
+
+ private int socialFailures;
+
+ private int socialPollBusy;
+ private volatile bool inRoom;
+
+ // A background poll is skipped while the previous one still runs: on a slow link they piled up every 3 s.
+ private async Task SocialAsync(string cmd, JsonElement m)
+ {
+ if (cmd != "social") { await SocialCoreAsync(cmd, m); return; }
+ if (Interlocked.Exchange(ref socialPollBusy, 1) == 1) return;
+ try { await SocialCoreAsync(cmd, m); }
+ finally { Volatile.Write(ref socialPollBusy, 0); }
+ }
+
+ private async Task SocialCoreAsync(string cmd, JsonElement m)
+ {
+ var online = LoadOnlineConfig();
+ if (online == null || !toggles["onlineMode"].On || Page == null) return;
+ var (server, name, key) = online.Value;
+ string Str(string p) => m.TryGetProperty(p, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
+ string channel = Str("channel");
+ string? error = null;
+ try
+ {
+ if (cmd == "social" && channel == "")
+ {
+ // Social page closed: refresh the badge only every 15 s (every poll while in a room, to start the game on time).
+ if (!inRoom && DateTime.UtcNow - lastBackgroundSocial < TimeSpan.FromSeconds(15)) return;
+ lastBackgroundSocial = DateTime.UtcNow;
+ }
+ if (cmd == "chatSend")
+ {
+ using var r = await PostJson(server, "/v1/textchat", new { me = name, key, action = "send", channel, text = Str("text") });
+ if (r != null && r.RootElement.TryGetProperty("error", out var e)) error = ChatError(e.GetString());
+ }
+ else if (cmd == "chatAction")
+ {
+ long id = m.TryGetProperty("id", out var idv) && idv.ValueKind == JsonValueKind.Number ? idv.GetInt64() : 0;
+ using var r = await PostJson(server, "/v1/textchat", new { me = name, key, action = Str("action"), other = Str("other"), id });
+ if (Str("action") == "report") error = "Thanks, the message was reported";
+ }
+ else if (cmd == "friend")
+ {
+ using var r = await PostJson(server, "/v1/friends", new { me = name, key, action = Str("action"), other = Str("other") });
+ if (r != null && r.RootElement.TryGetProperty("result", out var fr) && fr.ValueKind == JsonValueKind.String)
+ error = fr.GetString() switch { "unknown" => $"No player called {Str("other")}", "self" => "You can't add yourself", _ => null };
+ }
+ else if (cmd == "room")
+ {
+ // Game rooms (rooms.py): when a room is full the game takes both players to the match set-up by itself.
+ string action = Str("action");
+ long roomId = m.TryGetProperty("room", out var rv) && rv.ValueKind == JsonValueKind.Number ? rv.GetInt64() : 0;
+ int stadium = m.TryGetProperty("stadium", out var sv2) && sv2.ValueKind == JsonValueKind.Number ? sv2.GetInt32() : 1047;
+ using var r = action switch
+ {
+ "create" => await PostJson(server, "/v1/rooms", new { me = name, key, action, name = Str("title").Trim().Length > 0 ? Str("title").Trim() : name + "'s game", mode = Str("mode"), stadium }),
+ "join" => await PostJson(server, "/v1/rooms", new { me = name, key, action, room = roomId }),
+ _ => await PostJson(server, "/v1/rooms", new { me = name, key, action = "leave" }),
+ };
+ if (r != null && r.RootElement.TryGetProperty("error", out var re)) error = RoomError(re.GetString());
+ else if (action == "create" && r != null && r.RootElement.TryGetProperty("room", out var made))
+ {
+ // Tell the server channel, so anyone can join from the Open games list.
+ string text = $"🎮 I opened a {RoomModeName(Str("mode"))} game at {made.GetProperty("stadium_name").GetString()}. Join it from the Matches tab!";
+ using var _ = await PostJson(server, "/v1/textchat", new { me = name, key, action = "send", channel = "general", text });
+ }
+ }
+
+ // Fresh snapshot for the page. All requests at once: one after the other they took seconds on a far server.
+ var friendsTask = PostJson(server, "/v1/friends", new { me = name, key, action = "list" });
+ var playersTask = GetJson(server, "/v1/online");
+ var roomsTask = PostJson(server, "/v1/rooms", new { me = name, key, action = "list" });
+ var myRoomTask = PostJson(server, "/v1/rooms", new { me = name, key, action = "current" });
+ var convosTask = PostJson(server, "/v1/textchat", new { me = name, key, action = "conversations" });
+ var msgsTask = channel == "" ? Task.FromResult<JsonDocument?>(null)
+ : PostJson(server, "/v1/textchat", new { me = name, key, action = "read", channel, since = m.TryGetProperty("since", out var s2) && s2.ValueKind == JsonValueKind.Number ? s2.GetInt64() : 0 });
+ JsonDocument? convos = null, msgs = null;
+ bool chatOff = false;
+ try
+ {
+ convos = await convosTask;
+ msgs = await msgsTask;
+ chatOff = convos == null && msgs == null; // either answer means the chat is there
+ }
+ catch (HttpRequestException) { chatOff = true; }
+ using var friends = await friendsTask;
+ using var players = await playersTask;
+ using var rooms = await roomsTask;
+ using var myRoom = await myRoomTask;
+ var waited = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
+ if (players.RootElement.TryGetProperty("searching_list", out var sl) && sl.ValueKind == JsonValueKind.Array)
+ foreach (var it in sl.EnumerateArray())
+ if (it.TryGetProperty("name", out var wn) && it.TryGetProperty("waited_s", out var ws) && ws.ValueKind == JsonValueKind.Number)
+ waited[wn.GetString() ?? ""] = ws.GetInt32();
+ string regionName = Regions.FirstOrDefault(r => r.Address == server).Name ?? server;
+ var payload = new Dictionary<string, object?>
+ {
+ ["type"] = "social",
+ ["me"] = name,
+ ["server"] = regionName,
+ ["channel"] = channel,
+ ["error"] = error,
+ ["chatOff"] = chatOff,
+ ["players"] = players.RootElement.TryGetProperty("players", out var pl)
+ ? pl.EnumerateArray().Select(p => new
+ {
+ name = p.GetProperty("name").GetString(),
+ state = p.GetProperty("state").GetString(),
+ note = p.GetProperty("state").GetString() switch
+ {
+ "in_game" => "Playing " + (p.TryGetProperty("mode", out var md) ? md.GetString() : ""),
+ "searching" => "Searching · " + (p.TryGetProperty("mode", out var md2) ? md2.GetString() : "") +
+ (waited.TryGetValue(p.GetProperty("name").GetString() ?? "", out int w) ? $" · {w / 60}:{w % 60:00}" : ""),
+ _ => "In the menus",
+ },
+ }).ToArray()
+ : Array.Empty<object>(),
+ };
+ if (players.RootElement.TryGetProperty("searching_modes", out var smodes))
+ payload["searchingModes"] = JsonSerializer.Deserialize<object>(smodes.GetRawText());
+ if (rooms != null && rooms.RootElement.TryGetProperty("rooms", out var rl))
+ payload["rooms"] = JsonSerializer.Deserialize<object>(rl.GetRawText());
+ if (myRoom != null && myRoom.RootElement.TryGetProperty("room", out var mr))
+ payload["myRoom"] = JsonSerializer.Deserialize<object>(mr.GetRawText());
+ inRoom = myRoom != null && myRoom.RootElement.TryGetProperty("room", out var mr3) && mr3.ValueKind == JsonValueKind.Object;
+ OnRoomState(myRoom != null && myRoom.RootElement.TryGetProperty("room", out var mr2) ? mr2.Clone() : null);
+ if (friends != null)
+ {
+ var f = friends.RootElement;
+ payload["friends"] = f.TryGetProperty("friends", out var fl) ? JsonSerializer.Deserialize<object>(fl.GetRawText()) : null;
+ payload["requests"] = f.TryGetProperty("requests", out var rq) ? JsonSerializer.Deserialize<object>(rq.GetRawText()) : null;
+ payload["pending"] = f.TryGetProperty("pending", out var pd) ? JsonSerializer.Deserialize<object>(pd.GetRawText()) : null;
+ }
+ if (convos != null && convos.RootElement.TryGetProperty("conversations", out var cv))
+ payload["convos"] = JsonSerializer.Deserialize<object>(cv.GetRawText());
+ if (msgs != null && msgs.RootElement.TryGetProperty("messages", out var ms))
+ payload["messages"] = JsonSerializer.Deserialize<object>(ms.GetRawText());
+ convos?.Dispose(); msgs?.Dispose();
+ socialFailures = 0;
+ string json = JsonSerializer.Serialize(payload);
+ Page?.Send(json);
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
+ {
+ // Background refreshes keep the last data; only say so after three failures in a row (or when the
+ // player's own action failed).
+ if (cmd == "social" && ++socialFailures < 3) return;
+ string json = JsonSerializer.Serialize(new { type = "social", error = "Server not reachable" });
+ Page?.Send(json);
+ }
+ }
+
+ private static string RoomModeName(string mode) => mode switch
+ {
+ "fives" => "5-a-side", "sixes" => "6-a-side", "futsal" => "Futsal", _ => mode,
+ };
+
+ private static string RoomError(string? code) => code switch
+ {
+ "full" => "That game is already full",
+ "already_in_room" => "Leave your current game first",
+ "too_fast" => "Wait a few seconds before opening another game",
+ "no_such_room" or "unknown_room" => "That game is closed",
+ _ => "Could not do that: " + code,
+ };
+
+ private static string ChatError(string? code) => code switch
+ {
+ "too_fast" => "Slow down a little",
+ "no_links" => "Links are not allowed in chat",
+ "too_long" => "Message too long (300 characters max)",
+ "muted" => "You are muted for a while",
+ "banned" => "You can't use the chat",
+ "not_friends" => "You can only message friends",
+ _ => "Message not sent",
+ };
+}
diff --git a/docs/BUILDING.md b/docs/BUILDING.md
index bb34341..ab6718d 100644
--- a/docs/BUILDING.md
+++ b/docs/BUILDING.md
@@ -169,6 +169,31 @@ The launcher expects installed backend pairs under:
It activates the selected pair beside `fifastreet.exe` before starting the game.
+## Build the Linux launcher
+
+`Launcher/FifaStreetLauncher.Linux` is a native Linux launcher for an existing ReStreet install. It shows the same
+`ui/launcher.html` in a WebKitGTK window (Photino.NET) and starts the Windows game through Proton with `umu-run`,
+passing the same `REX_*` and online `FIFASTREET_*` variables as the Windows launcher. It can be built on Linux or
+Windows with the .NET 8 SDK:
+
+ dotnet publish Launcher/FifaStreetLauncher.Linux/FifaStreetLauncher.Linux.csproj -c Release --self-contained -o dist/Linux
+
+Copy `dist/Linux` into the ReStreet folder (beside `Binaries` and `Game`) and run `Linux/restreet-launcher`, or pass
+`--root <ReStreet folder>`. `--play` starts the game without a window. The **Shortcut** button adds "ReStreet
+Launcher" and "ReStreet (direct play)" to the desktop menu.
+
+Runtime needs: `umu-launcher`, `webkit2gtk-4.1` and a Proton build. The launcher prefers Proton-CachyOS, then
+GE-Proton, then Valve's; with none installed `umu-run` downloads UMU-Proton. The Wine prefix is
+`~/.local/share/restreet/prefix` (or `prefix-restreet` beside the install, if present). Settings are kept in
+`linux-settings.json`; `controls.json` and `fifastreet.toml` are shared with the Windows launcher and the game.
+
+Not on Linux yet: the self-updater, stadium pictures and performance reports.
+
+Installing on Linux without Windows: the setup's page needs WebView2, which Proton lacks, so run its headless
+install instead (ISO, target folder, online name):
+
+ umu-run ReStreet-<version>-Setup.exe --iso-install-test 'Z:\path\to\FIFASTREET.iso' 'Z:\path\to\ReStreet' YourName
+
## Package the installer
The source images and icon are tracked. Compiled SDK tools, `extract-xiso.exe`, compiler binaries and `bundle.zip` remain local and excluded from Git.