using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Http; using System.Net.WebSockets; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using UnityEngine; namespace GrassCutter { /// /// The web behind the phone: the player's own Edge or Chrome, with no window and a profile of its own, driven over the /// DevTools protocol. It renders a real phone-sized page, we copy its screencast into a texture and send touches and /// text back, so feeds, logins and video behave as they do on a phone. It starts on the first page opened, is paused /// while the phone is put away, comes back if it dies, and goes when the match does. /// public class PhoneWeb { const int TallW = 390, WideH = 390, FrameTall = 640, FrameWide = 1120; const int Retries = 4; // our eyes in every document and frame: the game's volume, quiet when the phone goes away, and new windows in the one tab const string Keep = "(()=>{const s=window.__gc={vol:.6,hold:false};" + "setInterval(()=>{for(const v of document.querySelectorAll('video,audio')){if(v.volume!==s.vol)v.volume=s.vol;" + "if(s.hold){if(!v.paused){v.pause();v.__gcHeld=1}}else if(v.__gcHeld){v.__gcHeld=0;v.play().catch(()=>{})}}" + "for(let i=0;i{const m=e.data&&e.data.__gc;if(m){s.vol=m[0];s.hold=m[1]}});" + "window.open=u=>{if(u)location.href=u;return window};" + "addEventListener('click',e=>{const a=e.target.closest&&e.target.closest('a[target]');if(a)a.target='_self'},true)})()"; /// /// Full screen, done on the page itself: the element is pinned over the whole of the phone's page. The browser /// runs without a window of its own, so the real thing was refused or came out the wrong size and shifted to /// one side, and each site's fallback for that came out crooked in its own way. /// const string Full = "(()=>{let fe=null,was=null,hid=[];const ev=e=>{for(const n of['fullscreenchange','webkitfullscreenchange'])e.dispatchEvent(new Event(n,{bubbles:true}))};" + "const exit=function(){if(!fe)return Promise.resolve();const e=fe;fe=null;for(const[h,v]of hid)h.style.visibility=v;hid=[];if(was)e.setAttribute('style',was);else e.removeAttribute('style');ev(e);return Promise.resolve()};" + "const enter=function(){if(fe===this)return Promise.resolve();if(fe)exit();fe=this;was=this.getAttribute('style');" + "this.style.cssText+=';position:fixed!important;left:0!important;top:0!important;right:auto!important;bottom:auto!important;width:100vw!important;height:100vh!important;" + "max-width:none!important;max-height:none!important;margin:0!important;transform:none!important;z-index:2147483647!important;background:#000!important';" + // whatever else is on the page (a site's own header sits above the player) is hidden while it lasts "for(let n=this;n&&n.parentElement;n=n.parentElement)for(const o of n.parentElement.children)if(o!==n){hid.push([o,o.style.visibility]);o.style.setProperty('visibility','hidden','important')}" + "ev(this);return Promise.resolve()};" + "for(const n of['requestFullscreen','webkitRequestFullscreen','webkitRequestFullScreen'])Element.prototype[n]=enter;" + "HTMLVideoElement.prototype.webkitEnterFullscreen=enter;HTMLVideoElement.prototype.webkitEnterFullScreen=enter;" + "for(const n of['exitFullscreen','webkitExitFullscreen','webkitCancelFullScreen'])Document.prototype[n]=exit;" + "for(const n of['fullscreenElement','webkitFullscreenElement','webkitCurrentFullScreenElement'])Object.defineProperty(Document.prototype,n,{get:()=>fe,configurable:true});" + "for(const n of['fullscreenEnabled','webkitFullscreenEnabled'])Object.defineProperty(Document.prototype,n,{get:()=>true,configurable:true})})()"; /// One running browser. A new one is made after a crash, so a late message from the old one can't touch it. sealed class Link { public Process Proc; public IntPtr Job; public ClientWebSocket Ws; public string Tab; public readonly CancellationTokenSource Stop = new CancellationTokenSource(); public readonly BlockingCollection Out = new BlockingCollection(); public volatile bool Ready; public bool Dressed; } /// A frame on its way to the screen. Reused: at 30 a second, fresh arrays of half a megabyte would be a garbage collection a second. sealed class Shot { public byte[] Jpeg = new byte[1 << 18]; public int Session; } readonly Texture2D _decoded; readonly RenderTexture _rt; readonly string _profile; readonly bool _mute; readonly int _pageH, _fullW; readonly ConcurrentBag _spare = new ConcurrentBag(); readonly ConcurrentDictionary> _wait = new ConcurrentDictionary>(); Link _link; Shot _shot; int _id, _frames, _decodes, _tries, _restarts; volatile int _navId; volatile bool _loading, _died, _failed; volatile string _url, _navError, _problem; string _pending, _wanted, _last; bool _shown, _wide, _page; float _retryAt, _nextState, _nextDecode, _nextFlick, _decodeMs; /// The page, as a texture of its own. It is stretched to fit, so the page's shape doesn't matter here. public Texture Picture => _rt; public bool Fresh { get; private set; } public bool Ready => _link != null && _link.Ready; public bool Loading => _loading; public string Url => _url; public int CssW => _wide ? _fullW : TallW; public int CssH => _wide ? WideH : _pageH; /// What went wrong, once. public string TakeProblem() { var p = _problem; _problem = null; return p; } public static bool Available => Engine() != null; /// The page's height over its width with the phone upright. /// Its width over its height with the phone on its side. public PhoneWeb(float tall, float wide) { _pageH = Mathf.RoundToInt(TallW * tall); _fullW = Mathf.RoundToInt(WideH * wide); // a test run keeps away from the player's logins and out of their speakers _mute = CommandLine.Has("-autodemo"); _profile = Path.Combine(_mute ? Application.temporaryCachePath : Application.persistentDataPath, "PhoneWeb"); _decoded = new Texture2D(FrameTall, FrameTall, TextureFormat.RGB24, false); _rt = new RenderTexture(FrameTall, FrameTall * _pageH / TallW, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "PhoneWeb" }; _rt.Create(); ClearPicture(); } // ───────────────────────── what the phone asks of it ───────────────────────── public void Go(string url) { if (!Available) return; _page = true; _url = null; _navError = null; _wanted = null; _pending = url; _loading = true; _restarts = 0; ClearPicture(); Boot(); } /// The home screen is up: the page goes, and with it anything still playing. public void Leave() { _page = false; _pending = _wanted = _last = null; _loading = false; _url = null; ClearPicture(); if (Ready) Cmd("Page.navigate", "{\"url\":\"about:blank\"}"); } /// Black, so the last site's last frame isn't what the next one opens on. void ClearPicture() { var was = RenderTexture.active; RenderTexture.active = _rt; GL.Clear(false, true, Color.black); RenderTexture.active = was; var s = Interlocked.Exchange(ref _shot, null); if (s != null) Ack(s); } public void Stop() { if (Ready) { Cmd("Page.stopLoading"); _loading = false; } } /// Something else has the phone's screen (a call): whatever plays on the page is paused under it. public bool Hold { get => _hold; set { if (_hold != value) { _hold = value; _nextState = 0f; } } } bool _hold; public void Back() { if (Ready) Cmd("Runtime.evaluate", "{\"expression\":\"void history.back()\"}"); } public void Forward() { if (Ready) Cmd("Runtime.evaluate", "{\"expression\":\"void history.forward()\"}"); } public void Reload() { if (Ready) { _loading = true; Cmd("Page.reload"); } } /// The phone came out or went away: frames only flow while someone can see them. public void Show(bool on) { if (_shown == on) return; _shown = on; _nextState = 0f; if (Ready) Screencast(on); } public void Wide(bool on) { if (_wide == on) return; _wide = on; ClearPicture(); if (Ready) { Metrics(); if (_shown) { Cmd("Page.stopScreencast"); Screencast(true); } } } void Screencast(bool on) { if (on) Cmd("Page.startScreencast", _wide ? $"{{\"format\":\"jpeg\",\"quality\":70,\"maxWidth\":{FrameWide},\"maxHeight\":{FrameWide * WideH / _fullW},\"everyNthFrame\":1}}" : $"{{\"format\":\"jpeg\",\"quality\":68,\"maxWidth\":{FrameTall},\"maxHeight\":{FrameTall * _pageH / TallW},\"everyNthFrame\":1}}"); else Cmd("Page.stopScreencast"); } void Metrics() { string turned = _wide ? ",\"screenOrientation\":{\"type\":\"landscapePrimary\",\"angle\":90}" : ",\"screenOrientation\":{\"type\":\"portraitPrimary\",\"angle\":0}"; Cmd("Emulation.setDeviceMetricsOverride", $"{{\"width\":{CssW},\"height\":{CssH},\"screenWidth\":{CssW},\"screenHeight\":{CssH},\"deviceScaleFactor\":2,\"mobile\":true{turned}}}"); Bounds(); } /// /// The browser's own window the size of the phone's page. A site going full screen fills the window, not the page /// the phone shows, so with the window left at its start-up size the video came out shifted off to one side. /// void Bounds() { if (_winId > 0) Cmd("Browser.setWindowBounds", $"{{\"windowId\":{_winId},\"bounds\":{{\"width\":{CssW},\"height\":{CssH}}}}}"); } volatile int _winAsk, _winId; // ───────────────────────── fingers ───────────────────────── public void Touch(string type, float x, float y) { if (Ready) Cmd("Input.dispatchTouchEvent", string.Format(CultureInfo.InvariantCulture, "{{\"type\":\"{0}\",\"touchPoints\":[{{\"x\":{1:0.#},\"y\":{2:0.#}}}]}}", type, x, y)); } public void TouchEnd() { if (Ready) Cmd("Input.dispatchTouchEvent", "{\"type\":\"touchEnd\",\"touchPoints\":[]}"); } /// A quick swipe: the next video in a feed, or a screenful anywhere else. void Flick(int dir) { float x = CssW * 0.5f, y0 = dir > 0 ? CssH * 0.72f : CssH * 0.28f; float step = -dir * CssH * 0.05f; Task.Run(async () => { Touch("touchStart", x, y0); for (int i = 1; i <= 9; i++) { Touch("touchMove", x, y0 + step * i); await Task.Delay(14); } TouchEnd(); }); } /// A feed moves one video at a time; anything else scrolls like a page. bool OnFeed { get { string u = _url ?? ""; return u.Contains("tiktok.com") || u.Contains("instagram.com") || u.Contains("/shorts"); } } /// The mouse wheel, one notch at a time. Positive is on down the page. public void Wheel(int dir) => Wheel(dir, CssW / 2f, CssH / 2f); /// The wheel over a point of the page: what's under it scrolls (a chat beside a stream, a list in a menu). public void Wheel(int dir, float x, float y) { if (!Ready) return; if (OnFeed) { if (Time.unscaledTime < _nextFlick) return; _nextFlick = Time.unscaledTime + 0.35f; Flick(dir); return; } Cmd("Input.dispatchMouseEvent", string.Format(CultureInfo.InvariantCulture, "{{\"type\":\"mouseWheel\",\"x\":{0:0.#},\"y\":{1:0.#},\"deltaX\":0,\"deltaY\":{2}}}", x, y, dir * 220)); } public void Insert(string text) { if (Ready) Cmd("Input.insertText", "{\"text\":" + Str(text) + "}"); } /// CDP's: 1 Alt, 2 Ctrl, 4 Meta, 8 Shift. public void Key(string name, int code, string text, int modifiers = 0) { if (!Ready) return; string common = $"\"key\":\"{name}\",\"code\":\"{name}\",\"windowsVirtualKeyCode\":{code},\"modifiers\":{modifiers}"; Cmd("Input.dispatchKeyEvent", "{\"type\":\"" + (text != null ? "keyDown" : "rawKeyDown") + "\"," + common + (text != null ? ",\"text\":\"" + text + "\"" : "") + "}"); Cmd("Input.dispatchKeyEvent", "{\"type\":\"keyUp\"," + common + "}"); } /// An editing command on the focused text box: selectAll, undo, redo. public void Command(string name) { if (Ready) Cmd("Input.dispatchKeyEvent", "{\"type\":\"rawKeyDown\",\"key\":\"\",\"windowsVirtualKeyCode\":0,\"commands\":[\"" + name + "\"]}"); } /// Is the page waiting for typing? public async Task FieldActive() { const string js = "(()=>{const e=document.activeElement;return String(!!e&&(e.isContentEditable||e.tagName==='TEXTAREA'||(e.tagName==='INPUT'&&!/^(checkbox|radio|button|submit|range|file)$/.test(e.type))))})()"; return await Ask(js) == "true"; } /// A question for the page, answered as a string, or null if it never comes. public Task Ask(string js) { int id = Interlocked.Increment(ref _id); var done = new TaskCompletionSource(); if (!Ready) { done.TrySetResult(null); return done.Task; } _wait[id] = done; Send(_link, "{\"id\":" + id + ",\"method\":\"Runtime.evaluate\",\"params\":{\"expression\":" + Str(js) + ",\"awaitPromise\":true,\"userGesture\":true}}"); return done.Task; } /// For the test bot: how the frames are doing. public string Stats => $"{_frames} frames in, {_decodes} shown, {_decodeMs * 1000f / Mathf.Max(_decodes, 1):0.0} ms each"; /// For the test bot: the browser dies under the phone. public void Kill() { try { _link?.Proc?.Kill(); } catch (InvalidOperationException) { } } public bool Running { get { try { return _link?.Proc != null && !_link.Proc.HasExited; } catch (InvalidOperationException) { return false; } } } // ───────────────────────── every frame ───────────────────────── /// Runs whether the phone is out or not, or nothing could tell a page to stop. public void Tick(bool sharp) { Fresh = false; if (_failed) { _failed = false; _loading = false; _died = false; Drop(_link); _link = null; } if (_died) Revive(); if (Ready && !_link.Dressed) { // the page's shape and the frames, as they are now: a Show or a turn while it started can't be lost _link.Dressed = true; Metrics(); if (_shown) Screencast(true); } if (Ready) { if (_pending != null) { _wanted = _pending; _pending = null; _tries = 0; _retryAt = Time.unscaledTime + 5f; Navigate(); } KeepNavigating(); SendState(); } float now = Time.unscaledTime; if (now >= _nextDecode) { var s = Interlocked.Exchange(ref _shot, null); if (s != null) { // the screen of a phone is no reason to spend a frame of the game on every frame of a video _nextDecode = now + (sharp ? 1f / 30f : 1f / 24f); if (_page) { float started = Time.realtimeSinceStartup; if (_decoded.LoadImage(s.Jpeg, false)) { // the texture takes the frame's own size: no squeezing a 1120-wide frame into less and back if (_rt.width != _decoded.width || _rt.height != _decoded.height) { _rt.Release(); _rt.width = _decoded.width; _rt.height = _decoded.height; _rt.Create(); } Graphics.Blit(_decoded, _rt); Fresh = true; } _decodeMs += Time.realtimeSinceStartup - started; _decodes++; } Ack(s); } } var at = _url; if (at != null && at != "about:blank") _last = at; } void Navigate() => _navId = Cmd("Page.navigate", "{\"url\":" + Str(_wanted) + "}"); /// Until the page has actually arrived it can still get lost: a navigation is dropped while the tab is busy. void KeepNavigating() { if (_wanted == null) return; string at = _url, failed = _navError; if (at != null && at != "about:blank") { _wanted = null; return; } if (failed != null) { _navError = null; if (!failed.Contains("ABORTED")) { GiveUp(); return; } _retryAt = 0f; } if (Time.unscaledTime < _retryAt) return; if (_tries >= Retries) { GiveUp(); return; } _tries++; _retryAt = Time.unscaledTime + 5f * (_tries + 1); Navigate(); } void GiveUp() { _wanted = null; _loading = false; _problem = Loc.N("Can't reach that site."); } /// Sent again and again: a new document starts with nothing, and the phone may have gone away before it arrived. void SendState() { if (Time.unscaledTime < _nextState) return; _nextState = Time.unscaledTime + 0.5f; string v = (GameSettings.Master * GameSettings.PhoneVolume).ToString("0.00", CultureInfo.InvariantCulture); Cmd("Runtime.evaluate", "{\"expression\":\"void(window.__gc&&(__gc.vol=" + v + ",__gc.hold=" + (_shown && !_hold ? "false" : "true") + "))\"}"); } void Revive() { _died = false; Drop(_link); _link = null; if (!_page) return; string back = _wanted ?? _pending ?? _last; if (back != null && _restarts < 3) { _restarts++; _pending = back; _url = null; _loading = true; Boot(); return; } _loading = false; _problem = Loc.N("The connection dropped."); } // ───────────────────────── the engine ───────────────────────── static string Engine() { string pf = Environment.GetEnvironmentVariable("ProgramFiles"), pf86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); string local = Environment.GetEnvironmentVariable("LOCALAPPDATA"); foreach (var root in new[] { pf86, pf, local }) { if (string.IsNullOrEmpty(root)) continue; foreach (var exe in new[] { @"Microsoft\Edge\Application\msedge.exe", @"Google\Chrome\Application\chrome.exe", @"BraveSoftware\Brave-Browser\Application\brave.exe", @"Chromium\Application\chrome.exe" }) { var path = Path.Combine(root, exe); if (File.Exists(path)) return path; } } return null; } void Boot() { if (_link != null) return; var link = _link = new Link(); string exe = Engine(); Application.quitting -= Close; Application.quitting += Close; Task.Run(() => Connect(link, exe)); } async Task Connect(Link link, string exe) { try { Directory.CreateDirectory(_profile); string portFile = Path.Combine(_profile, "DevToolsActivePort"); // the last browser may still be letting go of its profile for (int i = 0; i < 20 && File.Exists(portFile); i++) { try { File.Delete(portFile); } catch (IOException) { await Task.Delay(100); } catch (UnauthorizedAccessException) { await Task.Delay(100); } } string args = "--headless=new --remote-debugging-port=0 --user-data-dir=\"" + _profile + "\" --no-first-run --no-default-browser-check " + "--autoplay-policy=no-user-gesture-required --disable-blink-features=AutomationControlled --hide-crash-restore-bubble --disable-sync --disk-cache-size=157286400 --window-size=412,875 " + (_mute ? "--mute-audio " : "") + "about:blank"; link.Proc = Process.Start(new ProcessStartInfo(exe, args) { UseShellExecute = false, CreateNoWindow = true }); TieToGame(link); string port = null; for (int i = 0; i < 150 && port == null; i++) { await Task.Delay(100); try { port = File.ReadAllText(portFile).Split('\n')[0].Trim(); } catch (IOException) { } if (port == "") port = null; } if (port == null) throw new TimeoutException("The browser didn't start."); string ws, ua, chrome; using (var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(10) }) { // the debug server hangs up after each answer, so no reusing the connection http.DefaultRequestHeaders.ConnectionClose = true; // a fresh tab of our own: what's already open can be a restored page, a start-up about:blank still on its // way, or Edge's hidden extension pages, which come first in its list and would swallow the page we ask for var open = await http.GetStringAsync($"http://127.0.0.1:{port}/json"); var made = await http.SendAsync(new HttpRequestMessage(HttpMethod.Put, $"http://127.0.0.1:{port}/json/new?about:blank")); made.EnsureSuccessStatusCode(); var tab = await made.Content.ReadAsStringAsync(); ws = Regex.Match(tab, "\"webSocketDebuggerUrl\"\\s*:\\s*\"(ws://[^\"]+)\"").Groups[1].Value; link.Tab = Regex.Match(tab, "\"id\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value; foreach (Match old in Regex.Matches(open, "\"id\"\\s*:\\s*\"([^\"]+)\"[^{}]*?\"type\"\\s*:\\s*\"page\"")) await http.GetAsync($"http://127.0.0.1:{port}/json/close/{old.Groups[1].Value}"); var version = await http.GetStringAsync($"http://127.0.0.1:{port}/json/version"); chrome = Regex.Match(version, "\"Browser\"\\s*:\\s*\"[^/]+/(\\d+)").Groups[1].Value; ua = $"Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{chrome}.0.0.0 Mobile Safari/537.36"; } link.Ws = new ClientWebSocket(); link.Ws.Options.Proxy = null; using (var limit = CancellationTokenSource.CreateLinkedTokenSource(link.Stop.Token)) { limit.CancelAfter(TimeSpan.FromSeconds(10)); await link.Ws.ConnectAsync(new Uri(ws), limit.Token); } _ = Task.Run(() => Sender(link)); _ = Task.Run(() => Receiver(link)); Send(link, "Page.enable", "{}"); // the whole of a phone's Chrome, client hints included: with only the agent string swapped, the hints still // said HeadlessChrome on Windows, and YouTube stopped a video a couple of minutes in ("something went wrong") string brands = $"[{{\"brand\":\"Chromium\",\"version\":\"{chrome}\"}},{{\"brand\":\"Google Chrome\",\"version\":\"{chrome}\"}},{{\"brand\":\"Not.A/Brand\",\"version\":\"99\"}}]"; string full = $"[{{\"brand\":\"Chromium\",\"version\":\"{chrome}.0.0.0\"}},{{\"brand\":\"Google Chrome\",\"version\":\"{chrome}.0.0.0\"}},{{\"brand\":\"Not.A/Brand\",\"version\":\"99.0.0.0\"}}]"; Send(link, "Emulation.setUserAgentOverride", "{\"userAgent\":" + Str(ua) + ",\"platform\":\"Linux armv8l\",\"userAgentMetadata\":{\"brands\":" + brands + ",\"fullVersionList\":" + full + ",\"platform\":\"Android\",\"platformVersion\":\"14.0.0\",\"architecture\":\"\",\"model\":\"Pixel 8\",\"mobile\":true}}"); Send(link, "Emulation.setTouchEmulationEnabled", "{\"enabled\":true,\"maxTouchPoints\":5}"); Send(link, "Browser.setDownloadBehavior", "{\"behavior\":\"deny\"}"); Send(link, "Page.addScriptToEvaluateOnNewDocument", "{\"source\":" + Str(Keep + ";" + Full) + "}"); int win = Interlocked.Increment(ref _id); _winAsk = win; Send(link, "{\"id\":" + win + ",\"method\":\"Browser.getWindowForTarget\",\"params\":{}}"); link.Ready = true; } catch (Exception e) { if (link.Stop.IsCancellationRequested) return; UnityEngine.Debug.LogWarning("[PhoneWeb] " + e.GetType().Name + ": " + (e.InnerException ?? e).Message); _problem = Loc.N("Something on this PC stopped the browser from starting."); _failed = true; } } int Cmd(string method, string args = "{}") { int id = Interlocked.Increment(ref _id); Send(_link, "{\"id\":" + id + ",\"method\":\"" + method + "\",\"params\":" + args + "}"); return id; } void Send(Link link, string method, string args) { int id = Interlocked.Increment(ref _id); Send(link, "{\"id\":" + id + ",\"method\":\"" + method + "\",\"params\":" + args + "}"); } static void Send(Link link, string message) { if (link == null || link.Out.IsAddingCompleted) return; try { link.Out.Add(message); } catch (InvalidOperationException) { } } void Ack(Shot s) { Cmd("Page.screencastFrameAck", "{\"sessionId\":" + s.Session + "}"); _spare.Add(s); } static string Str(string s) { var b = new StringBuilder("\""); foreach (char c in s) { if (c == '"' || c == '\\') b.Append('\\').Append(c); else if (c < 32) b.Append("\\u").Append(((int)c).ToString("x4")); else b.Append(c); } return b.Append('"').ToString(); } async Task Sender(Link link) { try { foreach (var m in link.Out.GetConsumingEnumerable(link.Stop.Token)) await link.Ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(m)), WebSocketMessageType.Text, true, link.Stop.Token); } catch (OperationCanceledException) { } catch (WebSocketException) { Lost(link); } catch (ObjectDisposedException) { } } [Serializable] class Msg { public int id; public string method; public Params @params; public Outer result; } [Serializable] class Params { public string url, frameId; public FrameInfo frame; } [Serializable] class FrameInfo { public string url; public string parentId; } [Serializable] class Outer { public Inner result; public string errorText; public int windowId; } [Serializable] class Inner { public string value; } async Task Receiver(Link link) { var buffer = new byte[1 << 16]; var message = new MemoryStream(1 << 20); try { while (!link.Stop.IsCancellationRequested) { var r = await link.Ws.ReceiveAsync(new ArraySegment(buffer), link.Stop.Token); if (r.MessageType == WebSocketMessageType.Close) { Lost(link); return; } message.Write(buffer, 0, r.Count); if (!r.EndOfMessage) continue; try { Handle(link, message.GetBuffer(), (int)message.Length); } catch (ArgumentException e) { UnityEngine.Debug.LogWarning("[PhoneWeb] bad message: " + e.Message); } message.SetLength(0); } } catch (OperationCanceledException) { } catch (WebSocketException) { Lost(link); } catch (ObjectDisposedException) { } } static readonly byte[] FrameMark = Encoding.ASCII.GetBytes("\"Page.screencastFrame\""), DataMark = Encoding.ASCII.GetBytes("\"data\":\""), SessionMark = Encoding.ASCII.GetBytes("\"sessionId\":"); static readonly sbyte[] Sextet = MakeSextets(); static sbyte[] MakeSextets() { var t = new sbyte[256]; for (int i = 0; i < 256; i++) t[i] = -1; const string abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (int i = 0; i < 64; i++) t[abc[i]] = (sbyte)i; return t; } static int Find(byte[] b, int from, int to, byte[] what) { for (int i = from; i <= to - what.Length; i++) { int k = 0; while (k < what.Length && b[i + k] == what[k]) k++; if (k == what.Length) return i; } return -1; } void Handle(Link link, byte[] b, int n) { // video frames are nearly all of the traffic, and big: picked out of the bytes, with no strings made of them if (Find(b, 0, Math.Min(n, 64), FrameMark) >= 0) { TakeFrame(b, n); return; } var m = JsonUtility.FromJson(Encoding.UTF8.GetString(b, 0, n)); if (m.id != 0) { if (_wait.TryRemove(m.id, out var done)) done.TrySetResult(m.result?.result?.value); if (m.id == _navId && !string.IsNullOrEmpty(m.result?.errorText)) _navError = m.result.errorText; if (m.id == _winAsk && m.result != null && m.result.windowId > 0) { _winId = m.result.windowId; Bounds(); } } else if (m.method == "Page.frameNavigated") { if (string.IsNullOrEmpty(m.@params?.frame?.parentId)) { var u = m.@params?.frame?.url; // the blank page from going home, landing after the next site was asked for if (u == "about:blank" && (_wanted != null || _pending != null)) return; _url = u; } } else if (m.method == "Page.navigatedWithinDocument") _url = m.@params?.url; else if (m.method == "Page.frameStartedLoading") { if (m.@params?.frameId == link.Tab) _loading = true; } else if (m.method == "Page.frameStoppedLoading") { if (m.@params?.frameId == link.Tab) _loading = false; } else if (m.method == "Page.javascriptDialogOpening") Cmd("Page.handleJavaScriptDialog", "{\"accept\":true}"); } void TakeFrame(byte[] b, int n) { int a = Find(b, 0, n, DataMark) + DataMark.Length; int e = a; while (e < n && b[e] != (byte)'"') e++; int s = -1; for (int i = n - SessionMark.Length; i > e && s < 0; i--) if (Find(b, i, i + SessionMark.Length, SessionMark) == i) s = i + SessionMark.Length; int session = 0; while (s > 0 && s < n && b[s] >= (byte)'0' && b[s] <= (byte)'9') session = session * 10 + b[s++] - '0'; if (!_spare.TryTake(out var shot)) shot = new Shot(); int need = (e - a) / 4 * 3 + 3; if (shot.Jpeg.Length < need) shot.Jpeg = new byte[need * 5 / 4]; var o = shot.Jpeg; int w = 0, bits = 0, count = 0; for (int i = a; i < e; i++) { int v = Sextet[b[i]]; if (v < 0) continue; bits = (bits << 6) | v; if (++count == 4) { o[w++] = (byte)(bits >> 16); o[w++] = (byte)(bits >> 8); o[w++] = (byte)bits; bits = 0; count = 0; } } if (count == 3) { o[w++] = (byte)(bits >> 10); o[w++] = (byte)(bits >> 2); } else if (count == 2) o[w++] = (byte)(bits >> 4); // what's left of a bigger frame after the end of this one is past the JPEG's own end marker, where nothing reads it shot.Session = session; Interlocked.Increment(ref _frames); var old = Interlocked.Exchange(ref _shot, shot); if (old != null) Ack(old); } void Lost(Link link) { if (link != _link || link.Stop.IsCancellationRequested) return; link.Ready = false; _died = true; } /// Closed properly, so the logins from this session make it to disk. The game doesn't wait for it, unless it's quitting. public void Close() => Close(true); public void Close(bool quitting) { Application.quitting -= Close; var link = _link; _link = null; _page = false; _pending = _wanted = _last = null; _url = null; _loading = false; if (link == null) return; if (link.Ready) { link.Ready = false; Send(link, "Browser.close", "{}"); if (!quitting) { Task.Run(() => { try { link.Proc?.WaitForExit(4000); } catch (InvalidOperationException) { } Drop(link); }); return; } try { link.Proc?.WaitForExit(1500); } catch (InvalidOperationException) { } } Drop(link); } void Drop(Link link) { if (link == null) return; link.Ready = false; link.Stop.Cancel(); link.Out.CompleteAdding(); try { if (link.Proc != null && !link.Proc.HasExited) link.Proc.Kill(); } catch (InvalidOperationException) { } catch (System.ComponentModel.Win32Exception) { } if (link.Job != IntPtr.Zero) CloseHandle(link.Job); foreach (var w in _wait.Values) w.TrySetResult(null); _wait.Clear(); } // ───────────────────────── never outlive the game, even after a crash ───────────────────────── [StructLayout(LayoutKind.Sequential)] struct BasicLimits { public long a, b; public uint flags; public UIntPtr c, d; public uint e; public UIntPtr f; public uint g, h; } [StructLayout(LayoutKind.Sequential)] struct IoCounters { public ulong a, b, c, d, e, f; } [StructLayout(LayoutKind.Sequential)] struct ExtendedLimits { public BasicLimits basic; public IoCounters io; public UIntPtr a, b, c, d; } [DllImport("kernel32", SetLastError = true)] static extern IntPtr CreateJobObject(IntPtr attributes, string name); [DllImport("kernel32", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr job, int kind, ref ExtendedLimits info, int size); [DllImport("kernel32", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); [DllImport("kernel32", SetLastError = true)] static extern bool CloseHandle(IntPtr handle); static void TieToGame(Link link) { const int ExtendedLimitInformation = 9; const uint KillOnJobClose = 0x2000; link.Job = CreateJobObject(IntPtr.Zero, null); if (link.Job == IntPtr.Zero) return; var info = new ExtendedLimits { basic = new BasicLimits { flags = KillOnJobClose } }; if (SetInformationJobObject(link.Job, ExtendedLimitInformation, ref info, Marshal.SizeOf())) AssignProcessToJobObject(link.Job, link.Proc.Handle); } } }