A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Share: Copy puts the screenshot on the clipboard, or the post text (Fixes #1238) (#1253)
Beri24e8d441e9f6
diff --git a/changelog.d/1238.md b/changelog.d/1238.mdnew file mode 100644index 000000000..67c30bfc9--- /dev/null+++ b/changelog.d/1238.md@@ -0,0 +1,3 @@+- Share: a Copy button in the Share panel puts the screenshot on the clipboard, or the post text with the itch link+ where the browser refuses the picture, and says which one it copied (or that it could not copy, with the download+ still there), in English and Hebrew (#1238).diff --git a/unity/Assets/Scripts/UI/SharePresenter.cs b/unity/Assets/Scripts/UI/SharePresenter.csindex 7fd5d074f..807a64ef3 100644--- a/unity/Assets/Scripts/UI/SharePresenter.cs+++ b/unity/Assets/Scripts/UI/SharePresenter.cs@@ -11,6 +11,7 @@ namespace Statecraft.Game.UI/// before the panel shows, so the panel is never in the picture. Where the browser can share files, Share opens its share/// sheet with the picture, the post and the itch URL; elsewhere the same button downloads the picture, and the panel then/// shows the X, Facebook, WhatsApp and LinkedIn share links and says to attach the picture, which a link cannot carry.+ /// Copy (#1238) puts the picture on the clipboard, or the post text where the browser refuses the picture, and says which./// <para>While it shows, the root has <see cref="OpenClass"/> and every other part of the UI is disabled, so Tab stays in/// the panel; Close, Esc or Cancel give each part its own state back and the focus back to the button that opened it./// <see cref="Escape"/> is what GameRoot's Escape poll and ScreenNav (TakesEscape) ask first.</para></summary>@@ -23,16 +24,19 @@ namespace Statecraft.Game.UI{ ["x"] = "X", ["facebook"] = "Facebook", ["whatsapp"] = "WhatsApp", ["linkedin"] = "LinkedIn" };readonly VisualElement hudRoot, layer, fallback;- readonly Button go, close, settingsOpen, reportOpen;- readonly Label post;+ readonly Button go, copy, close, settingsOpen, reportOpen;+ readonly Label post, copied;readonly SimBridge bridge; readonly UiText text;readonly Action<Action<byte[]?>> capture;readonly EventCallback<PointerDownEvent> onGoPointer;readonly EventCallback<NavigationSubmitEvent> onGoSubmit;+ readonly EventCallback<PointerDownEvent> onCopyPointer;+ readonly EventCallback<NavigationSubmitEvent> onCopySubmit;readonly EventCallback<NavigationCancelEvent> onCancel;readonly List<Action> unbindSites = new List<Action>();readonly List<(VisualElement part, bool enabled)> covered = new List<(VisualElement, bool)>();Button? opener;+ IVisualElementScheduledItem? copyPoll;bool capturing, canShareFiles, disposed;int closedAt = -1;@@ -46,6 +50,8 @@ namespace Statecraft.Game.UIfallback = layer.Q("share-fallback");go = layer.Q<Button>("share-go"); close = layer.Q<Button>("share-close");post = layer.Q<Label>("share-post");+ copy = layer.Q<Button>("share-copy"); copied = layer.Q<Label>("share-copied");+ copy.text = text["share.copy"];settingsOpen = root.Q<Button>("settings-share"); reportOpen = root.Q<Button>("turn-report-share");settingsOpen.text = reportOpen.text = text["share.open"];layer.Q<Label>("share-title").text = text["share.title"];@@ -58,6 +64,10 @@ namespace Statecraft.Game.UIonGoSubmit = _ => Go();go.RegisterCallback(onGoPointer, TrickleDown.TrickleDown);go.RegisterCallback(onGoSubmit, TrickleDown.TrickleDown);+ onCopyPointer = e => { if (e.button == 0) Copy(); };+ onCopySubmit = _ => Copy();+ copy.RegisterCallback(onCopyPointer, TrickleDown.TrickleDown);+ copy.RegisterCallback(onCopySubmit, TrickleDown.TrickleDown);settingsOpen.clicked += OpenFromSettings;reportOpen.clicked += OpenFromReport;close.clicked += Close;@@ -86,6 +96,8 @@ namespace Statecraft.Game.UIpost.text = ShareShot.Text(text, shown.Date, bridge.State.Turn);go.text = text[canShareFiles ? "share.native" : "share.download"];fallback.style.display = DisplayStyle.None;+ copyPoll?.Pause();+ copied.style.display = DisplayStyle.None;foreach (var unbind in unbindSites) unbind();unbindSites.Clear();foreach (var site in ShareShot.Sites) unbindSites.Add(ExternalLink.Bind(layer.Q<Button>("share-" + site), ShareShot.IntentUrl(site, post.text)));@@ -112,6 +124,33 @@ namespace Statecraft.Game.UIgo.schedule.Execute(() => { if (IsOpen && ShareShot.Failed()) fallback.style.display = DisplayStyle.Flex; }).Every(250).ForDuration(3000);}+ /// <summary>Copy: the browser copies on the release and answers after a promise (ShareShot.jslib), so the panel looks+ /// for the answer as it looks for a refused share sheet, and then says what was copied, or that nothing was.</summary>+ void Copy()+ {+ if (!IsOpen) return;+ copyPoll?.Pause();+ copied.style.display = DisplayStyle.None;+ ShareShot.Copy(post.text);+ // A press whose release never reached the browser (shorter than a frame, or another press first) copies+ // nothing and stays Pending: after a few seconds the panel says so rather than staying silent.+ var giveUpAt = UnityEngine.Time.realtimeSinceStartup + 4.5f;+ copyPoll = copy.schedule.Execute(() =>+ {+ var result = ShareShot.Copied();+ if (result == ShareShot.CopyResult.Pending && UnityEngine.Time.realtimeSinceStartup >= giveUpAt) result = ShareShot.CopyResult.Failed;+ if (!IsOpen || result == ShareShot.CopyResult.Pending) return;+ copied.text = text[result switch+ {+ ShareShot.CopyResult.Picture => "share.copied_picture",+ ShareShot.CopyResult.Text => "share.copied_text",+ _ => "share.copy_failed",+ }];+ copied.style.display = DisplayStyle.Flex;+ copyPoll?.Pause();+ }).Every(250).ForDuration(5000);+ }+public void Close(){if (!IsOpen) return;@@ -139,6 +178,9 @@ namespace Statecraft.Game.UIforeach (var unbind in unbindSites) unbind();go.UnregisterCallback(onGoPointer, TrickleDown.TrickleDown);go.UnregisterCallback(onGoSubmit, TrickleDown.TrickleDown);+ copyPoll?.Pause();+ copy.UnregisterCallback(onCopyPointer, TrickleDown.TrickleDown);+ copy.UnregisterCallback(onCopySubmit, TrickleDown.TrickleDown);settingsOpen.clicked -= OpenFromSettings;reportOpen.clicked -= OpenFromReport;close.clicked -= Close;diff --git a/unity/Assets/Scripts/UI/ShareShot.cs b/unity/Assets/Scripts/UI/ShareShot.csindex 4eb98859e..2692062a9 100644--- a/unity/Assets/Scripts/UI/ShareShot.cs+++ b/unity/Assets/Scripts/UI/ShareShot.cs@@ -29,6 +29,11 @@ namespace Statecraft.Game.UIpublic static Action<string, string> Share = DefaultShare;/// <summary>True when the browser refused the share sheet (not a cancel) and the picture downloaded instead.</summary>public static Func<bool> Failed = DefaultFailed;+ /// <summary>What Copy (#1238) put on the clipboard: Pending until the browser has answered.</summary>+ public enum CopyResult { Pending, Picture, Text, Failed }+ /// <summary>Copies the kept picture on the player's release, or the post text if the browser refuses the picture.</summary>+ public static Action<string> Copy = DefaultCopy;+ public static Func<CopyResult> Copied = DefaultCopied;/// <summary>The post, in the UI's language, with the in-game date and turn and the itch URL.</summary>public static string Text(UiText text, string date, int turn) => text.Format("share.post", date, turn, Itch);@@ -103,6 +108,10 @@ namespace Statecraft.Game.UIpublic static void DefaultShare(string text, string url) => StatecraftShareOnRelease(text, url);[System.Runtime.InteropServices.DllImport("__Internal")] static extern int StatecraftShareFailed();public static bool DefaultFailed() => StatecraftShareFailed() == 1;+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftShareCopyOnRelease(string text);+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern int StatecraftShareCopied();+ public static void DefaultCopy(string text) => StatecraftShareCopyOnRelease(text);+ public static CopyResult DefaultCopied() => (CopyResult)StatecraftShareCopied();#elsestatic byte[]? kept; static string keptName = "";public static void DefaultKeep(byte[] png, string name) { kept = png; keptName = name; }@@ -117,6 +126,10 @@ namespace Statecraft.Game.UIFile.WriteAllBytes(path, kept);Debug.Log("SHARE picture saved to " + path);}+ static CopyResult copied;+ /// <summary>Outside the browser Unity can only put text on the clipboard: the post.</summary>+ public static void DefaultCopy(string text) { GUIUtility.systemCopyBuffer = text; copied = CopyResult.Text; }+ public static CopyResult DefaultCopied() => copied;#endif}}diff --git a/unity/Assets/Scripts/UI/ShareShot.jslib b/unity/Assets/Scripts/UI/ShareShot.jslibindex 07b00565f..6910c415e 100644--- a/unity/Assets/Scripts/UI/ShareShot.jslib+++ b/unity/Assets/Scripts/UI/ShareShot.jslib@@ -6,6 +6,10 @@// An unused arm disarms itself after 1.5 s, and a new press on the canvas (pointerdown) disarms it at once: a tap shorter// than a frame is released before Unity arms the listener, and a stray click would otherwise share or download (#1182// review, as on #1178). Nothing leaves the page unless the player shares or downloads it.+// Copy (#1238) arms the same kind of release listener; on the release it writes the kept picture to the clipboard, and+// where the browser refuses the picture (no ClipboardItem or no image/png, a denied permission, an iframe without+// clipboard-write) it copies the post text instead, then through a hidden textarea (execCommand), which some iframes+// still allow. StatecraftShareCopied tells the panel which one landed: 1 the picture, 2 the text, 3 neither, 0 not yet.mergeInto(LibraryManager.library, {StatecraftShareKeep: function (pngPtr, length, namePtr) {var bytes = HEAPU8.slice(pngPtr, pngPtr + length);@@ -62,4 +66,55 @@ mergeInto(LibraryManager.library, {window.statecraftShareDisarm = disarm;timer = setTimeout(disarm, 1500);},+ StatecraftShareCopied: function () { return window.statecraftShareCopied || 0; },+ StatecraftShareCopyOnRelease: function (textPtr) {+ var text = UTF8ToString(textPtr);+ if (typeof window === "undefined") return;+ if (window.statecraftShareDisarm) window.statecraftShareDisarm();+ var canvas = document.querySelector("#unity-canvas") || document;+ var timer;+ var disarm = function () {+ clearTimeout(timer);+ canvas.removeEventListener("pointerup", go);+ canvas.removeEventListener("pointerdown", disarm);+ document.removeEventListener("keyup", go);+ window.statecraftShareDisarm = null;+ };+ var done = function (result) { window.statecraftShareCopied = result; };+ // The textarea takes the focus for the copy; the game's canvas gets it back, or its keys stop working.+ var legacyCopy = function () {+ var focused = document.activeElement, area = document.createElement("textarea"), ok = false;+ area.value = text;+ area.setAttribute("readonly", "");+ area.style.position = "fixed"; area.style.opacity = "0";+ document.body.appendChild(area);+ area.select();+ try { ok = document.execCommand("copy"); } catch (e) {}+ area.remove();+ if (focused && focused.focus) focused.focus();+ return ok;+ };+ var copyText = function () {+ var write;+ try { write = navigator.clipboard && navigator.clipboard.writeText ? navigator.clipboard.writeText(text) : Promise.reject(); }+ catch (e) { write = Promise.reject(e); } // some browsers throw at once instead of rejecting+ write.then(function () { done(2); }, function () { done(legacyCopy() ? 2 : 3); });+ };+ var go = function () {+ disarm();+ var file = window.statecraftShareFile;+ var picture = file && navigator.clipboard && navigator.clipboard.write && typeof ClipboardItem !== "undefined"+ && !(ClipboardItem.supports && !ClipboardItem.supports("image/png"));+ if (!picture) { copyText(); return; }+ try { navigator.clipboard.write([new ClipboardItem({ "image/png": file })]).then(function () { done(1); }, copyText); }+ catch (e) { copyText(); }+ };+ // Reset on the press, as statecraftShareFailed is: the panel starts asking right after it.+ window.statecraftShareCopied = 0;+ canvas.addEventListener("pointerup", go);+ canvas.addEventListener("pointerdown", disarm);+ document.addEventListener("keyup", go);+ window.statecraftShareDisarm = disarm;+ timer = setTimeout(disarm, 1500);+ },});diff --git a/unity/Assets/Tests/EditMode/ShareShotTests.cs b/unity/Assets/Tests/EditMode/ShareShotTests.csindex 8a0f66d0d..d542ea0b8 100644--- a/unity/Assets/Tests/EditMode/ShareShotTests.cs+++ b/unity/Assets/Tests/EditMode/ShareShotTests.cs@@ -184,6 +184,86 @@ public class ShareShotTests}}+ /// <summary>#1238: Copy asks the browser once, on the player's press, to copy the picture; the browser falls back to the+ /// post text (with the itch link) and reports which one landed, or that neither did (ShareShot.jslib, in that order).+ /// The panel says which, in both languages, polling ShareShot.Copied as it polls Failed; nothing shows while the copy+ /// is still pending, and on a failure the Share or Download button stays where it was. The order itself (picture, then+ /// text, then the error) lives in the jslib's promises, which an edit-mode test cannot run; the PR's browser check+ /// covers it.</summary>+ [UnityEngine.TestTools.UnityTest]+ public System.Collections.IEnumerator CopySaysWhetherThePictureOrTheTextWasCopied(+ [Values(ShareShot.CopyResult.Picture, ShareShot.CopyResult.Text, ShareShot.CopyResult.Failed)] ShareShot.CopyResult result,+ [Values(false, true)] bool hebrew)+ {+ var text = hebrew ? He : En;+ var copies = new List<string>();+ var copied = ShareShot.CopyResult.Pending;+ ShareShot.Keep = (png, name) => { }; ShareShot.Share = (a, b) => { };+ ShareShot.Copy = copies.Add; ShareShot.Copied = () => copied;+ var ui = new UiTestKit();+ try+ {+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);+ using var share = new SharePresenter(ui.Root, bridge, text, done => done(new byte[] { 1 }));+ UiTestKit.Press(ui.Q<Button>("settings-share"));+ var copy = ui.Q<Button>("share-copy");+ var said = ui.Q<Label>("share-copied");+ Assert.IsNotNull(copy, "the panel has a Copy button");+ Assert.AreEqual(text["share.copy"], copy.text);+ Assert.AreEqual(DisplayStyle.None, said.style.display.value, "nothing to say before the press");+ SettingsScreenTests.PressWithPointer(copy);+ CollectionAssert.AreEqual(new[] { ui.Q<Label>("share-post").text }, copies, "one copy, of the post, on the press");+ // The batch editor idles between frames unless asked for one, and the panel's scheduler runs on those frames.+ var until = Time.realtimeSinceStartup + 0.6f;+ while (Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }+ Assert.AreEqual(DisplayStyle.None, said.style.display.value, "still pending after a few looks: nothing yet");+ copied = result;+ until = Time.realtimeSinceStartup + 4f; // the panel looks every 250 ms+ while (said.style.display.value != DisplayStyle.Flex && Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }+ Assert.AreEqual(DisplayStyle.Flex, said.style.display.value);+ var key = result switch { ShareShot.CopyResult.Picture => "share.copied_picture", ShareShot.CopyResult.Text => "share.copied_text", _ => "share.copy_failed" };+ Assert.AreEqual(text[key], said.text);+ var go = ui.Q<Button>("share-go");+ Assert.IsTrue(go.enabledInHierarchy && go.style.display.value != DisplayStyle.None, "the Share or Download button stays available");+ UiTestKit.Press(ui.Q<Button>("share-close"));+ UiTestKit.Press(ui.Q<Button>("settings-share"));+ Assert.AreEqual(DisplayStyle.None, said.style.display.value, "a new picture, a new copy: the old message goes");+ }+ finally+ {+ ui.Dispose();+ ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.Share = ShareShot.DefaultShare;+ ShareShot.Copy = ShareShot.DefaultCopy; ShareShot.Copied = ShareShot.DefaultCopied;+ }+ }++ /// <summary>A Copy press whose release never reached the browser stays Pending; after a few seconds the panel says+ /// the copy failed instead of staying silent.</summary>+ [UnityEngine.TestTools.UnityTest]+ public System.Collections.IEnumerator ACopyThatNeverAnswersSaysItFailed()+ {+ ShareShot.Keep = (png, name) => { };+ ShareShot.Copy = t => { }; ShareShot.Copied = () => ShareShot.CopyResult.Pending;+ var ui = new UiTestKit();+ try+ {+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);+ using var share = new SharePresenter(ui.Root, bridge, En, done => done(new byte[] { 1 }));+ UiTestKit.Press(ui.Q<Button>("settings-share"));+ SettingsScreenTests.PressWithPointer(ui.Q<Button>("share-copy"));+ var said = ui.Q<Label>("share-copied");+ var until = Time.realtimeSinceStartup + 7f;+ while (said.style.display.value != DisplayStyle.Flex && Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }+ Assert.AreEqual(DisplayStyle.Flex, said.style.display.value);+ Assert.AreEqual(En["share.copy_failed"], said.text);+ }+ finally+ {+ ui.Dispose();+ ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.Copy = ShareShot.DefaultCopy; ShareShot.Copied = ShareShot.DefaultCopied;+ }+ }+/// <summary>The turn report's Share opens the same panel over the report.</summary>[Test]public void TheTurnReportHasAShareButton()diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxmlindex b641886d9..53f63ceda 100644--- a/unity/Assets/UI/Game.uxml+++ b/unity/Assets/UI/Game.uxml@@ -508,12 +508,15 @@</ui:VisualElement></ui:VisualElement><!-- "Share" (#1170, SharePresenter): over everything, the turn report too, after the frame was captured without it.- The share links show only where the browser cannot share the picture itself. Before the toast. -->+ The share links show only where the browser cannot share the picture itself. Copy (#1238) puts the picture, or the+ post text, on the clipboard, and the line under it says which. Before the toast. --><ui:VisualElement name="share-layer" class="share-layer"><ui:VisualElement name="share-panel" class="panel share-panel"><ui:VisualElement class="screen-header"><ui:Label name="share-title" text="Share a picture of the game" class="title" /></ui:VisualElement><ui:Label name="share-post" class="share-post" /><ui:Button name="share-go" class="share-go" />+ <ui:Button name="share-copy" class="share-go" />+ <ui:Label name="share-copied" class="muted share-copied" /><ui:VisualElement name="share-fallback" class="share-fallback"><ui:Label name="share-attach" text="These sites can't take a picture through a link: attach the downloaded picture to your post." class="muted share-attach" /><ui:VisualElement class="row share-sites">diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.ussindex a48598fb6..b8c75cc48 100644--- a/unity/Assets/UI/Statecraft.uss+++ b/unity/Assets/UI/Statecraft.uss@@ -562,6 +562,7 @@ Button.settings-choice-selected { -unity-font-definition: url("project://databas.share-panel { width: 560px; max-width: 100%; max-height: 100%; padding: 18px; background-color: rgb(11, 18, 32); }.share-post, .share-attach { white-space: normal; }.share-go { margin-top: 12px; }+.share-copied { white-space: normal; margin-top: 6px; }.share-attach { margin-top: 12px; }.share-sites { flex-wrap: wrap; margin-top: 6px; }.share-sites > Button { margin: 4px 8px 0 0; }diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex da68d1d0d..d63a575f4 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -123,6 +123,10 @@ share.post: "I'm running Israel in 1948 in Statecraft: Israel, a free open-sourcshare.native: "Share"share.download: "Download the picture"share.attach: "These sites can't take a picture through a link: attach the downloaded picture to your post."+share.copy: "Copy"+share.copied_picture: "Picture copied"+share.copied_text: "Text copied"+share.copy_failed: "Couldn't copy here. Share or download the picture with the button above."event.draft: "DRAFT"start.source: "From the Declaration of the Establishment of the State of Israel (Official Gazette No. 1, 14 May 1948) and its official English translation. Painting: AI-generated."start.recording_credit: "Recording: Ralph Hellinger, Israel State Archives"diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex ce851b1e6..bc5bff9de 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -129,6 +129,14 @@ share.post: "ניהול מדינת ישראל ב־1948 במשחק Statecraft: Isshare.native: "שיתוף"share.download: "הורדת התמונה"share.attach: "האתרים האלה לא מקבלים תמונה דרך קישור: יש לצרף לפוסט את התמונה שהורדה."+# Copy (#1238): the button ("copying"), "the picture was copied", "the text was copied", and the failure ("copying is+# not possible here; the picture can still be shared or downloaded with the button above"). Agent-drafted.+# Approved by Beri, a native speaker, on #1253 (21 Oct 2026).+# For the native reviewer (#564).+share.copy: "העתקה"+share.copied_picture: "התמונה הועתקה"+share.copied_text: "הטקסט הועתק"+share.copy_failed: "לא ניתן להעתיק כאן. אפשר לשתף או להוריד את התמונה בכפתור שלמעלה."event.draft: "טיוטה"start.source: "מתוך ההכרזה על הקמת מדינת ישראל (עיתון רשמי מס׳ 1, 14 במאי 1948) ותרגומה הרשמי לאנגלית. הציור נוצר בבינה מלאכותית."# The recordist's name as the Israel State Archives spells it in its own description of item