{
  "id": "files",
  "kind": "recipe",
  "tags": [
    "device"
  ],
  "title": "Files, sharing and printing",
  "note": "Ask the capability, not the platform. Phones, Windows 10+ and the Mac have the picker and the share sheet; Linux has no share sheet; a browser has the picker always and the sheet only sometimes. Printing takes a PDF, and every platform's own dialog does the rest.",
  "className": "R31Files",
  "package": "dev.cf.recipe",
  "doc": "<p>Choosing a file, sharing it, saving it and printing — and asking first whether this platform can.</p>\n\n<p>These two are the clearest case in the framework of a capability that is <b>not</b> a property\nof the platform. macOS has both since 29/09/2026, through AppKit's own share menu, and Windows 10+\nsince 01/10/2026, through WinRT's DataTransferManager; Linux has a file dialog and no share sheet.\nThe browser has a picker always and a share sheet only in\nsome browsers, over HTTPS. So \"am I on the web?\" is the wrong question, and\n<code>isSupported</code> is the right one — it is answered at runtime, per capability,\nand two browsers on the same machine can answer it differently.</p>\n\n<p>The picker is <b>asynchronous, and has to be</b>: the web build is single-threaded JavaScript,\nso a blocking file dialog cannot exist on one of the four platforms. The callback arrives on the\npaint thread, so it may touch the UI directly, as it does below.</p>\n\n<p>The cancel is not an error and not a null: <code>open</code> answers with an\n<b>empty array</b>. That is one branch, always present, and forgetting it is what produces a\nscreen that appears to do nothing when the user backs out of the dialog.</p>",
  "api": [
    {
      "name": "Button",
      "doc": "/docs/ui/widgets/button"
    },
    {
      "name": "Capabilities",
      "doc": null
    },
    {
      "name": "Capability",
      "doc": null
    },
    {
      "name": "Card",
      "doc": null
    },
    {
      "name": "Component",
      "doc": null
    },
    {
      "name": "Debug",
      "doc": null
    },
    {
      "name": "FileChooser",
      "doc": null
    },
    {
      "name": "Gap",
      "doc": null
    },
    {
      "name": "GridLayout",
      "doc": null
    },
    {
      "name": "Label",
      "doc": "/docs/ui/widgets/label"
    },
    {
      "name": "MaterialIcon",
      "doc": null
    },
    {
      "name": "PalColor",
      "doc": null
    },
    {
      "name": "Pdf",
      "doc": null
    },
    {
      "name": "PlatformUtils",
      "doc": null
    },
    {
      "name": "Screen",
      "doc": null
    },
    {
      "name": "Styles",
      "doc": null
    },
    {
      "name": "VerticalLayout",
      "doc": null
    },
    {
      "name": "Widgets",
      "doc": null
    }
  ],
  "files": [
    {
      "path": "dev/cf/recipe/R31Files.java",
      "name": "R31Files.java",
      "code": "package dev.cf.recipe;\n\nimport dev.cf.Tones;\n\nimport dev.crossfly.Capability;\nimport dev.crossfly.PlatformUtils;\nimport dev.crossfly.capability.Capabilities;\nimport dev.crossfly.capability.FileChooser;\nimport dev.crossfly.util.Debug;\nimport dev.crossfly.util.pdf.Pdf;\nimport dev.crossfly.ui.*;\nimport dev.crossfly.ui.color.*;\nimport dev.crossfly.ui.graphics.*;\nimport dev.crossfly.ui.layout.*;\nimport dev.crossfly.ui.style.*;\n\nimport static dev.crossfly.ui.Widgets.*;\n\n/**\n * Choosing a file, sharing it, saving it and printing — and asking first whether this platform can.\n *\n * <p>These two are the clearest case in the framework of a capability that is <b>not</b> a property\n * of the platform. macOS has both since 29/09/2026, through AppKit's own share menu, and Windows 10+\n * since 01/10/2026, through WinRT's DataTransferManager; Linux has a file dialog and no share sheet.\n * The browser has a picker always and a share sheet only in\n * some browsers, over HTTPS. So \"am I on the web?\" is the wrong question, and\n * {@link PlatformUtils#isSupported} is the right one — it is answered at runtime, per capability,\n * and two browsers on the same machine can answer it differently.</p>\n *\n * <p>The picker is <b>asynchronous, and has to be</b>: the web build is single-threaded JavaScript,\n * so a blocking file dialog cannot exist on one of the four platforms. The callback arrives on the\n * paint thread, so it may touch the UI directly, as it does below.</p>\n *\n * <p>The cancel is not an error and not a null: {@link FileChooser#open} answers with an\n * <b>empty array</b>. That is one branch, always present, and forgetting it is what produces a\n * screen that appears to do nothing when the user backs out of the dialog.</p>\n */\npublic class R31Files extends Recipe\n{\n   private Label answer;\n\n   /** The last pick, kept so the share row has something to hand over. */\n   private FileChooser.PickedFile chosen;\n\n   public String title()\n   {\n      return \"Files, sharing and printing\";\n   }\n\n   public String note()\n   {\n      return \"Ask the capability, not the platform. Phones, Windows 10+ and the Mac have the picker and\"\n         + \" the share sheet; Linux has no share sheet; a browser has the picker always and the sheet only\"\n         + \" sometimes.\"\n         + \" Printing takes a PDF, and every platform's own dialog does the rest.\";\n   }\n\n   public void build(Component body) throws Exception\n   {\n      answer = label(\"Nothing chosen yet.\", 1f, false, Styles.captionColor, Position.START);\n      answer.testTag(\"files.answer\");\n      // Pinned below the scrolling body, so the answer stays in view (see Recipe.pin).\n      pin(answer);\n\n      row(body, \"files.choose\", 0xE2C8, \"Choose a file\", PlatformUtils.isSupported(Capability.FILE_PICKER),\n         () -> Capabilities.files()\n            .open(new FileChooser.Options().title(\"Choose a file\").extensions(\"pdf\", \"png\", \"jpg\", \"txt\"),\n               files ->\n               {\n                  // The empty array IS the cancel. No null to check, and no exception to catch.\n                  if (files.length == 0)\n                  {\n                     said(\"Cancelled\");\n                     return;\n                  }\n                  chosen = files[0];\n                  read(chosen);\n               }));\n\n      row(body, \"files.share-link\", 0xE80D, \"Share a link\", PlatformUtils.isSupported(Capability.SHARING),\n         () -> Capabilities.sharing().text(\"CrossFly\", \"https://crossfly.dev\"));\n\n      // Sharing.bytes and not Sharing.file, and the difference is the whole lesson: a file the\n      // user picked has no path on Android (it is a content:// document) and none at all in a\n      // browser, so the path-shaped call cannot serve the most ordinary flow there is — pick\n      // something, then send it. Handing over the content works on every platform that shares.\n      row(body, \"files.share-file\", 0xE2C4, \"Share the chosen file\",\n         PlatformUtils.isSupported(Capability.SHARING), () ->\n         {\n            if (chosen == null)\n            {\n               said(\"Choose a file first\");\n               return;\n            }\n            try\n            {\n               Capabilities.sharing().bytes(\"CrossFly\", chosen.name, chosen.bytes());\n            }\n            catch (Exception e)\n            {\n               said(\"Could not share: \" + e.getMessage());\n            }\n         });\n\n      // Saving is NOT sharing, and the two rows sit together so the difference is visible: sharing\n      // sends content somewhere else and never says where it went; saving puts a file under the\n      // person's own control, with a name they picked, in a place they can find again.\n      row(body, \"files.save\", 0xE161, \"Save a file\",\n         PlatformUtils.isSupported(Capability.SAVE_FILE), () ->\n         {\n            byte[] content = chosen != null ? bytesOf(chosen)\n               : \"Saved by CrossFly.\\n\".getBytes(java.nio.charset.StandardCharsets.UTF_8);\n            String name = chosen != null ? chosen.name : \"crossfly.txt\";\n            String mime = chosen != null ? chosen.mimeType() : \"text/plain\";\n            if (content == null)\n               return;\n            Capabilities.saver()\n               .save(name, mime, content, (saved, error) -> said(saved ? \"Saved \" + name\n                  : error == null ? \"Cancelled\" : \"Could not save: \" + error));\n         });\n\n      // Printing is the third way out, and it takes a PDF because every platform's print system\n      // already speaks PDF -- a receipt generated here and a boleto downloaded from a server\n      // print through the same call.\n      row(body, \"files.print\", 0xE8AD, \"Print a receipt\",\n         PlatformUtils.isSupported(Capability.PRINTING), this::printReceipt);\n   }\n\n   /**\n    * A receipt on an 80 mm roll, built with {@link Pdf} and handed to the system's print dialog.\n    * <p>\n    * The answer has <b>four</b> values and the browser is why: a phone and a desktop say whether\n    * the job was sent or cancelled, and a browser only says that its dialog closed. Treating\n    * {@code CLOSED} as either of the other two would be the app guessing.\n    */\n   private void printReceipt()\n   {\n      Pdf pdf = new Pdf();\n      pdf.page(Pdf.ROLL_80MM_WIDTH, 300);\n      pdf.font(Pdf.COURIER_BOLD, 14).text(12, 270, \"RECEIPT 4471\");\n      // Amounts in reais on purpose: a Brazilian receipt, with the comma as decimal separator.\n      pdf.font(Pdf.COURIER, 10).text(12, 250, \"2 x Specialty coffee R$ 38,00\");\n      pdf.font(Pdf.COURIER, 10).text(12, 235, \"1 x Sugar 1 kg       R$  6,90\");\n      pdf.lineWidth(1).line(12, 225, 215, 225);\n      pdf.font(Pdf.COURIER_BOLD, 11).text(12, 208, \"Total               R$ 44,90\");\n      Capabilities.printing().print(\"Receipt 4471\",pdf.build(), (result, error) ->\n      {\n         switch (result)\n         {\n            case SENT:\n               said(\"Sent to the printer\");\n               break;\n            case CANCELLED:\n               said(\"Cancelled\");\n               break;\n            case CLOSED:\n               said(\"The print dialog closed (this platform does not say whether it printed)\");\n               break;\n            default:\n               said(\"Could not print: \" + error);\n         }\n      });\n   }\n\n   /**\n    * The chosen file's bytes, or null after saying why not.\n    *\n    * @param f the chosen file\n    * @return its content, or null\n    */\n   private byte[] bytesOf(FileChooser.PickedFile f)\n   {\n      try\n      {\n         return f.bytes();\n      }\n      catch (Exception e)\n      {\n         said(\"Could not read \" + f.name + \": \" + e.getMessage());\n         return null;\n      }\n   }\n\n   /**\n    * Proves the pick is real by reading it, which is the part that differs most between platforms:\n    * a path on the desktop and on iOS, a content resolver on Android, an ArrayBuffer in a browser.\n    */\n   private void read(FileChooser.PickedFile f)\n   {\n      try\n      {\n         int bytes = f.bytes().length;\n         said(f.name + \" — \" + bytes + \" bytes read, \" + f.mimeType());\n      }\n      catch (Exception e)\n      {\n         said(f.name + \" — could not be read: \" + e.getMessage());\n      }\n   }\n\n   /**\n    * A row per capability. The button carries a {@code testTag} so a TestCase can drive it — which\n    * on a phone is the only way in, since the whole UI is drawn on one GL surface and a device\n    * automation tool sees a single view with no children inside it.\n    *\n    * @param tag       stable name for the button, for tests\n    * @param icone     the Material glyph on the tile\n    * @param name      the row's label\n    * @param available whether the platform has this capability\n    * @param go        what the button does\n    */\n   private void row(Component body, String tag, int icone, String name, boolean available,\n      Runnable go) throws Exception\n   {\n      Card c = new Card();\n      c.setLayout(new GridLayout(Position.START, Position.CENTER));\n      c.getStyle()\n         .outgap(Gap.ofFont(0, 0, 0, .5f));\n\n      PalColor tom = available ? Tones.accent() : Tones.danger();\n\n      Component text = new Component();\n      text.setLayout(new VerticalLayout(Position.START, Position.START));\n      text.add(LAY_AUTO, label(name, 1.2f, true, Styles.textColor, Position.START));\n      text.add(LAY_AUTO, label(available ? \"Ready\" : \"Not on this platform\", 1f, true, tom,\n         Position.START));\n\n      Button b = new Button(MaterialIcon.of(available ? 0xE5C8 : 0xE002, 1.4f));\n      b.setEnabled(available);\n      b.testTag(tag);\n      b.onAction(e -> go.run());\n\n      c.add(0f, 1f, 0f, Tones.tile(icone, tom), outgap(text, .6f, 0, 0, 0), b);\n      body.add(LAY_AUTO, c);\n   }\n\n   private void said(String what)\n   {\n      // Also to the log, and not only to the label. This screen is the one people drive by hand on\n      // a device or over ssh to find out whether a native capability actually worked -- and a\n      // verdict that exists only as pixels is unreadable exactly then. It cost a round trip here:\n      // a save that left no file on disk, with no way to tell a cancel from a failure.\n      Debug.log(\"[files] \" + what);\n      answer.setText(what);\n      answer.invalidateMeasure(); // the pinned band must grow with it (see Recipe.pin)\n      Screen.repaint();\n   }\n}\n"
    }
  ],
  "lines": 249,
  "sharedFiles": [
    {
      "path": "dev/cf/recipe/Recipe.java",
      "name": "Recipe.java",
      "code": "package dev.cf.recipe;\n\nimport dev.cf.*;\nimport dev.crossfly.ui.*;\nimport dev.crossfly.ui.graphics.*;\nimport dev.crossfly.ui.layout.*;\nimport dev.crossfly.ui.skin.*;\nimport dev.crossfly.ui.style.*;\n\nimport static dev.crossfly.ui.Widgets.*;\n\n/**\n * Base of a <b>recipe</b>: one screen that shows one thing, and nothing else.\n *\n * <p>A recipe is not a sample. A sample shows a component with all its knobs; a recipe answers a\n * question somebody actually has — \"how do I put a filter sheet over a list?\", \"how do I make this\n * follow the theme?\" — in as few lines as it takes, so the answer can be read in one screen and\n * copied without editing.</p>\n *\n * <p>That is the whole design constraint: <b>the boilerplate lives here, the substance lives in the\n * subclass.</b> A recipe that spends twenty lines building a title bar teaches the title bar.</p>\n *\n * <p>Write one as:</p>\n *\n * <pre>\n * public class MyRecipe extends Recipe\n * {\n *    public String title() { return \"What this shows\"; }\n *    public String note()  { return \"The one sentence worth knowing.\"; }\n *\n *    public void build(Component body) throws Exception\n *    {\n *       body.add(LAY_AUTO, new Button(\"Tap\"));\n *    }\n * }\n * </pre>\n */\npublic abstract class Recipe extends SampleWindow implements Described\n{\n   @Override\n   public abstract String title();\n\n   /**\n    * The one thing a reader should take away — printed above the recipe, in caption tone.\n    *\n    * @return the note, or null for none\n    */\n   @Override\n   public String note()\n   {\n      return null;\n   }\n\n   /**\n    * Builds the recipe.\n    *\n    * @param body a vertical, scrollable container with sensible padding — add to it and stop\n    * @throws Exception when building fails\n    */\n   public abstract void build(Component body) throws Exception;\n\n   @Override\n   public void onAdd(boolean firstTime) throws Exception\n   {\n      addTopBar(title());\n\n      // The page, not the surface. addTopBar just set fullscreenColor to the surface,\n      // and on a white page a white card has no edges — see Tones.page(). Re-derived on restyle so\n      // a dark-mode flip does not leave the light page behind.\n      fullscreenColor = Tones.page();\n      onRestyle(() -> fullscreenColor = Tones.page());\n\n      contents.setLayout(new VerticalLayout(Position.START, Position.START));\n      contents.getStyle()\n         .ingap(Gap.ofFont(1f, 1f, 1f, 1f));\n\n      String n = note();\n      if (n != null)\n         contents.add(LAY_AUTO, outgap(nota(n), 0, 0, 0, 1f));\n\n      Component body = new Component();\n      body.setLayout(new VerticalLayout(Position.START, Position.START));\n      body.setScrollable(ScrollDirection.VERTICAL);\n      body.testTag(\"recipe.body\");\n      contents.add(LAY_FILL, body);\n      build(body);\n      if (pinned != null)\n      {\n         // Measured again once its labels have sizes: the band's AUTO height is taken in the first\n         // layout, before them, and on the iPhone it showed only its first line - the odometer's\n         // \"No text recognizer on this device.\" was set and never seen (17/10/2026).\n         final Component band = pinned;\n         onUI(band::invalidateMeasure);\n      }\n      if (pinned != null)\n         body.add(LAY_AUTO, new Component()\n         {\n            @Override\n            public int getAutoHeight()\n            {\n               // Room for the last row to scroll clear of the floating band.\n               return pinned.getAutoHeight();\n            }\n         });\n   }\n\n   /**\n    * The note, as a tinted band rather than three lines of grey.\n    *\n    * <p>It is the one sentence the reader is meant to leave with, and it used to be the least\n    * legible thing on the screen: caption-coloured, caption-sized, indistinguishable from the\n    * captions further down that are only labels. A tone and a glyph cost nothing here — nobody has\n    * to read the band to know what it is.</p>\n    *\n    * @param n the note text\n    * @return the band\n    * @throws Exception when building fails\n    */\n   /**\n    * Pins {@code c} to the bottom of the screen, in a band that FLOATS over the scrolling body: it\n    * stays on screen however far the body is scrolled, and the body scrolls underneath it. That is the\n    * place a recipe says what just happened. An answer at the top of the body went out of view as soon\n    * as the person scrolled down to the button that produced it (14/10/2026).\n    * <p>\n    * The band is 80% OPAQUE (the surface at alpha 0xCC), as the user asked; it floats rather than\n    * sitting below the body because a transparency with nothing behind it cannot be seen -- the first\n    * version had the band under the body, and the person saw a plain bar. The body gets a spacer as\n    * tall as the band at its end, so its last row can still scroll clear of it.\n    *\n    * @param c the component to pin, usually the answer label\n    * @return {@code c}, to chain\n    * @throws Exception if the layout refuses\n    */\n   protected <T extends Component> T pin(T c) throws Exception\n   {\n      Component band = new Component();\n      band.setLayout(new VerticalLayout(Position.START, Position.START));\n      band.style(Skin.get()\n         .card()\n         .backColor(Styles.backColor.withAlpha(0xCC))\n         .borderColor(Styles.borderColor.withAlpha(0x33))\n         .borderRadius(0)\n         .shadow(0, 0, 0, 0)\n         .ingap(Gap.ofFont(1f, 1f, 1f, 1.2f))\n         .outgap(Gap.ofFont(0)));\n      band.add(LAY_AUTO, c);\n      // Floated: positioned at the bottom, full width, over whatever the body has there.\n      band.setRelativeBounds(Relative.START, Relative.END, Relative.FULL, Relative.AUTO);\n      contents.add(LAY_AUTO, band);\n      pinned = band;\n      return c;\n   }\n\n   /** The floating band {@link #pin} made, or null; the body ends in a spacer as tall as it. */\n   private Component pinned;\n\n   private Component nota(String n) throws Exception\n   {\n      Component band = new Component();\n      band.setLayout(new GridLayout(Position.START, Position.START));\n      band.style(Skin.get()\n         .card()\n         .backColor(Tones.accent().withAlpha(0x16))\n         .borderColor(Tones.accent().withAlpha(0x4A))\n         .shadow(0, 0, 0, 0)\n         .outgap(Gap.ofFont(0)));\n      // 0xE88E is the outlined \"info\". The glyph column hugs; the text takes the rest and wraps.\n      // The weights are GridLayout's own — 0f hugs, 1f takes what is left. LAY_FILL belongs to the\n      // vertical and horizontal layouts and means nothing here: it collapsed the text to nothing.\n      band.add(LAY_AUTO, 1f, matglyph(0xE88E, Tones.accent(), 1.05f),\n         outgap(label(n, 1f, false, secondary(), Position.START), .5f, 0, 0, 0));\n      return band;\n   }\n}\n"
    },
    {
      "path": "dev/cf/SampleWindow.java",
      "name": "SampleWindow.java",
      "code": "package dev.cf;\n\nimport dev.crossfly.ui.*;\nimport dev.crossfly.ui.graphics.*;\nimport dev.crossfly.ui.layout.*;\nimport dev.crossfly.ui.style.*;\n\nimport static dev.cf.sample.CrossFlySamplesColors.*;\n\n/**\n * Base class for all CrossFly sample windows.\n * <p>\n * Provides common infrastructure:\n * <ul>\n *   <li>Shared color palette and styles from {@link dev.cf.sample.CrossFlySamplesColors}</li>\n *   <li>{@link #addTopBar(String, Button...)} — standard deep-indigo top bar with back button</li>\n *   <li>{@link #barButton(String, Runnable)} — helper to create icon buttons for the bar</li>\n * </ul>\n *\n * <h3>Usage</h3>\n * <pre>\n * public class MySample extends SampleWindow {\n *     public void onAdd(boolean firstTime) throws Exception {\n *         if (!firstTime) return;\n *         initWindow();\n *         addTopBar(\"My Sample\");\n *         // ... add content\n *     }\n * }\n * </pre>\n */\npublic abstract class SampleWindow extends Window\n{\n   /** The main content area of the window, added by {@link #addTopBar(String, Button...)}, for subclasses to add their content into. */\n   protected Component contents;\n\n   // ─── Top bar ─────────────────────────────────────────────────────────────\n\n   /**\n    * Builds and adds a standard top bar with a back (←) button on the left,\n    * a centered title, and any optional extra buttons on the right.\n    *\n    * @param title        the text shown in the bar\n    * @param rightButtons zero or more icon buttons placed aligned to the right\n    * @throws Exception if component construction fails\n    */\n   protected void addTopBar(String title, Button... rightButtons) throws Exception\n   {\n      fullscreenColor = Styles.backColor.color();\n      setLayout(new VerticalLayout());\n      add(0f, buildTopBar(title, rightButtons));\n      add(LAY_FILL, contents = new Component());\n      contents.getStyle()\n         .ingap(Gap.ofFont(0, .5f, 0, .5f));\n   }\n\n   /**\n    * Same as {@link #addTopBar(String, Button...)}, but returns the bar component\n    * instead of adding it, for callers that need to position it manually.\n    *\n    * @param title        the bar title\n    * @param rightButtons optional right-side icon buttons\n    * @return the assembled top-bar {@link Component}\n    * @throws Exception if component construction fails\n    */\n   protected Component buildTopBar(String title, Button... rightButtons) throws Exception\n   {\n      Button btBack = barButton(\"\\ue5c4\", this::hide);   // arrow_back\n      btBack.testTag(\"sample.back\");\n      // Padded on every side, like the bar's right buttons: with none above and below, the target\n      // was the arrow itself, too small to hit on a small phone (iPhone 5s, 17/10/2026).\n      btBack.getStyle()\n         .ingap(Gap.ofFont(.75f))\n         .outgap(Gap.ofFont(0, 0, .25f, 0));\n\n      Component bar = new Component().style(barStyle);\n      bar.setLayout(new GridLayout(Position.START, Position.CENTER));\n\n      int n = 2 + rightButtons.length;\n      Object[] params = new Object[n * 2];\n      params[0] = 0f;\n      params[1] = 1f;\n      for (int i = 0; i < rightButtons.length; i++)\n         params[2 + i] = 0f;\n      params[n] = btBack;\n      params[n + 1] = new Label(title).style(barTitleStyle);\n      for (int i = 0; i < rightButtons.length; i++)\n      {\n         params[n + 2 + i] = rightButtons[i];\n         rightButtons[i].getStyle()\n            .ingap(Gap.ofFont(.75f));\n      }\n\n      bar.add(params);\n      return bar;\n   }\n\n   /**\n    * Creates a standard bar icon button (transparent, white icon, pressed feedback).\n    *\n    * @param materialIcon the Material Icon unicode codepoint string\n    * @param action       the action to run when the button is tapped\n    * @return the configured {@link Button}\n    */\n   protected Button barButton(String materialIcon, Runnable action)\n   {\n      return new Button(new MaterialIcon(materialIcon)).style(barButtonNormal)\n         .pressedStyle(barButtonPressed)\n         .onAction(e -> action.run());\n   }\n}\n"
    }
  ],
  "page": "https://crossfly.dev/examples/files",
  "run": "https://crossfly.dev/playground/index.html?ex=files",
  "runLocally": "gradlew lwjgl3:run --args=\"classname dev.cf.recipe.R31Files\"",
  "license": "See crossfly.dev for licensing. The code is published to be copied into your own project."
}